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 change · mcp

Build an MCP server changeddocs/draft/develop/build-server

Nearest release: v2.1.319, published 13 hours before upstream edited the page. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.

Upstream edited this page at 6 Nov 2026 14:02 UTC, give or take a minute or two: the time comes from Anthropic’s own sitemap rather than from a commit. This site recorded the change at 6 Nov 2026 14:07 UTC.

Upstream edited
Recorded here
Lines+178added
Lines−76removed
From line 2,018 where the diff opens
First seen 26 Aug 2026 this site's first read of the page
Recorded edits11to this page, all time

The whole hunk

from line 2018, old and new numbered
/
lines
from line 2018
20182018>
20192019> ### System requirements
20202020>
2021> * Rust 1.70 or higher installed.
2021> * Rust 1.88 or higher installed. This is the minimum version the `rmcp` crate declares.
20222022> * Cargo (comes with Rust installation).
20232023>
20242024> ### Set up your environment
from line 2063
20632063> edition = "2024"
20642064>
20652065> [dependencies]
2066> rmcp = { version = "0.3", features = ["server", "macros", "transport-io"] }
2067> tokio = { version = "1.46", features = ["full"] }
2068> reqwest = { version = "0.12", features = ["json"] }
2066> rmcp = { version = "3.4", features = ["server", "macros", "transport-io"] }
2067> tokio = { version = "1.53", features = ["full"] }
2068> reqwest = { version = "0.13", features = ["json"] }
20692069> serde = { version = "1.0", features = ["derive"] }
20702070> serde_json = "1.0"
20712071> anyhow = "1.0"
2072> tracing = "0.1"
2073> tracing-subscriber = { version = "0.3", features = ["env-filter", "std", "fmt"] }
20742072> ```
20752073>
20762074> Now let's dive into building your server.
from line 2082
20842082> ```rust theme={null}
20852083> use anyhow::Result;
20862084> use rmcp::{
2087> ServerHandler, ServiceExt,
2088> handler::server::{router::tool::ToolRouter, tool::Parameters},
2085> ErrorData, ServerHandler, ServiceExt,
2086> handler::server::{router::tool::ToolRouter, tool::schema_for_output, wrapper::Parameters},
20892087> model::*,
2090> schemars, tool, tool_handler, tool_router,
2088> schemars::{self, JsonSchema},
2089> tool, tool_handler, tool_router,
2090> transport::stdio,
20912091> };
20922092> use serde::Deserialize;
20932093> use serde::de::DeserializeOwned;
2094> use serde::Serialize;
20942095>
20952096> const NWS_API_BASE: &str = "https://api.weather.gov";
20962097> const USER_AGENT: &str = "weather-app/1.0";
20972098> ```
20982099>
2099> The `rmcp` crate provides the Model Context Protocol SDK for Rust, with features for server implementation, procedural macros, and stdio transport.
2100> The `rmcp` crate provides the Model Context Protocol SDK for Rust, with features for server implementation, procedural macros, and stdio transport. `Parameters` unwraps the arguments a client sends to a tool, `schema_for_output` builds the JSON Schema a tool advertises for its results, and `stdio` is the standard input and output transport.
21002101>
21012102> ### Data structures
21022103>
from line 2159
21582159> }
21592160> ```
21602161>
2161> Now define the request types that MCP clients will send:
2162> Each tool also returns structured content next to its text. Define the types that describe it. Deriving `JsonSchema` lets the server advertise their shape as the tool's output schema, and the doc comments become property descriptions in that schema:
21622163>
21632164> ```rust theme={null}
2164> #[derive(serde::Deserialize, schemars::JsonSchema)]
2165> pub struct MCPForecastRequest {
2165> /// One element of `get_alerts`' structured content. Declaring `Vec<Alert>` as
2166> /// the output schema makes `structuredContent` a top-level JSON array rather
2167> /// than an object wrapping one, which revision 2026-07-28 is the first to allow.
2168> #[derive(Debug, Serialize, JsonSchema)]
2169> pub struct Alert {
2170> /// The kind of weather event.
2171> event: String,
2172> /// The area the alert covers.
2173> area: String,
2174> /// How severe the event is.
2175> severity: String,
2176> /// What is happening.
2177> description: String,
2178> /// What people in the area should do.
2179> instructions: String,
2180> }
2181>
2182> /// `get_forecast`' structured content: the object case.
2183> #[derive(Debug, Serialize, JsonSchema)]
2184> pub struct Forecast {
2185> /// Latitude the forecast is for.
21662186> latitude: f32,
2187> /// Longitude the forecast is for.
21672188> longitude: f32,
2189> /// The forecast periods, soonest first.
2190> periods: Vec<Period>,
21682191> }
21692192>
2170> #[derive(serde::Deserialize, schemars::JsonSchema)]
2171> pub struct MCPAlertRequest {
2172> state: String,
2193> #[derive(Debug, Serialize, JsonSchema)]
2194> pub struct Period {
2195> name: String,
2196> temperature: i32,
2197> temperature_unit: String,
2198> wind_speed: String,
2199> wind_direction: String,
2200> detailed_forecast: String,
21732201> }
21742202> ```
21752203>
21762204> ### Helper functions
21772205>
2178> Add helper functions for making API requests and formatting responses:
2206> Add helper functions for making API requests, formatting text, and building a tool result that carries both text and structured content:
21792207>
21802208> ```rust theme={null}
21812209> async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> {
from line 2218
21902218> Ok(rsp.json::<T>().await?)
21912219> }
21922220>
2193> fn format_alert(feature: &AlertFeature) -> String {
2194> let props = &feature.properties;
2221> fn format_alert(alert: &Alert) -> String {
21952222> format!(
21962223> "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}",
2197> props.event.as_deref().unwrap_or("Unknown"),
2198> props.area_desc.as_deref().unwrap_or("Unknown"),
2199> props.severity.as_deref().unwrap_or("Unknown"),
2200> props
2201> .description
2202> .as_deref()
2203> .unwrap_or("No description available"),
2204> props
2205> .instruction
2206> .as_deref()
2207> .unwrap_or("No specific instructions provided")
2224> alert.event, alert.area, alert.severity, alert.description, alert.instructions
22082225> )
22092226> }
22102227>
2211> fn format_period(period: &ForecastPeriod) -> String {
2228> fn format_period(period: &Period) -> String {
22122229> format!(
22132230> "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}",
22142231> period.name,
from line 2236
22192236> period.detailed_forecast
22202237> )
22212238> }
2239>
2240> /// Build a result carrying both channels.
2241> fn dual_channel_result(
2242> text: String,
2243> structured: impl Serialize,
2244> ) -> Result<CallToolResult, ErrorData> {
2245> let value = serde_json::to_value(structured).map_err(|e| {
2246> ErrorData::internal_error(format!("failed to serialize structured content: {e}"), None)
2247> })?;
2248> let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
2249> result.structured_content = Some(value);
2250> Ok(result)
2251> }
22222252> ```
22232253>
2254> `dual_channel_result` builds a `CallToolResult` whose `content` holds the human-readable text and whose `structured_content` holds the JSON that matches the tool's output schema.
2255>
22242256> ### Implementing the Weather server and tools
22252257>
2258> Now define the request types that MCP clients will send:
2259>
2260> ```rust theme={null}
2261> #[derive(serde::Deserialize, JsonSchema)]
2262> pub struct MCPForecastRequest {
2263> /// Latitude of the location.
2264> latitude: f32,
2265> /// Longitude of the location.
2266> longitude: f32,
2267> }
2268>
2269> #[derive(serde::Deserialize, JsonSchema)]
2270> pub struct MCPAlertRequest {
2271> /// Two-letter US state code (e.g. CA, NY).
2272> state: String,
2273> }
2274> ```
2275>
22262276> Now let's implement the main Weather server struct with the tool handlers:
22272277>
22282278> ```rust theme={null}
2279> #[derive(Clone)]
22292280> pub struct Weather {
22302281> tool_router: ToolRouter<Weather>,
22312282> }
22322283>
2233> #[tool_router]
2284> #[tool_router(router = tool_router)]
22342285> impl Weather {
22352286> fn new() -> Self {
22362287> Self {
from line 2289
22382289> }
22392290> }
22402291>
2241> #[tool(description = "Get weather alerts for a US state.")]
2292> #[tool(
2293> description = "Get weather alerts for a US state.",
2294> output_schema = schema_for_output::<Vec<Alert>>()
2295> )]
22422296> async fn get_alerts(
22432297> &self,
22442298> Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>,
2245> ) -> String {
2246> let url = format!(
2247> "{}/alerts/active/area/{}",
2248> NWS_API_BASE,
2249> state.to_uppercase()
2250> );
2299> ) -> Result<CallToolResult, ErrorData> {
2300> let state = state.to_uppercase();
2301> let url = format!("{NWS_API_BASE}/alerts/active/area/{state}");
22512302>
2252> match make_nws_request::<AlertsResponse>(&url).await {
2253> Ok(data) => {
2254> if data.features.is_empty() {
2255> "No active alerts for this state.".to_string()
2256> } else {
2257> data.features
2258> .iter()
2259> .map(format_alert)
2260> .collect::<Vec<_>>()
2261> .join("\n---\n")
2303> let Ok(data) = make_nws_request::<AlertsResponse>(&url).await else {
2304> return Ok(CallToolResult::error(vec![ContentBlock::text(format!(
2305> "Unable to fetch alerts for {state}."
2306> ))]));
2307> };
2308>
2309> // An empty result is an empty array, not an error.
2310> let alerts: Vec<Alert> = data
2311> .features
2312> .into_iter()
2313> .map(|feature| {
2314> let props = feature.properties;
2315> Alert {
2316> event: props.event.unwrap_or_else(|| "Unknown".into()),
2317> area: props.area_desc.unwrap_or_else(|| "Unknown".into()),
2318> severity: props.severity.unwrap_or_else(|| "Unknown".into()),
2319> description: props
2320> .description
2321> .unwrap_or_else(|| "No description available".into()),
2322> instructions: props
2323> .instruction
2324> .unwrap_or_else(|| "No specific instructions provided".into()),
22622325> }
2263> }
2264> Err(_) => "Unable to fetch alerts or no alerts found.".to_string(),
2265> }
2326> })
2327> .collect();
2328>
2329> let text = if alerts.is_empty() {
2330> "No active alerts for this state.".to_string()
2331> } else {
2332> alerts
2333> .iter()
2334> .map(format_alert)
2335> .collect::<Vec<_>>()
2336> .join("\n---\n")
2337> };
2338>
2339> dual_channel_result(text, &alerts)
22662340> }
22672341>
2268> #[tool(description = "Get weather forecast for a location.")]
2342> #[tool(
2343> description = "Get weather forecast for a location.",
2344> output_schema = schema_for_output::<Forecast>()
2345> )]
22692346> async fn get_forecast(
22702347> &self,
22712348> Parameters(MCPForecastRequest {
from line 2349
22722349> latitude,
22732350> longitude,
22742351> }): Parameters<MCPForecastRequest>,
2275> ) -> String {
2352> ) -> Result<CallToolResult, ErrorData> {
22762353> let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}");
22772354> let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else {
2278> return "Unable to fetch forecast data for this location.".to_string();
2355> return Ok(CallToolResult::error(vec![ContentBlock::text(
2356> "Unable to fetch forecast data for this location.",
2357> )]));
22792358> };
22802359>
22812360> let forecast_url = points_data.properties.forecast;
2282>
22832361> let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else {
2284> return "Unable to fetch forecast data for this location.".to_string();
2362> return Ok(CallToolResult::error(vec![ContentBlock::text(
2363> "Unable to fetch detailed forecast.",
2364> )]));
22852365> };
22862366>
2287> let periods = &forecast_data.properties.periods;
2288> let forecast_summary: String = periods
2367> let forecast = Forecast {
2368> latitude,
2369> longitude,
2370> periods: forecast_data
2371> .properties
2372> .periods
2373> .into_iter()
2374> .take(5) // Next 5 periods only
2375> .map(|p| Period {
2376> name: p.name,
2377> temperature: p.temperature,
2378> temperature_unit: p.temperature_unit,
2379> wind_speed: p.wind_speed,
2380> wind_direction: p.wind_direction,
2381> detailed_forecast: p.detailed_forecast,
2382> })
2383> .collect(),
2384> };
2385>
2386> let text = forecast
2387> .periods
22892388> .iter()
2290> .take(5) // Next 5 periods only
22912389> .map(format_period)
2292> .collect::<Vec<String>>()
2390> .collect::<Vec<_>>()
22932391> .join("\n---\n");
2294> forecast_summary
2392>
2393> dual_channel_result(text, &forecast)
22952394> }
22962395> }
22972396> ```
22982397>
2299> The `#[tool_router]` macro automatically generates the routing logic, and the `#[tool]` attribute marks methods as MCP tools.
2398> The `#[tool_router]` macro automatically generates the routing logic, and the `#[tool]` attribute marks methods as MCP tools. Each tool declares an `output_schema` and returns `Result<CallToolResult, ErrorData>`. A failed request to the weather service is reported with `CallToolResult::error`, which the client receives as a tool failure.
23002399>
23012400> ### Implementing the ServerHandler
23022401>
2303> Implement the `ServerHandler` trait to define server capabilities:
2402> Implement the `ServerHandler` trait to declare the server's name, version, and capabilities:
23042403>
23052404> ```rust theme={null}
2306> #[tool_handler]
2405> #[tool_handler(router = self.tool_router)]
23072406> impl ServerHandler for Weather {
2308> fn get_info(&self) -> ServerInfo {
2309> ServerInfo {
2310> capabilities: ServerCapabilities::builder().enable_tools().build(),
2311> ..Default::default()
2312> }
2407> fn get_info(&self) -> ServerConfig {
2408> let mut info = ServerConfig::default();
2409> // Without this the server reports rmcp's own crate name and version
2410> // rather than its own.
2411> info.server_info = Implementation::new("weather", "1.0.0");
2412> info.capabilities = ServerCapabilities::builder().enable_tools().build();
2413> info
23132414> }
23142415> }
23152416> ```
23162417>
2418> `get_info` returns a `ServerConfig`. Setting `server_info` gives the server its own name and version in the `initialize` response.
2419>
23172420> ### Running the server
23182421>
23192422> Finally, implement the main function to run the server with stdio transport:
from line 2424
23212424> ```rust theme={null}
23222425> #[tokio::main]
23232426> async fn main() -> Result<()> {
2324> let transport = (tokio::io::stdin(), tokio::io::stdout());
2325> let service = Weather::new().serve(transport).await?;
2427> let service = Weather::new().serve(stdio()).await?;
23262428> service.waiting().await?;
23272429> Ok(())
23282430> }
Feedback