Follow Discord
Sweep 20 Nov 2026 · 19:55Z Build v2.1.330 547 read Stable v2.1.323 Latest v2.1.330 Next v2.1.330 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · mcp

One read of Model Context Protocolmcp-20261031T083705Z

2 pages moved out of 359 read.

Pages moved 2 significant first
Pages read 359 in this capture
Captured 08:37 UTC
Corpus hash a5cbfb3ceb60 corpus-hash

What this read moved

1-2 of 2

docs/2026-07-28/develop/build-client Changed · +521 / -246 lines

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 2026
20262026>
20272027> ## System Requirements
20282028>
2029> Before starting, ensure your Linux system meets these requirements:
2030>
2031> * Latest stable version of [Rust and Cargo](https://www.rust-lang.org/tools/install)
2029> Before starting, ensure your system meets these requirements:
2030>
2031> * [Rust and Cargo](https://www.rust-lang.org/tools/install) 1.88 or newer
20322032> * Anthropic API key (Claude)
20332033> * A Python, Node.js, or executable MCP server to connect to
20342034>
from line 2050
20502050> edition = "2024"
20512051>
20522052> [dependencies]
2053> anyhow = "1.0.100"
2054> genai = "0.4.2"
2055> rmcp = { version = "0.8.0", features = ["server", "client", "transport-io", "transport-child-process"] }
2056> tokio = { version = "1.47.1", features = ["full"] }
2057> tracing = "0.1.41"
2058> tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2059> serde_json = "1.0.128"
2053> anyhow = "1.0.104"
2054> jsonschema = "0.59"
2055> # Only the client half of rmcp is needed, over a child-process stdio transport.
2056> rmcp = { version = "3.4", features = [
2057> "client",
2058> "transport-io",
2059> "transport-child-process",
2060> ], default-features = false }
2061> # The Messages API is called directly, which keeps the provider's content
2062> # blocks verbatim. That matters for signed thinking blocks; see request_model.
2063> reqwest = { version = "0.13", features = ["json"] }
2064> serde = { version = "1.0", features = ["derive"] }
2065> serde_json = "1.0.151"
2066> tokio = { version = "1.53", features = ["full"] }
20602067> dotenvy = "0.15.7"
2061> reqwest = "0.12.23"
2062> ```
2063>
2064> The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and child-process transport. This example uses the [`genai`](https://github.com/jeremychone/rust-genai) crate to send requests to Claude and represent tools in the model request.
2068> ```
2069>
2070> The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and the child-process stdio transport. Only its client half is enabled. The client calls the [Messages API](https://docs.anthropic.com/en/api/messages) directly with [`reqwest`](https://docs.rs/reqwest). Calling the API directly keeps the content blocks of each reply verbatim, which matters when a reply contains a signed thinking block. The [`jsonschema`](https://docs.rs/jsonschema) crate validates structured tool results against the schema a tool declares.
20652071>
20662072> ## Setting Up Your API Key
20672073>
from line 2084
20782084> ```bash theme={null}
20792085> echo ".env" >> .gitignore
20802086> ```
2087>
2088> The client loads `.env` when the file exists. Exporting `ANTHROPIC_API_KEY` in the shell works as well.
20812089>
20822090> > [!WARNING]
20832091> >
from line 2097
20892097>
20902098> ### Imports and Client Structure
20912099>
2092> First, add the imports, model constant, and basic client structure:
2100> First, add the imports and constants:
20932101>
20942102> ```rust theme={null}
20952103> use anyhow::{Context, Result, bail};
2096> use genai::Client;
2097> use genai::chat::{
2098> ChatMessage, ChatRequest, ChatResponse, ContentPart, Tool as GenaiTool, ToolResponse,
2104> use jsonschema::Validator;
2105> use rmcp::model::{
2106> CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, Implementation,
2107> ProtocolVersion, Tool as McpTool,
20992108> };
2100> use rmcp::model::{CallToolRequestParam, Tool as McpTool};
2101> use rmcp::service::{RoleClient, RunningService, ServiceExt};
2109> use rmcp::service::{ClientLifecycleMode, ClientServiceExt, RoleClient, RunningService};
21022110> use rmcp::transport::TokioChildProcess;
2103> use serde_json::Value;
2111> use serde::{Deserialize, Serialize};
2112> use serde_json::{Value, json};
2113> use std::collections::HashMap;
2114> use std::time::Duration;
21042115> use tokio::io::{self, AsyncBufReadExt, BufReader};
21052116> use tokio::process::Command;
21062117>
21072118> const MODEL_ANTHROPIC: &str = "claude-opus-5";
2119> /// The model may think before answering, and max_tokens caps thinking
2120> /// plus the reply, so leave room for both.
2121> const MAX_TOKENS: u32 = 10000;
2122> const MAX_TOOL_TURNS: usize = 10;
2123>
2124> const ANTHROPIC_API_BASE: &str = "https://api.anthropic.com";
2125> const ANTHROPIC_VERSION: &str = "2023-06-01";
2126> const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
2127> ```
2128>
2129> `MAX_TOKENS` caps the thinking and the reply together. `MAX_TOOL_TURNS` bounds how many rounds of tool calls one query may take. `REQUEST_TIMEOUT` applies to each request sent to the Messages API.
2130>
2131> Next, add the types for the Messages API and the client structure:
2132>
2133> ```rust theme={null}
2134> /// One turn of the conversation, as the Messages API takes it.
2135> ///
2136> /// `content` is a list of raw blocks rather than typed ones on purpose. An
2137> /// assistant turn is fed straight back on the next request, and Claude requires
2138> /// the blocks it sent to return unchanged -- a thinking block's `signature`
2139> /// included. Reserialising through a narrower type would drop whatever it does
2140> /// not model.
2141> #[derive(Serialize, Clone)]
2142> struct Message {
2143> role: &'static str,
2144> content: Vec<Value>,
2145> }
2146>
2147> impl Message {
2148> fn user(content: Vec<Value>) -> Self {
2149> Message {
2150> role: "user",
2151> content,
2152> }
2153> }
2154>
2155> fn assistant(content: Vec<Value>) -> Self {
2156> Message {
2157> role: "assistant",
2158> content,
2159> }
2160> }
2161> }
2162>
2163> /// A tool as the Messages API declares it, converted from an MCP tool.
2164> #[derive(Serialize, Clone)]
2165> struct ToolDefinition {
2166> name: String,
2167> #[serde(skip_serializing_if = "Option::is_none")]
2168> description: Option<String>,
2169> input_schema: Value,
2170> }
2171>
2172> #[derive(Serialize)]
2173> struct MessagesRequest<'a> {
2174> model: &'a str,
2175> max_tokens: u32,
2176> messages: &'a [Message],
2177> tools: &'a [ToolDefinition],
2178> }
2179>
2180> #[derive(Deserialize)]
2181> struct MessagesResponse {
2182> content: Vec<Value>,
2183> }
2184>
2185> /// The `type` of a content block, when it has one.
2186> fn block_type(block: &Value) -> &str {
2187> block
2188> .get("type")
2189> .and_then(Value::as_str)
2190> .unwrap_or_default()
2191> }
21082192>
21092193> struct MCPClient {
2110> anthropic: Client,
2111> session: Option<RunningService<RoleClient, ()>>,
2112> tools: Vec<GenaiTool>,
2113> }
2114> ```
2115>
2116> The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.
2194> http: reqwest::Client,
2195> session: Option<RunningService<RoleClient, ClientConfig>>,
2196> tools: Vec<ToolDefinition>,
2197> /// Compiled `outputSchema` per tool name. rmcp does not validate results,
2198> /// so this client does it with the `jsonschema` crate.
2199> output_schemas: HashMap<String, Validator>,
2200> }
2201> ```
2202>
2203> `Message` holds the content blocks of one turn as raw `serde_json::Value`s. An assistant turn goes back to the API unchanged on the next request, with any thinking block and its `signature` intact. `ToolDefinition` is a tool as the Messages API declares it. `MCPClient` keeps the HTTP client, the active MCP session, the tools in Messages API form, and one compiled validator per tool that declares an `outputSchema`.
21172204>
21182205> ### Client Initialization
21192206>
2120> Next, initialize the model client and start without an MCP session or tools:
2207> Next, open the `impl MCPClient` block with the constructor. The methods in the following sections go inside this block, which closes after `cleanup`:
21212208>
21222209> ```rust theme={null}
21232210> impl MCPClient {
21242211> fn new() -> Result<Self> {
21252212> Ok(MCPClient {
2126> anthropic: Client::default(),
2213> http: reqwest::Client::builder()
2214> .timeout(REQUEST_TIMEOUT)
2215> .build()
2216> .context("Failed to build HTTP client")?,
21272217> session: None,
21282218> tools: Vec::new(),
2219> output_schemas: HashMap::new(),
21292220> })
21302221> }
2131>
2132> // Additional methods will go here.
2133> }
2134> ```
2135>
2136> `genai::Client::default()` reads the `ANTHROPIC_API_KEY` environment variable when it sends a request.
2222> ```
2223>
2224> `new` builds a `reqwest::Client` with the request timeout. The API key is read later, when a request is sent, so connecting to a server and listing its tools works without one.
2225>
2226> ### Validating Structured Tool Output
2227>
2228> Add this method inside the `impl MCPClient` block:
2229>
2230> ```rust theme={null}
2231> /// Check a result against its tool's declared `outputSchema`. Error results
2232> /// are exempt: they carry a message, not data.
2233> fn validate_tool_output(&self, name: &str, result: &CallToolResult) -> Result<()> {
2234> let Some(validator) = self.output_schemas.get(name) else {
2235> return Ok(());
2236> };
2237> if result.is_error.unwrap_or(false) {
2238> return Ok(());
2239> }
2240> let Some(structured) = &result.structured_content else {
2241> bail!("Tool {name} declares an output schema but returned no structured content");
2242> };
2243> if let Err(error) = validator.validate(structured) {
2244> bail!("Structured content from tool {name} does not match its output schema: {error}");
2245> }
2246> Ok(())
2247> }
2248> ```
2249>
2250> A tool may declare an `outputSchema`, and the specification asks clients to validate `structuredContent` against it. rmcp does not do this, so the client keeps a compiled `jsonschema::Validator` per tool and checks each successful result. A result with `is_error` set carries a message, so it is exempt. A tool that declares a schema and returns no structured content is reported as an error.
21372251>
21382252> ### Server Connection Management
21392253>
21402254> Add this method inside the `impl MCPClient` block:
21412255>
21422256> ```rust theme={null}
2143> async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2144> if self.session.is_some() {
2145> bail!("Client is already connected to a server");
2257> async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2258> if self.session.is_some() {
2259> bail!("Client is already connected to a server");
2260> }
2261>
2262> let mut command = Command::new(&server_args[0]);
2263> command.args(&server_args[1..]);
2264>
2265> let process = TokioChildProcess::new(command)
2266> .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2267>
2268> // Without a ClientConfig the client would report rmcp's own crate name
2269> // and version rather than its own.
2270> let config = ClientConfig::new(
2271> ClientCapabilities::default(),
2272> Implementation::new("mcp-client-rust", "1.0.0"),
2273> );
2274>
2275> // `Auto` probes server/discover and falls back to the 2025-11-25
2276> // initialize handshake, matching the Python and TypeScript clients.
2277> // `serve` alone would only ever do the legacy handshake, under which a
2278> // server cannot offer this era's features -- an array-rooted
2279> // `outputSchema`, for one, which get_alerts uses.
2280> let session = config
2281> .serve_with_lifecycle(
2282> process,
2283> ClientLifecycleMode::Auto {
2284> preferred_versions: vec![ProtocolVersion::V_2026_07_28],
2285> legacy_version: Some(ProtocolVersion::V_2025_11_25),
2286> },
2287> )
2288> .await?;
2289>
2290> let rmcp_tools = session
2291> .list_all_tools()
2292> .await
2293> .context("Unable to list tools from server")?;
2294>
2295> let tool_names: Vec<String> = rmcp_tools
2296> .iter()
2297> .map(|tool| tool.name.to_string())
2298> .collect();
2299>
2300> let protocol_version = session
2301> .peer_info()
2302> .map(|info| info.protocol_version.to_string())
2303> .unwrap_or_else(|| "unknown".to_string());
2304> println!("Connected over protocol {protocol_version} with tools: {tool_names:?}");
2305>
2306> // An outputSchema root may be any JSON Schema, not just an object.
2307> for tool in &rmcp_tools {
2308> let Some(schema) = &tool.output_schema else {
2309> continue;
2310> };
2311> let schema = Value::Object(schema.as_ref().clone());
2312> let validator = Validator::new(&schema).with_context(|| {
2313> format!("Failed to compile output schema of tool {}", tool.name)
2314> })?;
2315> self.output_schemas.insert(tool.name.to_string(), validator);
2316> }
2317>
2318> self.tools = convert_tools(&rmcp_tools);
2319> self.session = Some(session);
2320> Ok(())
21462321> }
2147>
2148> let mut command = Command::new(&server_args[0]);
2149> command.args(&server_args[1..]);
2150>
2151> let process = TokioChildProcess::new(command)
2152> .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2153>
2154> let session = ().serve(process).await?;
2155>
2156> let rmcp_tools = session
2157> .list_all_tools()
2158> .await
2159> .context("Unable to list tools from server")?;
2160>
2161> let tool_names: Vec<String> = rmcp_tools
2162> .iter()
2163> .map(|tool| tool.name.to_string())
2164> .collect();
2165>
2166> println!("Connected to server with tools: {tool_names:?}");
2167>
2168> self.tools = convert_tools(&rmcp_tools);
2169> self.session = Some(session);
2170> Ok(())
2171> }
21722322> ```
21732323>
21742324> This method:
21752325>
21762326> 1. Starts the server as a child process using the command and arguments supplied on the command line
2177> 2. Establishes an MCP session over stdio
2178> 3. Lists all tools advertised by the server
2179> 4. Converts those tools into the format used in model requests
2180>
2181> ### Converting MCP Tools
2182>
2183> Add this function outside the `impl MCPClient` block:
2327> 2. Names the client `mcp-client-rust` through a `ClientConfig`
2328> 3. Negotiates the protocol with `serve_with_lifecycle` and `ClientLifecycleMode::Auto`, which probes `server/discover` for `2026-07-28` and falls back to the `2025-11-25` `initialize` handshake
2329> 4. Lists all tools advertised by the server and prints the negotiated protocol version with the tool names
2330> 5. Compiles a validator from each tool's `outputSchema`
2331> 6. Converts the tools into the form used in model requests
2332>
2333> rmcp's `serve` method alone performs only the legacy handshake. The `Auto` mode makes the features of the current revision reachable, including an `outputSchema` whose root is an array.
2334>
2335> ### Query Processing Logic
2336>
2337> Now add the core query-processing method inside `impl MCPClient`:
21842338>
21852339> ```rust theme={null}
2186> fn convert_tools(tools: &[McpTool]) -> Vec<GenaiTool> {
2187> tools
2188> .iter()
2189> .map(|tool| GenaiTool {
2190> name: tool.name.to_string(),
2191> description: tool.description.as_deref().map(str::to_string),
2192> schema: Some(Value::Object(tool.input_schema.as_ref().clone())),
2193> config: None,
2194> })
2195> .collect()
2196> }
2197> ```
2198>
2199> MCP and model APIs describe tools with similar information but different Rust types. `convert_tools` maps each MCP tool's name, description, and input schema into a `genai` tool definition.
2340> async fn process_query(&mut self, query: &str) -> Result<String> {
2341> let session = self
2342> .session
2343> .as_ref()
2344> .context("Client is not connected to any server")?;
2345>
2346> let mut messages = vec![Message::user(vec![json!({"type": "text", "text": query})])];
2347> let mut final_text = Vec::new();
2348>
2349> // Initial Claude API call with tools
2350> let mut content = self.request_model(&messages).await?;
2351>
2352> // Keep calling tools until Claude answers without one, up to a cap.
2353> for _ in 0..MAX_TOOL_TURNS {
2354> let mut tool_uses = Vec::new();
2355> for block in &content {
2356> match block_type(block) {
2357> "text" => {
2358> if let Some(text) = block.get("text").and_then(Value::as_str) {
2359> final_text.push(text.to_string());
2360> }
2361> }
2362> "tool_use" => tool_uses.push(block.clone()),
2363> _ => {}
2364> }
2365> }
2366>
2367> if tool_uses.is_empty() {
2368> return Ok(final_text.join("\n"));
2369> }
2370>
2371> // Execute every tool call in this response and collect the results
2372> let mut tool_results = Vec::new();
2373> for tool_use in &tool_uses {
2374> let name = tool_use
2375> .get("name")
2376> .and_then(Value::as_str)
2377> .context("tool_use block has no name")?;
2378> let id = tool_use
2379> .get("id")
2380> .and_then(Value::as_str)
2381> .context("tool_use block has no id")?;
2382> let input = tool_use.get("input").cloned().unwrap_or(json!({}));
2383>
2384> // Add information about the tool call to final text
2385> final_text.push(format!("[Calling tool {name} with args {input}]"));
2386>
2387> // Query the MCP server
2388> let mut params = CallToolRequestParams::new(name.to_string());
2389> if let Some(arguments) = input.as_object().cloned() {
2390> params = params.with_arguments(arguments);
2391> }
2392> let tool_result = match session.call_tool(params).await {
2393> Ok(result) => result,
2394> // A rejected call is the model's mistake to correct, so it
2395> // goes back as a failed tool_result rather than ending the
2396> // query. Every tool_use still needs a matching result.
2397> Err(error) => {
2398> final_text.push(format!("[{name} failed: {error}]"));
2399> tool_results.push(json!({
2400> "type": "tool_result",
2401> "tool_use_id": id,
2402> "content": format!("Tool call {name} failed: {error}"),
2403> "is_error": true,
2404> }));
2405> continue;
2406> }
2407> };
2408>
2409> self.validate_tool_output(name, &tool_result)?;
2410>
2411> // structured_content is data the application can use directly.
2412> if let Some(Value::Array(items)) = &tool_result.structured_content {
2413> final_text.push(format!("[{name} returned {} items]", items.len()));
2414> }
2415>
2416> // content is a list of block types; forward only the text ones.
2417> let mut payload = tool_result
2418> .content
2419> .iter()
2420> .filter_map(|block| block.as_text().map(|text| text.text.as_str()))
2421> .collect::<Vec<_>>()
2422> .join("\n");
2423>
2424> // A structured result SHOULD also carry serialized JSON in a text
2425> // block, but only SHOULD, so fall back to serializing it rather
2426> // than sending the model an empty result.
2427> if payload.is_empty() {
2428> if let Some(structured) = &tool_result.structured_content {
2429> payload = structured.to_string();
2430> }
2431> }
2432>
2433> tool_results.push(json!({
2434> "type": "tool_result",
2435> "tool_use_id": id,
2436> "content": payload,
2437> "is_error": tool_result.is_error.unwrap_or(false),
2438> }));
2439> }
2440>
2441> // Append the assistant's response and all tool results, in one user
2442> // message, to the history. Every tool_use needs a matching
2443> // tool_result, and the assistant's blocks go back as they arrived.
2444> messages.push(Message::assistant(content));
2445> messages.push(Message::user(tool_results));
2446>
2447> content = self.request_model(&messages).await?;
2448> }
2449>
2450> // The turn cap was hit. Keep the last response's text. If it asked for
2451> // more tools, say they were not run.
2452> let mut wants_tools = false;
2453> for block in &content {
2454> match block_type(block) {
2455> "text" => {
2456> if let Some(text) = block.get("text").and_then(Value::as_str) {
2457> final_text.push(text.to_string());
2458> }
2459> }
2460> "tool_use" => wants_tools = true,
2461> _ => {}
2462> }
2463> }
2464> if wants_tools {
2465> final_text.push(format!("[Stopped after {MAX_TOOL_TURNS} tool-use turns]"));
2466> }
2467>
2468> Ok(final_text.join("\n"))
2469> }
2470> ```
2471>
2472> The method sends the user's query to Claude with the server's tools and then loops. Each pass collects the text blocks of the reply and gathers its `tool_use` blocks. When a reply contains no tool use, the collected text is returned. Otherwise the client calls each requested tool through the MCP session and builds one `tool_result` block per `tool_use`. A call the server rejects goes back with `is_error` set, so Claude can read the message and try something else. A successful result is checked against its output schema. Its text blocks are joined and forwarded to Claude, and when it has no text blocks the serialized `structured_content` is sent in their place. When `structured_content` is an array, the client prints the item count as an example of using structured data directly. The assistant's blocks are appended to the history exactly as they arrived, followed by one user message holding all tool results, and the next request is sent. The loop stops after `MAX_TOOL_TURNS` rounds. At that point the last reply's text is kept, and a note is added when Claude asked for more tools.
22002473>
22012474> ### Sending Model Requests
22022475>
22032476> Add this helper method inside `impl MCPClient`:
22042477>
22052478> ```rust theme={null}
2206> async fn request_model(&self, chat_req: &ChatRequest) -> Result<ChatResponse> {
2207> let response = self
2208> .anthropic
2209> .exec_chat(MODEL_ANTHROPIC, chat_req.clone(), None)
2210> .await
2211> .context("Anthropic chat request failed")?;
2212>
2213> Ok(response)
2214> }
2215> ```
2216>
2217> This keeps model request handling in one place and adds useful context if the API request fails.
2218>
2219> ### Query Processing Logic
2220>
2221> Now add the core query-processing method inside `impl MCPClient`:
2479> /// Call Claude with the current history and return the content blocks of
2480> /// its reply, untouched. Tools are passed on every call so Claude can keep
2481> /// calling them across turns.
2482> async fn request_model(&self, messages: &[Message]) -> Result<Vec<Value>> {
2483> let api_key = std::env::var("ANTHROPIC_API_KEY").context("ANTHROPIC_API_KEY is not set")?;
2484> // The base URL is configurable so the client can point at a local stand-in.
2485> let base_url =
2486> std::env::var("ANTHROPIC_BASE_URL").unwrap_or_else(|_| ANTHROPIC_API_BASE.to_string());
2487>
2488> let request = MessagesRequest {
2489> model: MODEL_ANTHROPIC,
2490> max_tokens: MAX_TOKENS,
2491> messages,
2492> tools: &self.tools,
2493> };
2494>
2495> let response = self
2496> .http
2497> .post(format!("{}/v1/messages", base_url.trim_end_matches('/')))
2498> .header("x-api-key", api_key)
2499> .header("anthropic-version", ANTHROPIC_VERSION)
2500> .json(&request)
2501> .send()
2502> .await
2503> .context("Anthropic request failed")?;
2504>
2505> let status = response.status();
2506> let body = response
2507> .text()
2508> .await
2509> .context("Unable to read the Anthropic response")?;
2510> if !status.is_success() {
2511> bail!("Anthropic request failed with {status}: {body}");
2512> }
2513>
2514> let parsed: MessagesResponse =
2515> serde_json::from_str(&body).context("Unable to parse the Anthropic response")?;
2516> Ok(parsed.content)
2517> }
2518> ```
2519>
2520> `request_model` reads `ANTHROPIC_API_KEY` on each call and posts the history to `/v1/messages` with the `x-api-key` and `anthropic-version` headers. `ANTHROPIC_BASE_URL` overrides the endpoint, which allows pointing the client at a local stand-in. Tools are sent on every request so Claude can keep calling them across turns. A non-success status becomes an error that includes the response body. The reply's content blocks are returned untouched.
2521>
2522> ### Interactive Chat Interface
2523>
2524> Add the interactive terminal loop inside `impl MCPClient`:
22222525>
22232526> ```rust theme={null}
2224> async fn process_query(&mut self, query: &str) -> Result<String> {
2225> let session = self
2226> .session
2227> .as_ref()
2228> .context("Client is not connected to any server")?;
2229>
2230> let mut messages = vec![ChatMessage::user(query)];
2231> let mut final_text = Vec::new();
2232>
2233> // Initial Claude API call with tools
2234> let mut chat_req = ChatRequest::new(messages.clone()).with_tools(self.tools.clone());
2235> let mut chat_rsp = self.request_model(&chat_req).await?;
2236>
2237> // Process response content - collect text and handle tool calls
2238> for text in chat_rsp.texts() {
2239> final_text.push(text.to_string());
2527> async fn chat_loop(&mut self) -> Result<()> {
2528> println!("\nMCP Client Started!");
2529> println!("Type your queries or 'quit' to exit.");
2530>
2531> let mut stdin = BufReader::new(io::stdin());
2532> let mut input = String::new();
2533>
2534> loop {
2535> print!("\nQuery: ");
2536> std::io::Write::flush(&mut std::io::stdout())?;
2537>
2538> input.clear();
2539> if stdin.read_line(&mut input).await? == 0 {
2540> break; // EOF
2541> }
2542>
2543> let query = input.trim();
2544> if query.eq_ignore_ascii_case("quit") {
2545> break;
2546> }
2547> if query.is_empty() {
2548> continue;
2549> }
2550>
2551> match self.process_query(query).await {
2552> Ok(response) => println!("\n{}", response),
2553> Err(err) => println!("\nError: {:#}", err),
2554> }
2555> }
2556>
2557> Ok(())
22402558> }
2241>
2242> let tool_calls = chat_rsp.tool_calls();
2243> if !tool_calls.is_empty() {
2244> // Append assistant's response to message history
2245> messages.push(ChatMessage::assistant(chat_rsp.content.clone()));
2246>
2247> // Execute each tool call and collect responses
2248> let mut tool_results = Vec::new();
2249> for tool_call in tool_calls {
2250> // Add information about the tool call to final text
2251> let tool_args_str = serde_json::to_string(&tool_call.fn_arguments)
2252> .unwrap_or_else(|_| "{}".to_string());
2253>
2254> final_text.push(format!(
2255> "[Calling tool {} with args {}]",
2256> tool_call.fn_name, tool_args_str
2257> ));
2258>
2259> // Query the MCP server
2260> let tool_result = session
2261> .call_tool(CallToolRequestParam {
2262> name: tool_call.fn_name.clone().into(),
2263> arguments: tool_call.fn_arguments.as_object().cloned(),
2264> })
2265> .await
2266> .with_context(|| format!("Tool call {} failed", tool_call.fn_name))?;
2267>
2268> let payload = serde_json::to_string(&tool_result)
2269> .context("Failed to serialize tool result")?;
2270>
2271> tool_results.push(ContentPart::ToolResponse(ToolResponse::new(
2272> tool_call.call_id.clone(),
2273> payload,
2274> )));
2559> ```
2560>
2561> The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client. The `{:#}` format prints the whole `anyhow` context chain on one line.
2562>
2563> ### Cleanup
2564>
2565> Add this method inside `impl MCPClient` to stop the MCP session and child process. The closing brace ends the `impl MCPClient` block:
2566>
2567> ```rust theme={null}
2568> async fn cleanup(&mut self) -> Result<()> {
2569> if let Some(session) = self.session.take() {
2570> let _ = session.cancel().await;
22752571> }
2276>
2277> // Append tool responses to message history
2278> messages.push(ChatMessage::user(tool_results));
2279>
2280> // Build the next request and query model
2281> chat_req = ChatRequest::new(messages.clone());
2282> chat_rsp = self.request_model(&chat_req).await?;
2283>
2284> // Collect text from response
2285> for text in chat_rsp.texts() {
2286> final_text.push(text.to_string());
2287> }
2572> Ok(())
22882573> }
2289>
2290> Ok(final_text.join("\n"))
2291> }
2292> ```
2293>
2294> The method first sends the user's query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.
2295>
2296> ### Interactive Chat Interface
2297>
2298> Add the interactive terminal loop inside `impl MCPClient`:
2299>
2300> ```rust theme={null}
2301> async fn chat_loop(&mut self) -> Result<()> {
2302> println!("\nMCP Client Started!");
2303> println!("Type your queries or 'quit' to exit.");
2304>
2305> let mut stdin = BufReader::new(io::stdin());
2306> let mut input = String::new();
2307>
2308> loop {
2309> print!("\nQuery: ");
2310> std::io::Write::flush(&mut std::io::stdout())?;
2311>
2312> input.clear();
2313> if stdin.read_line(&mut input).await? == 0 {
2314> break; // EOF
2315> }
2316>
2317> let query = input.trim();
2318> if query.eq_ignore_ascii_case("quit") {
2319> break;
2320> }
2321> if query.is_empty() {
2322> continue;
2323> }
2324>
2325> match self.process_query(query).await {
2326> Ok(response) => println!("\n{}", response),
2327> Err(err) => println!("\nError: {}", err),
2328> }
2329> }
2330>
2331> Ok(())
2332> }
2333> ```
2334>
2335> The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client.
2336>
2337> ### Cleanup
2338>
2339> Add this method inside `impl MCPClient` to stop the MCP session and child process:
2340>
2341> ```rust theme={null}
2342> async fn cleanup(&mut self) -> Result<()> {
2343> if let Some(session) = self.session.take() {
2344> let _ = session.cancel().await;
2345> }
2346> Ok(())
23472574> }
23482575> ```
23492576>
23502577> ### Main Entry Point
23512578>
2352> Finally, add the asynchronous entry point outside the `impl MCPClient` block:
2579> Next, add the asynchronous entry point outside the `impl MCPClient` block:
23532580>
23542581> ```rust theme={null}
23552582> #[tokio::main]
23562583> async fn main() -> Result<()> {
2357> dotenvy::dotenv().context("Failed to load env file")?;
2584> // .env is optional; the key may come from the environment instead.
2585> let _ = dotenvy::dotenv();
23582586>
23592587> let mut args = std::env::args();
23602588> let _ = args.next();
from line 2597
23692597>
23702598> let result = async {
23712599> client.connect_to_server(&server_args).await?;
2600>
2601> // Connecting and listing tools needs no credentials; querying them
2602> // does. Matching the Python and TypeScript clients, report and exit
2603> // rather than failing, so the connection itself can be exercised
2604> // without a key.
2605> // Empty counts as unset, as it does in the other clients: `KEY= cmd`
2606> // is how the smoke test forces this path.
2607> if std::env::var("ANTHROPIC_API_KEY").map_or(true, |key| key.is_empty()) {
2608> println!(
2609> "\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:"
2610> );
2611> println!(" export ANTHROPIC_API_KEY=your-api-key-here");
2612> return Ok(());
2613> }
2614>
23722615> client.chat_loop().await
23732616> }
23742617> .await;
from line 2625
23822625> }
23832626> ```
23842627>
2385> The entry point loads `.env`, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.
2628> The entry point loads `.env` when the file exists, treats all remaining command-line arguments as the server command, connects the client, and ensures cleanup runs before exiting. When `ANTHROPIC_API_KEY` is unset or empty, the client prints how to set the key and exits after listing the server's tools. This exercises the MCP connection without credentials.
2629>
2630> ### Describing Tools to the Model
2631>
2632> Finally, add this function outside the `impl MCPClient` block:
2633>
2634> ```rust theme={null}
2635> fn convert_tools(tools: &[McpTool]) -> Vec<ToolDefinition> {
2636> tools
2637> .iter()
2638> .map(|tool| ToolDefinition {
2639> name: tool.name.to_string(),
2640> description: tool.description.as_deref().map(str::to_string),
2641> input_schema: Value::Object(tool.input_schema.as_ref().clone()),
2642> })
2643> .collect()
2644> }
2645> ```
2646>
2647> MCP and the Messages API describe tools with the same information in different Rust types. `convert_tools` copies each MCP tool's name, description, and input schema into a `ToolDefinition`, which serializes to the shape the `tools` parameter expects. The description is omitted when a tool has none.
23862648>
23872649> ### Verify the Complete File
23882650>
23892651> Before running the client, confirm the items in `src/main.rs` are placed at the correct scope:
23902652>
2391> * `new`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block.
2392> * `main` and `convert_tools` are functions outside the `impl MCPClient` block.
2653> * `new`, `validate_tool_output`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block, which opens in Client Initialization and closes after `cleanup`.
2654> * `user` and `assistant` are methods inside the `impl Message` block.
2655> * `block_type`, `main`, and `convert_tools` are functions outside both `impl` blocks.
23932656>
23942657> Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the [complete `src/main.rs` example](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs), then check that it compiles:
23952658>
from line 2685
24222685> The client will:
24232686>
24242687> 1. Start and connect to the specified MCP server
2425> 2. List the tools available from that server
2688> 2. Print the negotiated protocol version and the tools available from that server
24262689> 3. Start an interactive chat session where you can:
24272690> * Enter queries
24282691> * See tool executions
24292692> * Get responses from Claude
24302693>
2694> Connecting to the weather server prints a line like:
2695>
2696> ```text theme={null}
2697> Connected over protocol 2026-07-28 with tools: ["get_alerts", "get_forecast"]
2698> ```
2699>
2700> Without an `ANTHROPIC_API_KEY`, the client stops after this line and prints how to set the key.
2701>
24312702> ## How It Works
24322703>
2433> When you submit a query:
2434>
2435> 1. The client sends your query and the server's available tools to Claude
2704> When the user submits a query:
2705>
2706> 1. The client sends the query and the server's tool definitions to Claude
24362707> 2. Claude decides which tools, if any, to use
2437> 3. The client executes requested tools through the MCP session
2438> 4. Tool results are sent back to Claude
2439> 5. Claude provides a natural language response
2440> 6. The response is displayed in the terminal
2708> 3. The client executes every requested tool through the MCP session and validates structured results against their output schemas
2709> 4. Tool results, including failures marked with `is_error`, are sent back to Claude together with Claude's own blocks, unchanged
2710> 5. Steps 2 through 4 repeat until Claude answers without a tool call or `MAX_TOOL_TURNS` is reached
2711> 6. The collected text is displayed in the terminal
24412712>
24422713> ## Best Practices
24432714>
24442715> 1. **Error Handling**
2445> * Add context to errors at process, MCP, model API, and serialization boundaries
2716> * Add context to errors at process, MCP, and model API boundaries
2717> * Send a rejected tool call back to Claude as a `tool_result` with `is_error` set, so every `tool_use` gets an answer
24462718> * Report individual query errors without terminating the interactive session
2447> * Validate server commands before running them
2448> 2. **Resource Management**
2719> 2. **Conversation History**
2720> * Feed assistant blocks back exactly as they arrived, thinking blocks and their signatures included
2721> * Pass the tool list on every request so Claude can keep calling tools across turns
2722> * Cap the number of tool turns per query
2723> 3. **Resource Management**
24492724> * Always cancel the MCP session during cleanup
24502725> * Ensure cleanup runs even when connection or chat-loop operations fail
24512726> * Avoid starting a second server while a session is active
2452> 3. **Security**
2453> * Store API keys securely in `.env`
2454> * Review the tools exposed by a server before allowing model-driven calls
2455> * Connect only to servers and executable commands you trust
2727> 4. **Security**
2728> * Store API keys securely in `.env` or the environment
2729> * Validate structured tool results against their declared output schemas
2730> * Connect only to trusted servers and executable commands
24562731>
24572732> ## Troubleshooting
24582733>
from line 2748
24732748>
24742749> ### Environment File Issues
24752750>
2476> If you see `Failed to load env file`, ensure `.env` exists in the directory where you run the client.
2477>
2478> If the model request reports a missing API key, confirm that `.env` contains:
2751> The `.env` file is optional. When it is missing, the client reads `ANTHROPIC_API_KEY` from the environment. When the key is unset or empty, the client connects, prints the server's tools, and exits with instructions for setting the key. Export the key, or create a `.env` in the directory where the client runs that contains:
24792752>
24802753> ```text theme={null}
24812754> ANTHROPIC_API_KEY=your-api-key-goes-here
from line 2757
24842757> ### Tool and Response Errors
24852758>
24862759> * `Unable to list tools from server`: Verify the server starts successfully and communicates over stdio
2487> * `Tool call ... failed`: Verify the server tool's required arguments and environment variables
2488> * `Failed to serialize tool result`: Inspect the server's response for unsupported or malformed content
2760> * `[... failed: ...]` in the output: The server rejected the tool call. The message also goes to Claude as a failed `tool_result`, so Claude may retry with different arguments
2761> * `Tool ... declares an output schema but returned no structured content` or `Structured content from tool ... does not match its output schema`: The server's result does not satisfy its own `outputSchema`
2762> * `Anthropic request failed with ...`: The response body follows the status and names the cause, such as an invalid key or insufficient credits
2763> * `[Stopped after 10 tool-use turns]`: The query reached `MAX_TOOL_TURNS`. Raise the constant for workflows that need more rounds
24892764 
24902765## Next steps
24912766 
24922767 

docs/draft/develop/build-client Changed · +521 / -246 lines

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 2026
20262026>
20272027> ## System Requirements
20282028>
2029> Before starting, ensure your Linux system meets these requirements:
2030>
2031> * Latest stable version of [Rust and Cargo](https://www.rust-lang.org/tools/install)
2029> Before starting, ensure your system meets these requirements:
2030>
2031> * [Rust and Cargo](https://www.rust-lang.org/tools/install) 1.88 or newer
20322032> * Anthropic API key (Claude)
20332033> * A Python, Node.js, or executable MCP server to connect to
20342034>
from line 2050
20502050> edition = "2024"
20512051>
20522052> [dependencies]
2053> anyhow = "1.0.100"
2054> genai = "0.4.2"
2055> rmcp = { version = "0.8.0", features = ["server", "client", "transport-io", "transport-child-process"] }
2056> tokio = { version = "1.47.1", features = ["full"] }
2057> tracing = "0.1.41"
2058> tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2059> serde_json = "1.0.128"
2053> anyhow = "1.0.104"
2054> jsonschema = "0.59"
2055> # Only the client half of rmcp is needed, over a child-process stdio transport.
2056> rmcp = { version = "3.4", features = [
2057> "client",
2058> "transport-io",
2059> "transport-child-process",
2060> ], default-features = false }
2061> # The Messages API is called directly, which keeps the provider's content
2062> # blocks verbatim. That matters for signed thinking blocks; see request_model.
2063> reqwest = { version = "0.13", features = ["json"] }
2064> serde = { version = "1.0", features = ["derive"] }
2065> serde_json = "1.0.151"
2066> tokio = { version = "1.53", features = ["full"] }
20602067> dotenvy = "0.15.7"
2061> reqwest = "0.12.23"
2062> ```
2063>
2064> The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and child-process transport. This example uses the [`genai`](https://github.com/jeremychone/rust-genai) crate to send requests to Claude and represent tools in the model request.
2068> ```
2069>
2070> The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and the child-process stdio transport. Only its client half is enabled. The client calls the [Messages API](https://docs.anthropic.com/en/api/messages) directly with [`reqwest`](https://docs.rs/reqwest). Calling the API directly keeps the content blocks of each reply verbatim, which matters when a reply contains a signed thinking block. The [`jsonschema`](https://docs.rs/jsonschema) crate validates structured tool results against the schema a tool declares.
20652071>
20662072> ## Setting Up Your API Key
20672073>
from line 2084
20782084> ```bash theme={null}
20792085> echo ".env" >> .gitignore
20802086> ```
2087>
2088> The client loads `.env` when the file exists. Exporting `ANTHROPIC_API_KEY` in the shell works as well.
20812089>
20822090> > [!WARNING]
20832091> >
from line 2097
20892097>
20902098> ### Imports and Client Structure
20912099>
2092> First, add the imports, model constant, and basic client structure:
2100> First, add the imports and constants:
20932101>
20942102> ```rust theme={null}
20952103> use anyhow::{Context, Result, bail};
2096> use genai::Client;
2097> use genai::chat::{
2098> ChatMessage, ChatRequest, ChatResponse, ContentPart, Tool as GenaiTool, ToolResponse,
2104> use jsonschema::Validator;
2105> use rmcp::model::{
2106> CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, Implementation,
2107> ProtocolVersion, Tool as McpTool,
20992108> };
2100> use rmcp::model::{CallToolRequestParam, Tool as McpTool};
2101> use rmcp::service::{RoleClient, RunningService, ServiceExt};
2109> use rmcp::service::{ClientLifecycleMode, ClientServiceExt, RoleClient, RunningService};
21022110> use rmcp::transport::TokioChildProcess;
2103> use serde_json::Value;
2111> use serde::{Deserialize, Serialize};
2112> use serde_json::{Value, json};
2113> use std::collections::HashMap;
2114> use std::time::Duration;
21042115> use tokio::io::{self, AsyncBufReadExt, BufReader};
21052116> use tokio::process::Command;
21062117>
21072118> const MODEL_ANTHROPIC: &str = "claude-opus-5";
2119> /// The model may think before answering, and max_tokens caps thinking
2120> /// plus the reply, so leave room for both.
2121> const MAX_TOKENS: u32 = 10000;
2122> const MAX_TOOL_TURNS: usize = 10;
2123>
2124> const ANTHROPIC_API_BASE: &str = "https://api.anthropic.com";
2125> const ANTHROPIC_VERSION: &str = "2023-06-01";
2126> const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
2127> ```
2128>
2129> `MAX_TOKENS` caps the thinking and the reply together. `MAX_TOOL_TURNS` bounds how many rounds of tool calls one query may take. `REQUEST_TIMEOUT` applies to each request sent to the Messages API.
2130>
2131> Next, add the types for the Messages API and the client structure:
2132>
2133> ```rust theme={null}
2134> /// One turn of the conversation, as the Messages API takes it.
2135> ///
2136> /// `content` is a list of raw blocks rather than typed ones on purpose. An
2137> /// assistant turn is fed straight back on the next request, and Claude requires
2138> /// the blocks it sent to return unchanged -- a thinking block's `signature`
2139> /// included. Reserialising through a narrower type would drop whatever it does
2140> /// not model.
2141> #[derive(Serialize, Clone)]
2142> struct Message {
2143> role: &'static str,
2144> content: Vec<Value>,
2145> }
2146>
2147> impl Message {
2148> fn user(content: Vec<Value>) -> Self {
2149> Message {
2150> role: "user",
2151> content,
2152> }
2153> }
2154>
2155> fn assistant(content: Vec<Value>) -> Self {
2156> Message {
2157> role: "assistant",
2158> content,
2159> }
2160> }
2161> }
2162>
2163> /// A tool as the Messages API declares it, converted from an MCP tool.
2164> #[derive(Serialize, Clone)]
2165> struct ToolDefinition {
2166> name: String,
2167> #[serde(skip_serializing_if = "Option::is_none")]
2168> description: Option<String>,
2169> input_schema: Value,
2170> }
2171>
2172> #[derive(Serialize)]
2173> struct MessagesRequest<'a> {
2174> model: &'a str,
2175> max_tokens: u32,
2176> messages: &'a [Message],
2177> tools: &'a [ToolDefinition],
2178> }
2179>
2180> #[derive(Deserialize)]
2181> struct MessagesResponse {
2182> content: Vec<Value>,
2183> }
2184>
2185> /// The `type` of a content block, when it has one.
2186> fn block_type(block: &Value) -> &str {
2187> block
2188> .get("type")
2189> .and_then(Value::as_str)
2190> .unwrap_or_default()
2191> }
21082192>
21092193> struct MCPClient {
2110> anthropic: Client,
2111> session: Option<RunningService<RoleClient, ()>>,
2112> tools: Vec<GenaiTool>,
2113> }
2114> ```
2115>
2116> The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.
2194> http: reqwest::Client,
2195> session: Option<RunningService<RoleClient, ClientConfig>>,
2196> tools: Vec<ToolDefinition>,
2197> /// Compiled `outputSchema` per tool name. rmcp does not validate results,
2198> /// so this client does it with the `jsonschema` crate.
2199> output_schemas: HashMap<String, Validator>,
2200> }
2201> ```
2202>
2203> `Message` holds the content blocks of one turn as raw `serde_json::Value`s. An assistant turn goes back to the API unchanged on the next request, with any thinking block and its `signature` intact. `ToolDefinition` is a tool as the Messages API declares it. `MCPClient` keeps the HTTP client, the active MCP session, the tools in Messages API form, and one compiled validator per tool that declares an `outputSchema`.
21172204>
21182205> ### Client Initialization
21192206>
2120> Next, initialize the model client and start without an MCP session or tools:
2207> Next, open the `impl MCPClient` block with the constructor. The methods in the following sections go inside this block, which closes after `cleanup`:
21212208>
21222209> ```rust theme={null}
21232210> impl MCPClient {
21242211> fn new() -> Result<Self> {
21252212> Ok(MCPClient {
2126> anthropic: Client::default(),
2213> http: reqwest::Client::builder()
2214> .timeout(REQUEST_TIMEOUT)
2215> .build()
2216> .context("Failed to build HTTP client")?,
21272217> session: None,
21282218> tools: Vec::new(),
2219> output_schemas: HashMap::new(),
21292220> })
21302221> }
2131>
2132> // Additional methods will go here.
2133> }
2134> ```
2135>
2136> `genai::Client::default()` reads the `ANTHROPIC_API_KEY` environment variable when it sends a request.
2222> ```
2223>
2224> `new` builds a `reqwest::Client` with the request timeout. The API key is read later, when a request is sent, so connecting to a server and listing its tools works without one.
2225>
2226> ### Validating Structured Tool Output
2227>
2228> Add this method inside the `impl MCPClient` block:
2229>
2230> ```rust theme={null}
2231> /// Check a result against its tool's declared `outputSchema`. Error results
2232> /// are exempt: they carry a message, not data.
2233> fn validate_tool_output(&self, name: &str, result: &CallToolResult) -> Result<()> {
2234> let Some(validator) = self.output_schemas.get(name) else {
2235> return Ok(());
2236> };
2237> if result.is_error.unwrap_or(false) {
2238> return Ok(());
2239> }
2240> let Some(structured) = &result.structured_content else {
2241> bail!("Tool {name} declares an output schema but returned no structured content");
2242> };
2243> if let Err(error) = validator.validate(structured) {
2244> bail!("Structured content from tool {name} does not match its output schema: {error}");
2245> }
2246> Ok(())
2247> }
2248> ```
2249>
2250> A tool may declare an `outputSchema`, and the specification asks clients to validate `structuredContent` against it. rmcp does not do this, so the client keeps a compiled `jsonschema::Validator` per tool and checks each successful result. A result with `is_error` set carries a message, so it is exempt. A tool that declares a schema and returns no structured content is reported as an error.
21372251>
21382252> ### Server Connection Management
21392253>
21402254> Add this method inside the `impl MCPClient` block:
21412255>
21422256> ```rust theme={null}
2143> async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2144> if self.session.is_some() {
2145> bail!("Client is already connected to a server");
2257> async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2258> if self.session.is_some() {
2259> bail!("Client is already connected to a server");
2260> }
2261>
2262> let mut command = Command::new(&server_args[0]);
2263> command.args(&server_args[1..]);
2264>
2265> let process = TokioChildProcess::new(command)
2266> .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2267>
2268> // Without a ClientConfig the client would report rmcp's own crate name
2269> // and version rather than its own.
2270> let config = ClientConfig::new(
2271> ClientCapabilities::default(),
2272> Implementation::new("mcp-client-rust", "1.0.0"),
2273> );
2274>
2275> // `Auto` probes server/discover and falls back to the 2025-11-25
2276> // initialize handshake, matching the Python and TypeScript clients.
2277> // `serve` alone would only ever do the legacy handshake, under which a
2278> // server cannot offer this era's features -- an array-rooted
2279> // `outputSchema`, for one, which get_alerts uses.
2280> let session = config
2281> .serve_with_lifecycle(
2282> process,
2283> ClientLifecycleMode::Auto {
2284> preferred_versions: vec![ProtocolVersion::V_2026_07_28],
2285> legacy_version: Some(ProtocolVersion::V_2025_11_25),
2286> },
2287> )
2288> .await?;
2289>
2290> let rmcp_tools = session
2291> .list_all_tools()
2292> .await
2293> .context("Unable to list tools from server")?;
2294>
2295> let tool_names: Vec<String> = rmcp_tools
2296> .iter()
2297> .map(|tool| tool.name.to_string())
2298> .collect();
2299>
2300> let protocol_version = session
2301> .peer_info()
2302> .map(|info| info.protocol_version.to_string())
2303> .unwrap_or_else(|| "unknown".to_string());
2304> println!("Connected over protocol {protocol_version} with tools: {tool_names:?}");
2305>
2306> // An outputSchema root may be any JSON Schema, not just an object.
2307> for tool in &rmcp_tools {
2308> let Some(schema) = &tool.output_schema else {
2309> continue;
2310> };
2311> let schema = Value::Object(schema.as_ref().clone());
2312> let validator = Validator::new(&schema).with_context(|| {
2313> format!("Failed to compile output schema of tool {}", tool.name)
2314> })?;
2315> self.output_schemas.insert(tool.name.to_string(), validator);
2316> }
2317>
2318> self.tools = convert_tools(&rmcp_tools);
2319> self.session = Some(session);
2320> Ok(())
21462321> }
2147>
2148> let mut command = Command::new(&server_args[0]);
2149> command.args(&server_args[1..]);
2150>
2151> let process = TokioChildProcess::new(command)
2152> .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2153>
2154> let session = ().serve(process).await?;
2155>
2156> let rmcp_tools = session
2157> .list_all_tools()
2158> .await
2159> .context("Unable to list tools from server")?;
2160>
2161> let tool_names: Vec<String> = rmcp_tools
2162> .iter()
2163> .map(|tool| tool.name.to_string())
2164> .collect();
2165>
2166> println!("Connected to server with tools: {tool_names:?}");
2167>
2168> self.tools = convert_tools(&rmcp_tools);
2169> self.session = Some(session);
2170> Ok(())
2171> }
21722322> ```
21732323>
21742324> This method:
21752325>
21762326> 1. Starts the server as a child process using the command and arguments supplied on the command line
2177> 2. Establishes an MCP session over stdio
2178> 3. Lists all tools advertised by the server
2179> 4. Converts those tools into the format used in model requests
2180>
2181> ### Converting MCP Tools
2182>
2183> Add this function outside the `impl MCPClient` block:
2327> 2. Names the client `mcp-client-rust` through a `ClientConfig`
2328> 3. Negotiates the protocol with `serve_with_lifecycle` and `ClientLifecycleMode::Auto`, which probes `server/discover` for `2026-07-28` and falls back to the `2025-11-25` `initialize` handshake
2329> 4. Lists all tools advertised by the server and prints the negotiated protocol version with the tool names
2330> 5. Compiles a validator from each tool's `outputSchema`
2331> 6. Converts the tools into the form used in model requests
2332>
2333> rmcp's `serve` method alone performs only the legacy handshake. The `Auto` mode makes the features of the current revision reachable, including an `outputSchema` whose root is an array.
2334>
2335> ### Query Processing Logic
2336>
2337> Now add the core query-processing method inside `impl MCPClient`:
21842338>
21852339> ```rust theme={null}
2186> fn convert_tools(tools: &[McpTool]) -> Vec<GenaiTool> {
2187> tools
2188> .iter()
2189> .map(|tool| GenaiTool {
2190> name: tool.name.to_string(),
2191> description: tool.description.as_deref().map(str::to_string),
2192> schema: Some(Value::Object(tool.input_schema.as_ref().clone())),
2193> config: None,
2194> })
2195> .collect()
2196> }
2197> ```
2198>
2199> MCP and model APIs describe tools with similar information but different Rust types. `convert_tools` maps each MCP tool's name, description, and input schema into a `genai` tool definition.
2340> async fn process_query(&mut self, query: &str) -> Result<String> {
2341> let session = self
2342> .session
2343> .as_ref()
2344> .context("Client is not connected to any server")?;
2345>
2346> let mut messages = vec![Message::user(vec![json!({"type": "text", "text": query})])];
2347> let mut final_text = Vec::new();
2348>
2349> // Initial Claude API call with tools
2350> let mut content = self.request_model(&messages).await?;
2351>
2352> // Keep calling tools until Claude answers without one, up to a cap.
2353> for _ in 0..MAX_TOOL_TURNS {
2354> let mut tool_uses = Vec::new();
2355> for block in &content {
2356> match block_type(block) {
2357> "text" => {
2358> if let Some(text) = block.get("text").and_then(Value::as_str) {
2359> final_text.push(text.to_string());
2360> }
2361> }
2362> "tool_use" => tool_uses.push(block.clone()),
2363> _ => {}
2364> }
2365> }
2366>
2367> if tool_uses.is_empty() {
2368> return Ok(final_text.join("\n"));
2369> }
2370>
2371> // Execute every tool call in this response and collect the results
2372> let mut tool_results = Vec::new();
2373> for tool_use in &tool_uses {
2374> let name = tool_use
2375> .get("name")
2376> .and_then(Value::as_str)
2377> .context("tool_use block has no name")?;
2378> let id = tool_use
2379> .get("id")
2380> .and_then(Value::as_str)
2381> .context("tool_use block has no id")?;
2382> let input = tool_use.get("input").cloned().unwrap_or(json!({}));
2383>
2384> // Add information about the tool call to final text
2385> final_text.push(format!("[Calling tool {name} with args {input}]"));
2386>
2387> // Query the MCP server
2388> let mut params = CallToolRequestParams::new(name.to_string());
2389> if let Some(arguments) = input.as_object().cloned() {
2390> params = params.with_arguments(arguments);
2391> }
2392> let tool_result = match session.call_tool(params).await {
2393> Ok(result) => result,
2394> // A rejected call is the model's mistake to correct, so it
2395> // goes back as a failed tool_result rather than ending the
2396> // query. Every tool_use still needs a matching result.
2397> Err(error) => {
2398> final_text.push(format!("[{name} failed: {error}]"));
2399> tool_results.push(json!({
2400> "type": "tool_result",
2401> "tool_use_id": id,
2402> "content": format!("Tool call {name} failed: {error}"),
2403> "is_error": true,
2404> }));
2405> continue;
2406> }
2407> };
2408>
2409> self.validate_tool_output(name, &tool_result)?;
2410>
2411> // structured_content is data the application can use directly.
2412> if let Some(Value::Array(items)) = &tool_result.structured_content {
2413> final_text.push(format!("[{name} returned {} items]", items.len()));
2414> }
2415>
2416> // content is a list of block types; forward only the text ones.
2417> let mut payload = tool_result
2418> .content
2419> .iter()
2420> .filter_map(|block| block.as_text().map(|text| text.text.as_str()))
2421> .collect::<Vec<_>>()
2422> .join("\n");
2423>
2424> // A structured result SHOULD also carry serialized JSON in a text
2425> // block, but only SHOULD, so fall back to serializing it rather
2426> // than sending the model an empty result.
2427> if payload.is_empty() {
2428> if let Some(structured) = &tool_result.structured_content {
2429> payload = structured.to_string();
2430> }
2431> }
2432>
2433> tool_results.push(json!({
2434> "type": "tool_result",
2435> "tool_use_id": id,
2436> "content": payload,
2437> "is_error": tool_result.is_error.unwrap_or(false),
2438> }));
2439> }
2440>
2441> // Append the assistant's response and all tool results, in one user
2442> // message, to the history. Every tool_use needs a matching
2443> // tool_result, and the assistant's blocks go back as they arrived.
2444> messages.push(Message::assistant(content));
2445> messages.push(Message::user(tool_results));
2446>
2447> content = self.request_model(&messages).await?;
2448> }
2449>
2450> // The turn cap was hit. Keep the last response's text. If it asked for
2451> // more tools, say they were not run.
2452> let mut wants_tools = false;
2453> for block in &content {
2454> match block_type(block) {
2455> "text" => {
2456> if let Some(text) = block.get("text").and_then(Value::as_str) {
2457> final_text.push(text.to_string());
2458> }
2459> }
2460> "tool_use" => wants_tools = true,
2461> _ => {}
2462> }
2463> }
2464> if wants_tools {
2465> final_text.push(format!("[Stopped after {MAX_TOOL_TURNS} tool-use turns]"));
2466> }
2467>
2468> Ok(final_text.join("\n"))
2469> }
2470> ```
2471>
2472> The method sends the user's query to Claude with the server's tools and then loops. Each pass collects the text blocks of the reply and gathers its `tool_use` blocks. When a reply contains no tool use, the collected text is returned. Otherwise the client calls each requested tool through the MCP session and builds one `tool_result` block per `tool_use`. A call the server rejects goes back with `is_error` set, so Claude can read the message and try something else. A successful result is checked against its output schema. Its text blocks are joined and forwarded to Claude, and when it has no text blocks the serialized `structured_content` is sent in their place. When `structured_content` is an array, the client prints the item count as an example of using structured data directly. The assistant's blocks are appended to the history exactly as they arrived, followed by one user message holding all tool results, and the next request is sent. The loop stops after `MAX_TOOL_TURNS` rounds. At that point the last reply's text is kept, and a note is added when Claude asked for more tools.
22002473>
22012474> ### Sending Model Requests
22022475>
22032476> Add this helper method inside `impl MCPClient`:
22042477>
22052478> ```rust theme={null}
2206> async fn request_model(&self, chat_req: &ChatRequest) -> Result<ChatResponse> {
2207> let response = self
2208> .anthropic
2209> .exec_chat(MODEL_ANTHROPIC, chat_req.clone(), None)
2210> .await
2211> .context("Anthropic chat request failed")?;
2212>
2213> Ok(response)
2214> }
2215> ```
2216>
2217> This keeps model request handling in one place and adds useful context if the API request fails.
2218>
2219> ### Query Processing Logic
2220>
2221> Now add the core query-processing method inside `impl MCPClient`:
2479> /// Call Claude with the current history and return the content blocks of
2480> /// its reply, untouched. Tools are passed on every call so Claude can keep
2481> /// calling them across turns.
2482> async fn request_model(&self, messages: &[Message]) -> Result<Vec<Value>> {
2483> let api_key = std::env::var("ANTHROPIC_API_KEY").context("ANTHROPIC_API_KEY is not set")?;
2484> // The base URL is configurable so the client can point at a local stand-in.
2485> let base_url =
2486> std::env::var("ANTHROPIC_BASE_URL").unwrap_or_else(|_| ANTHROPIC_API_BASE.to_string());
2487>
2488> let request = MessagesRequest {
2489> model: MODEL_ANTHROPIC,
2490> max_tokens: MAX_TOKENS,
2491> messages,
2492> tools: &self.tools,
2493> };
2494>
2495> let response = self
2496> .http
2497> .post(format!("{}/v1/messages", base_url.trim_end_matches('/')))
2498> .header("x-api-key", api_key)
2499> .header("anthropic-version", ANTHROPIC_VERSION)
2500> .json(&request)
2501> .send()
2502> .await
2503> .context("Anthropic request failed")?;
2504>
2505> let status = response.status();
2506> let body = response
2507> .text()
2508> .await
2509> .context("Unable to read the Anthropic response")?;
2510> if !status.is_success() {
2511> bail!("Anthropic request failed with {status}: {body}");
2512> }
2513>
2514> let parsed: MessagesResponse =
2515> serde_json::from_str(&body).context("Unable to parse the Anthropic response")?;
2516> Ok(parsed.content)
2517> }
2518> ```
2519>
2520> `request_model` reads `ANTHROPIC_API_KEY` on each call and posts the history to `/v1/messages` with the `x-api-key` and `anthropic-version` headers. `ANTHROPIC_BASE_URL` overrides the endpoint, which allows pointing the client at a local stand-in. Tools are sent on every request so Claude can keep calling them across turns. A non-success status becomes an error that includes the response body. The reply's content blocks are returned untouched.
2521>
2522> ### Interactive Chat Interface
2523>
2524> Add the interactive terminal loop inside `impl MCPClient`:
22222525>
22232526> ```rust theme={null}
2224> async fn process_query(&mut self, query: &str) -> Result<String> {
2225> let session = self
2226> .session
2227> .as_ref()
2228> .context("Client is not connected to any server")?;
2229>
2230> let mut messages = vec![ChatMessage::user(query)];
2231> let mut final_text = Vec::new();
2232>
2233> // Initial Claude API call with tools
2234> let mut chat_req = ChatRequest::new(messages.clone()).with_tools(self.tools.clone());
2235> let mut chat_rsp = self.request_model(&chat_req).await?;
2236>
2237> // Process response content - collect text and handle tool calls
2238> for text in chat_rsp.texts() {
2239> final_text.push(text.to_string());
2527> async fn chat_loop(&mut self) -> Result<()> {
2528> println!("\nMCP Client Started!");
2529> println!("Type your queries or 'quit' to exit.");
2530>
2531> let mut stdin = BufReader::new(io::stdin());
2532> let mut input = String::new();
2533>
2534> loop {
2535> print!("\nQuery: ");
2536> std::io::Write::flush(&mut std::io::stdout())?;
2537>
2538> input.clear();
2539> if stdin.read_line(&mut input).await? == 0 {
2540> break; // EOF
2541> }
2542>
2543> let query = input.trim();
2544> if query.eq_ignore_ascii_case("quit") {
2545> break;
2546> }
2547> if query.is_empty() {
2548> continue;
2549> }
2550>
2551> match self.process_query(query).await {
2552> Ok(response) => println!("\n{}", response),
2553> Err(err) => println!("\nError: {:#}", err),
2554> }
2555> }
2556>
2557> Ok(())
22402558> }
2241>
2242> let tool_calls = chat_rsp.tool_calls();
2243> if !tool_calls.is_empty() {
2244> // Append assistant's response to message history
2245> messages.push(ChatMessage::assistant(chat_rsp.content.clone()));
2246>
2247> // Execute each tool call and collect responses
2248> let mut tool_results = Vec::new();
2249> for tool_call in tool_calls {
2250> // Add information about the tool call to final text
2251> let tool_args_str = serde_json::to_string(&tool_call.fn_arguments)
2252> .unwrap_or_else(|_| "{}".to_string());
2253>
2254> final_text.push(format!(
2255> "[Calling tool {} with args {}]",
2256> tool_call.fn_name, tool_args_str
2257> ));
2258>
2259> // Query the MCP server
2260> let tool_result = session
2261> .call_tool(CallToolRequestParam {
2262> name: tool_call.fn_name.clone().into(),
2263> arguments: tool_call.fn_arguments.as_object().cloned(),
2264> })
2265> .await
2266> .with_context(|| format!("Tool call {} failed", tool_call.fn_name))?;
2267>
2268> let payload = serde_json::to_string(&tool_result)
2269> .context("Failed to serialize tool result")?;
2270>
2271> tool_results.push(ContentPart::ToolResponse(ToolResponse::new(
2272> tool_call.call_id.clone(),
2273> payload,
2274> )));
2559> ```
2560>
2561> The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client. The `{:#}` format prints the whole `anyhow` context chain on one line.
2562>
2563> ### Cleanup
2564>
2565> Add this method inside `impl MCPClient` to stop the MCP session and child process. The closing brace ends the `impl MCPClient` block:
2566>
2567> ```rust theme={null}
2568> async fn cleanup(&mut self) -> Result<()> {
2569> if let Some(session) = self.session.take() {
2570> let _ = session.cancel().await;
22752571> }
2276>
2277> // Append tool responses to message history
2278> messages.push(ChatMessage::user(tool_results));
2279>
2280> // Build the next request and query model
2281> chat_req = ChatRequest::new(messages.clone());
2282> chat_rsp = self.request_model(&chat_req).await?;
2283>
2284> // Collect text from response
2285> for text in chat_rsp.texts() {
2286> final_text.push(text.to_string());
2287> }
2572> Ok(())
22882573> }
2289>
2290> Ok(final_text.join("\n"))
2291> }
2292> ```
2293>
2294> The method first sends the user's query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.
2295>
2296> ### Interactive Chat Interface
2297>
2298> Add the interactive terminal loop inside `impl MCPClient`:
2299>
2300> ```rust theme={null}
2301> async fn chat_loop(&mut self) -> Result<()> {
2302> println!("\nMCP Client Started!");
2303> println!("Type your queries or 'quit' to exit.");
2304>
2305> let mut stdin = BufReader::new(io::stdin());
2306> let mut input = String::new();
2307>
2308> loop {
2309> print!("\nQuery: ");
2310> std::io::Write::flush(&mut std::io::stdout())?;
2311>
2312> input.clear();
2313> if stdin.read_line(&mut input).await? == 0 {
2314> break; // EOF
2315> }
2316>
2317> let query = input.trim();
2318> if query.eq_ignore_ascii_case("quit") {
2319> break;
2320> }
2321> if query.is_empty() {
2322> continue;
2323> }
2324>
2325> match self.process_query(query).await {
2326> Ok(response) => println!("\n{}", response),
2327> Err(err) => println!("\nError: {}", err),
2328> }
2329> }
2330>
2331> Ok(())
2332> }
2333> ```
2334>
2335> The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client.
2336>
2337> ### Cleanup
2338>
2339> Add this method inside `impl MCPClient` to stop the MCP session and child process:
2340>
2341> ```rust theme={null}
2342> async fn cleanup(&mut self) -> Result<()> {
2343> if let Some(session) = self.session.take() {
2344> let _ = session.cancel().await;
2345> }
2346> Ok(())
23472574> }
23482575> ```
23492576>
23502577> ### Main Entry Point
23512578>
2352> Finally, add the asynchronous entry point outside the `impl MCPClient` block:
2579> Next, add the asynchronous entry point outside the `impl MCPClient` block:
23532580>
23542581> ```rust theme={null}
23552582> #[tokio::main]
23562583> async fn main() -> Result<()> {
2357> dotenvy::dotenv().context("Failed to load env file")?;
2584> // .env is optional; the key may come from the environment instead.
2585> let _ = dotenvy::dotenv();
23582586>
23592587> let mut args = std::env::args();
23602588> let _ = args.next();
from line 2597
23692597>
23702598> let result = async {
23712599> client.connect_to_server(&server_args).await?;
2600>
2601> // Connecting and listing tools needs no credentials; querying them
2602> // does. Matching the Python and TypeScript clients, report and exit
2603> // rather than failing, so the connection itself can be exercised
2604> // without a key.
2605> // Empty counts as unset, as it does in the other clients: `KEY= cmd`
2606> // is how the smoke test forces this path.
2607> if std::env::var("ANTHROPIC_API_KEY").map_or(true, |key| key.is_empty()) {
2608> println!(
2609> "\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:"
2610> );
2611> println!(" export ANTHROPIC_API_KEY=your-api-key-here");
2612> return Ok(());
2613> }
2614>
23722615> client.chat_loop().await
23732616> }
23742617> .await;
from line 2625
23822625> }
23832626> ```
23842627>
2385> The entry point loads `.env`, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.
2628> The entry point loads `.env` when the file exists, treats all remaining command-line arguments as the server command, connects the client, and ensures cleanup runs before exiting. When `ANTHROPIC_API_KEY` is unset or empty, the client prints how to set the key and exits after listing the server's tools. This exercises the MCP connection without credentials.
2629>
2630> ### Describing Tools to the Model
2631>
2632> Finally, add this function outside the `impl MCPClient` block:
2633>
2634> ```rust theme={null}
2635> fn convert_tools(tools: &[McpTool]) -> Vec<ToolDefinition> {
2636> tools
2637> .iter()
2638> .map(|tool| ToolDefinition {
2639> name: tool.name.to_string(),
2640> description: tool.description.as_deref().map(str::to_string),
2641> input_schema: Value::Object(tool.input_schema.as_ref().clone()),
2642> })
2643> .collect()
2644> }
2645> ```
2646>
2647> MCP and the Messages API describe tools with the same information in different Rust types. `convert_tools` copies each MCP tool's name, description, and input schema into a `ToolDefinition`, which serializes to the shape the `tools` parameter expects. The description is omitted when a tool has none.
23862648>
23872649> ### Verify the Complete File
23882650>
23892651> Before running the client, confirm the items in `src/main.rs` are placed at the correct scope:
23902652>
2391> * `new`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block.
2392> * `main` and `convert_tools` are functions outside the `impl MCPClient` block.
2653> * `new`, `validate_tool_output`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block, which opens in Client Initialization and closes after `cleanup`.
2654> * `user` and `assistant` are methods inside the `impl Message` block.
2655> * `block_type`, `main`, and `convert_tools` are functions outside both `impl` blocks.
23932656>
23942657> Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the [complete `src/main.rs` example](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs), then check that it compiles:
23952658>
from line 2685
24222685> The client will:
24232686>
24242687> 1. Start and connect to the specified MCP server
2425> 2. List the tools available from that server
2688> 2. Print the negotiated protocol version and the tools available from that server
24262689> 3. Start an interactive chat session where you can:
24272690> * Enter queries
24282691> * See tool executions
24292692> * Get responses from Claude
24302693>
2694> Connecting to the weather server prints a line like:
2695>
2696> ```text theme={null}
2697> Connected over protocol 2026-07-28 with tools: ["get_alerts", "get_forecast"]
2698> ```
2699>
2700> Without an `ANTHROPIC_API_KEY`, the client stops after this line and prints how to set the key.
2701>
24312702> ## How It Works
24322703>
2433> When you submit a query:
2434>
2435> 1. The client sends your query and the server's available tools to Claude
2704> When the user submits a query:
2705>
2706> 1. The client sends the query and the server's tool definitions to Claude
24362707> 2. Claude decides which tools, if any, to use
2437> 3. The client executes requested tools through the MCP session
2438> 4. Tool results are sent back to Claude
2439> 5. Claude provides a natural language response
2440> 6. The response is displayed in the terminal
2708> 3. The client executes every requested tool through the MCP session and validates structured results against their output schemas
2709> 4. Tool results, including failures marked with `is_error`, are sent back to Claude together with Claude's own blocks, unchanged
2710> 5. Steps 2 through 4 repeat until Claude answers without a tool call or `MAX_TOOL_TURNS` is reached
2711> 6. The collected text is displayed in the terminal
24412712>
24422713> ## Best Practices
24432714>
24442715> 1. **Error Handling**
2445> * Add context to errors at process, MCP, model API, and serialization boundaries
2716> * Add context to errors at process, MCP, and model API boundaries
2717> * Send a rejected tool call back to Claude as a `tool_result` with `is_error` set, so every `tool_use` gets an answer
24462718> * Report individual query errors without terminating the interactive session
2447> * Validate server commands before running them
2448> 2. **Resource Management**
2719> 2. **Conversation History**
2720> * Feed assistant blocks back exactly as they arrived, thinking blocks and their signatures included
2721> * Pass the tool list on every request so Claude can keep calling tools across turns
2722> * Cap the number of tool turns per query
2723> 3. **Resource Management**
24492724> * Always cancel the MCP session during cleanup
24502725> * Ensure cleanup runs even when connection or chat-loop operations fail
24512726> * Avoid starting a second server while a session is active
2452> 3. **Security**
2453> * Store API keys securely in `.env`
2454> * Review the tools exposed by a server before allowing model-driven calls
2455> * Connect only to servers and executable commands you trust
2727> 4. **Security**
2728> * Store API keys securely in `.env` or the environment
2729> * Validate structured tool results against their declared output schemas
2730> * Connect only to trusted servers and executable commands
24562731>
24572732> ## Troubleshooting
24582733>
from line 2748
24732748>
24742749> ### Environment File Issues
24752750>
2476> If you see `Failed to load env file`, ensure `.env` exists in the directory where you run the client.
2477>
2478> If the model request reports a missing API key, confirm that `.env` contains:
2751> The `.env` file is optional. When it is missing, the client reads `ANTHROPIC_API_KEY` from the environment. When the key is unset or empty, the client connects, prints the server's tools, and exits with instructions for setting the key. Export the key, or create a `.env` in the directory where the client runs that contains:
24792752>
24802753> ```text theme={null}
24812754> ANTHROPIC_API_KEY=your-api-key-goes-here
from line 2757
24842757> ### Tool and Response Errors
24852758>
24862759> * `Unable to list tools from server`: Verify the server starts successfully and communicates over stdio
2487> * `Tool call ... failed`: Verify the server tool's required arguments and environment variables
2488> * `Failed to serialize tool result`: Inspect the server's response for unsupported or malformed content
2760> * `[... failed: ...]` in the output: The server rejected the tool call. The message also goes to Claude as a failed `tool_result`, so Claude may retry with different arguments
2761> * `Tool ... declares an output schema but returned no structured content` or `Structured content from tool ... does not match its output schema`: The server's result does not satisfy its own `outputSchema`
2762> * `Anthropic request failed with ...`: The response body follows the status and names the cause, such as an invalid key or insufficient credits
2763> * `[Stopped after 10 tool-use turns]`: The query reached `MAX_TOOL_TURNS`. Raise the constant for workflows that need more rounds
24892764 
24902765## Next steps
24912766 
24922767 
Feedback