Skip to content
Back to search

rust-sdk

The official Rust SDK for the Model Context Protocol

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/modelcontextprotocol/rust-sdk with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/modelcontextprotocol/rust-sdk'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/modelcontextprotocol--rust-sdk/badge.svg)](/listings/modelcontextprotocol--rust-sdk)

HTML

<a href="/listings/modelcontextprotocol--rust-sdk"><img src="/api/listings/modelcontextprotocol--rust-sdk/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,918 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # RMCP
  2. [![Crates.io Version](https://img.shields.io/crates/v/rmcp)](https://crates.io/crates/rmcp)
  3. [![docs.rs](https://img.shields.io/docsrs/rmcp)](https://docs.rs/rmcp/latest/rmcp)
  4. [![CI](https://github.com/modelcontextprotocol/rust-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/modelcontextprotocol/rust-sdk/actions/workflows/ci.yml)
  5. [![License](https://img.shields.io/crates/l/rmcp)](LICENSE)
  6. An official Rust Model Context Protocol SDK implementation with tokio async runtime.
  7. > **Migrating to 3.x?** See the [migration guide](https://github.com/modelcontextprotocol/rust-sdk/discussions/969) for breaking changes and upgrade instructions.
  8. This repository contains the following crates:
  9. - [rmcp](crates/rmcp): The core crate providing the RMCP protocol implementation - see [rmcp](crates/rmcp/README.md)
  10. - [rmcp-macros](crates/rmcp-macros): A procedural macro crate for generating RMCP tool implementations - see [rmcp-macros](crates/rmcp-macros/README.md)
  11. This SDK implements the stable MCP **`2026-07-28`** specification while
  12. remaining fully compatible with the **`2025-11-25`** release and earlier
  13. versions. Features introduced in `2026-07-28` — server discovery & negotiation,
  14. transport-neutral subscriptions, long-running tasks, response caching,
  15. multi-round-trip requests, and standard HTTP routing headers — are documented
  16. below. For the full MCP specification, see
  17. [modelcontextprotocol.io](https://modelcontextprotocol.io/specification/2026-07-28).
  18. ## Table of Contents
  19. - [Usage](#usage)
  20. - [Tools](#tools)
  21. - [Resources](#resources)
  22. - [Prompts](#prompts)
  23. - [Sampling](#sampling)
  24. - [Elicitation](#elicitation)
  25. - [Roots](#roots)
  26. - [Logging](#logging)
  27. - [Completions](#completions)
  28. - [Notifications](#notifications)
  29. - [Subscriptions](#subscriptions)
  30. - [Multi-Round-Trip Requests](#multi-round-trip-requests)
  31. - [Tasks](#tasks-long-running-tool-invocations)
  32. - [Caching](#caching)
  33. - [Standard HTTP Headers](#standard-http-headers)
  34. - [Stateless Streamable HTTP](#stateless-streamable-http)
  35. - [Transports](#transports)
  36. - [Pagination](#pagination)
  37. - [Capability & Protocol Version Negotiation](#capability--protocol-version-negotiation)
  38. - [JSON Schema 2020-12](#json-schema-2020-12)
  39. - [Examples](#examples)
  40. - [OAuth Support](#oauth-support)
  41. - [Related Resources](#related-resources)
  42. - [Related Projects](#related-projects)
  43. - [Development](#development)
  44. ## Usage
  45. ### Import the crate
  46. Add the latest published version with cargo:
  47. ```sh
  48. cargo add rmcp --features server
  49. ```
  50. Or use the dev channel:
  51. ```sh
  52. cargo add rmcp --features server --git https://github.com/modelcontextprotocol/rust-sdk --branch main
  53. ```
  54. ### Third Dependencies
  55. Basic dependencies:
  56. - [tokio](https://github.com/tokio-rs/tokio)
  57. - [serde](https://github.com/serde-rs/serde)
  58. Json Schema generation (version 2020-12):
  59. - [schemars](https://github.com/GREsau/schemars)
  60. ### Build a Client
  61. <details>
  62. <summary>Start a client</summary>
  63. ```rust, ignore
  64. use rmcp::{ServiceExt, transport::{TokioChildProcess, ConfigureCommandExt}};
  65. use tokio::process::Command;
  66. #[tokio::main]
  67. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  68. let client = ().serve(TokioChildProcess::new(Command::new("npx").configure(|cmd| {
  69. cmd.arg("-y").arg("@modelcontextprotocol/server-everything");
  70. }))?).await?;
  71. Ok(())
  72. }
  73. ```
  74. </details>
  75. ### Client lifecycle modes
  76. `serve()` uses the legacy MCP lifecycle: the client sends `initialize`, receives
  77. the negotiated server information, and then sends `notifications/initialized`.
  78. Use [`ClientServiceExt::serve_with_lifecycle`](crates/rmcp/src/service/client.rs) to
  79. select another lifecycle explicitly:
  80. ```rust, ignore
  81. use rmcp::{ClientLifecycleMode, ClientServiceExt, ProtocolVersion, model::ClientConfig};
  82. // Start directly with server/discover and include client metadata on every request.
  83. let client = ClientConfig::default()
  84. .serve_with_lifecycle(
  85. transport,
  86. ClientLifecycleMode::Discover {
  87. preferred_versions: vec![ProtocolVersion::V_2026_07_28],
  88. },
  89. )
  90. .await?;
  91. // Or probe the discover lifecycle and fall back when a legacy server reports
  92. // that server/discover is not implemented or does not respond within 10 seconds.
  93. let client = ClientConfig::default()
  94. .serve_with_lifecycle(
  95. transport,
  96. ClientLifecycleMode::Auto {
  97. preferred_versions: vec![ProtocolVersion::V_2026_07_28],
  98. legacy_version: Some(ProtocolVersion::V_2025_11_25),
  99. },
  100. )
  101. .await?;
  102. ```
  103. `ClientLifecycleMode::Initialize` is equivalent to the existing `serve()` behavior.
  104. Discover startup does not send `notifications/initialized`; discovery completes
  105. startup, and each subsequent request carries its protocol version, client
  106. information, and capabilities in `_meta`.
  107. ### Build a Server
  108. <details>
  109. <summary>Build a transport</summary>
  110. ```rust, ignore
  111. use tokio::io::{stdin, stdout};
  112. let transport = (stdin(), stdout());
  113. ```
  114. </details>
  115. <details>
  116. <summary>Build a service</summary>
  117. You can easily build a service by using [`ServerHandler`](crates/rmcp/src/handler/server.rs) or [`ClientHandler`](crates/rmcp/src/handler/client.rs).
  118. ```rust, ignore
  119. let service = common::counter::Counter::new();
  120. ```
  121. </details>
  122. <details>
  123. <summary>Start the server</summary>
  124. ```rust, ignore
  125. // Await protocol startup, then receive a handle to the running service.
  126. let server = service.serve(transport).await?;
  127. ```
  128. For a server, `serve()` waits for peer input that establishes the protocol
  129. lifecycle, such as `initialize` from a legacy client. A stdio MCP server is
  130. normally launched by an MCP client as a child process. Running the executable
  131. alone in a terminal can leave this await pending because no client has sent
  132. protocol messages yet.
  133. After `serve()` returns, the service handles messages in the background. You can
  134. run other asynchronous work, then use `waiting()` to wait for shutdown. To cancel
  135. during startup, use `serve_with_ct()` with a `CancellationToken`. Tokio's stdin
  136. uses a blocking read that cannot be cancelled, so runtime shutdown may still wait
  137. for input or EOF; see [Tokio's stdin documentation](https://docs.rs/tokio/latest/tokio/io/fn.stdin.html).
  138. For example, build the counter server from the repository root, then let the
  139. MCP Inspector CLI launch it and list its tools:
  140. ```sh
  141. cargo build -p mcp-server-examples --example servers_counter_stdio
  142. npx @modelcontextprotocol/inspector --cli ./target/debug/examples/servers_counter_stdio --method tools/list
  143. ```
  144. </details>
  145. <details>
  146. <summary>Interact with the server</summary>
  147. Once the server is initialized, you can send requests or notifications:
  148. ```rust, ignore
  149. // request
  150. let roots = server.list_roots().await?;
  151. // or send notification
  152. server.notify_cancelled(...).await?;
  153. ```
  154. </details>
  155. <details>
  156. <summary>Waiting for service shutdown</summary>
  157. ```rust, ignore
  158. let quit_reason = server.waiting().await?;
  159. // or cancel it
  160. let quit_reason = server.cancel().await?;
  161. ```
  162. </details>
  163. ---
  164. ## Tools
  165. Tools let servers expose callable functions to clients. Each tool has a name, description, and a JSON Schema for its parameters. Clients discover tools via `list_tools` and invoke them via `call_tool`.
  166. **MCP Spec:** [Tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)
  167. ### Server-side
  168. The `#[tool]`, `#[tool_router]`, and `#[tool_handler]` macros handle all the wiring. For a tools-only server you can use `#[tool_router(server_handler)]` to skip the separate `ServerHandler` impl:
  169. ```rust,ignore
  170. use rmcp::{handler::server::wrapper::Parameters, schemars, tool, tool_router, ServiceExt, transport::stdio};
  171. #[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
  172. struct AddParams {
  173. a: i32,
  174. b: i32,
  175. }
  176. #[derive(Clone)]
  177. struct Calculator;
  178. #[tool_router(server_handler)]
  179. impl Calculator {
  180. #[tool(description = "Add two numbers")]
  181. fn add(&self, Parameters(AddParams { a, b }): Parameters<AddParams>) -> String {
  182. (a + b).to_string()
  183. }
  184. }
  185. #[tokio::main]
  186. async fn main() -> anyhow::Result<()> {
  187. let service = Calculator.serve(stdio()).await?;
  188. service.waiting().await?;
  189. Ok(())
  190. }
  191. ```
  192. The generated tool `inputSchema` and `outputSchema` are derived from the fields of `T`. The type name and documentation on `T` are ignored; only field names, field types, and field documentation are used.
  193. > **`2026-07-28` (SEP-2106):** `outputSchema` may now be any JSON Schema type
  194. > (not just `object`), and a tool result's `structuredContent` may be any JSON
  195. > value (string, array, number, …) rather than only an object. Existing
  196. > object-typed tools are unaffected.
  197. When you need custom server metadata or multiple capabilities (tools + prompts), use explicit `#[tool_handler]`:
  198. ```rust,ignore
  199. use rmcp::{handler::server::wrapper::Parameters, schemars, tool, tool_router, tool_handler, ServerHandler, ServiceExt};
  200. #[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
  201. struct AddParams {
  202. a: i32,
  203. b: i32,
  204. }
  205. #[derive(Clone)]
  206. struct Calculator;
  207. #[tool_router]
  208. impl Calculator {
  209. #[tool(description = "Add two numbers")]
  210. fn add(&self, Parameters(AddParams { a, b }): Parameters<AddParams>) -> String {
  211. (a + b).to_string()
  212. }
  213. }
  214. #[tool_handler(name = "calculator", version = "1.0.0", instructions = "A simple calculator")]
  215. impl ServerHandler for Calculator {}
  216. ```
  217. See [`crates/rmcp-macros`](crates/rmcp-macros/README.md) for full macro documentation.
  218. #### Tool result content types
  219. Beyond a plain `String`, tools can return images, audio, embedded resources, and
  220. mixed content. Build a `CallToolResult` from a `Vec<ContentBlock>`:
  221. ```rust,ignore
  222. use rmcp::model::{CallToolResult, ContentBlock, ResourceContents};
  223. #[tool(description = "Render a chart")]
  224. async fn chart(&self) -> Result<CallToolResult, McpError> {
  225. let png_base64 = render_png(); // base64-encoded image bytes
  226. let wav_base64 = render_wav(); // base64-encoded audio bytes
  227. Ok(CallToolResult::success(vec![
  228. // Text
  229. ContentBlock::text("Here is your chart:"),
  230. // Image — base64 data + MIME type
  231. ContentBlock::image(png_base64, "image/png"),
  232. // Audio — base64 data + MIME type
  233. ContentBlock::audio(wav_base64, "audio/wav"),
  234. // Embedded resource — inline text (or ResourceContents::blob for binary)
  235. ContentBlock::resource(ResourceContents::text(
  236. "chart source data",
  237. "chart://last/data.csv",
  238. )),
  239. ]))
  240. }
  241. # fn render_png() -> String { String::new() }
  242. # fn render_wav() -> String { String::new() }
  243. ```
  244. Image and audio data are base64 strings with a MIME type. For embedded
  245. resources, `ResourceContents::text(..)` inlines text and
  246. `ResourceContents::blob(base64, uri)` inlines binary.
  247. #### Error handling
  248. Two failure modes, chosen by **whose problem it is**:
  249. - **Tool-level error** — `Ok(CallToolResult::error(vec![...]))`. The tool ran but
  250. failed in a way the caller should see (no rows matched, upstream 500). The
  251. client renders your `content`, so the message reaches the user. Use this for
  252. almost every "the tool ran and didn't work" case.
  253. - **Protocol error** — `Err(McpError)` with a JSON-RPC code (e.g.
  254. `McpError::invalid_params(..)`). Use this when the server can't route or process
  255. the request at all; clients render these opaquely, so the caller does **not**
  256. see your message.
  257. ```rust,ignore
  258. use rmcp::model::{CallToolResult, ContentBlock};
  259. use rmcp::ErrorData as McpError;
  260. #[tool(description = "Look up a record")]
  261. async fn lookup(&self, Parameters(args): Parameters<LookupArgs>) -> Result<CallToolResult, McpError> {
  262. // Malformed request — the server can't run anything → protocol error.
  263. if args.query.is_empty() {
  264. return Err(McpError::invalid_params("query must be non-empty", None));
  265. }
  266. // Tool ran, no result → tool-level error the user should see.
  267. let rows = self.run_query(&args.query).await;
  268. if rows.is_empty() {
  269. return Ok(CallToolResult::error(vec![ContentBlock::text(
  270. format!("no rows matched '{}'", args.query),
  271. )]));
  272. }
  273. Ok(CallToolResult::success(vec![ContentBlock::text(format_rows(&rows))]))
  274. }
  275. ```
  276. ### Client-side
  277. ```rust,ignore
  278. use rmcp::model::CallToolRequestParams;
  279. // List all tools
  280. let tools = client.list_all_tools().await?;
  281. // Call a tool by name
  282. let result = client.call_tool(CallToolRequestParams::new("add")).await?;
  283. ```
  284. **Example:** [`examples/servers/src/common/calculator.rs`](examples/servers/src/common/calculator.rs) (server), [`examples/servers/src/calculator_stdio.rs`](examples/servers/src/calculator_stdio.rs) (stdio runner)
  285. ---
  286. ## Resources
  287. Resources let servers expose data (files, database records, API responses) that clients can read. Each resource is identified by a URI and returns content as text or binary (base64-encoded) data. Resource templates allow servers to declare URI patterns with dynamic parameters.
  288. **MCP Spec:** [Resources](https://modelcontextprotocol.io/specification/2026-07-28/server/resources)
  289. ### Server-side
  290. Implement `list_resources()`, `read_resource()`, and optionally `list_resource_templates()` on the `ServerHandler` trait. Enable the resources capability in `get_info()`.
  291. ```rust
  292. use rmcp::{
  293. ErrorData as McpError, RoleServer, ServerHandler, ServiceExt,
  294. model::*,
  295. service::RequestContext,
  296. transport::stdio,
  297. };
  298. use serde_json::json;
  299. #[derive(Clone)]
  300. struct MyServer;
  301. impl ServerHandler for MyServer {
  302. fn get_info(&self) -> ServerConfig {
  303. ServerConfig::new(
  304. ServerCapabilities::builder()
  305. .enable_resources()
  306. .build(),
  307. )
  308. }
  309. async fn list_resources(
  310. &self,
  311. _request: Option<PaginatedRequestParams>,
  312. _context: RequestContext<RoleServer>,
  313. ) -> Result<ListResourcesResult, McpError> {
  314. Ok(ListResourcesResult {
  315. resources: vec![
  316. Resource::new("file:///config.json", "config"),
  317. Resource::new("memo://insights", "insights"),
  318. ],
  319. next_cursor: None,
  320. meta: None,
  321. })
  322. }
  323. async fn read_resource(
  324. &self,
  325. request: ReadResourceRequestParams,
  326. _context: RequestContext<RoleServer>,
  327. ) -> Result<ReadResourceResult, McpError> {
  328. match request.uri.as_str() {
  329. "file:///config.json" => Ok(ReadResourceResult::new(vec![
  330. ResourceContents::text(r#"{"key": "value"}"#, &request.uri),
  331. ])),
  332. "memo://insights" => Ok(ReadResourceResult::new(vec![
  333. ResourceContents::text("Analysis results...", &request.uri),
  334. ])),
  335. // Binary resource — base64-encode the bytes and return a blob.
  336. "file:///logo.png" => {
  337. use base64::{Engine, prelude::BASE64_STANDARD};
  338. let bytes = std::fs::read("logo.png").unwrap_or_default();
  339. let blob = BASE64_STANDARD.encode(bytes);
  340. Ok(ReadResourceResult::new(vec![
  341. ResourceContents::blob(blob, &request.uri)
  342. .with_mime_type("image/png"),
  343. ]))
  344. }
  345. // Template-expanded URI — the client fills in `{user_id}` from the
  346. // `users://{user_id}/profile` template declared in
  347. // `list_resource_templates`, and the server reads the concrete URI.
  348. uri if uri.starts_with("users://") && uri.ends_with("/profile") => {
  349. let user_id = uri
  350. .trim_start_matches("users://")
  351. .trim_end_matches("/profile");
  352. Ok(ReadResourceResult::new(vec![ResourceContents::text(
  353. format!(r#"{{"id": "{user_id}", "name": "User {user_id}"}}"#),
  354. uri,
  355. )]))
  356. }
  357. _ => Err(McpError::resource_not_found(
  358. "resource_not_found",
  359. Some(json!({ "uri": request.uri })),
  360. )),
  361. }
  362. }
  363. async fn list_resource_templates(
  364. &self,
  365. _request: Option<PaginatedRequestParams>,
  366. _context: RequestContext<RoleServer>,
  367. ) -> Result<ListResourceTemplatesResult, McpError> {
  368. // Declare a URI template with a `{user_id}` parameter. Clients expand it
  369. // (e.g. `users://42/profile`) and pass the concrete URI to `read_resource`.
  370. Ok(ListResourceTemplatesResult {
  371. resource_templates: vec![
  372. ResourceTemplate::new("users://{user_id}/profile", "user-profile"),
  373. ],
  374. next_cursor: None,
  375. meta: None,
  376. })
  377. }
  378. }
  379. ```
  380. ### Client-side
  381. ```rust
  382. use rmcp::model::{ReadResourceRequestParams};
  383. // List all resources (handles pagination automatically)
  384. let resources = client.list_all_resources().await?;
  385. // Read a specific resource by URI
  386. let result = client.read_resource(
  387. ReadResourceRequestParams::new("file:///config.json"),
  388. ).await?;
  389. // List resource templates, then read a resource through one by expanding its
  390. // parameters into a concrete URI (`users://{user_id}/profile` → `users://42/profile`).
  391. let templates = client.list_all_resource_templates().await?;
  392. let profile = client.read_resource(
  393. ReadResourceRequestParams::new("users://42/profile"),
  394. ).await?;
  395. ```
  396. ### Notifications
  397. Servers can notify clients when the resource list changes or when a specific resource is updated:
  398. ```rust
  399. // Notify that the resource list has changed (clients should re-fetch)
  400. context.peer.notify_resource_list_changed().await?;
  401. // Notify that a specific resource was updated
  402. context.peer.notify_resource_updated(
  403. ResourceUpdatedNotificationParam::new("file:///config.json"),
  404. ).await?;
  405. ```
  406. Clients handle these via `ClientHandler`:
  407. ```rust
  408. impl ClientHandler for MyClient {
  409. async fn on_resource_list_changed(
  410. &self,
  411. _context: NotificationContext<RoleClient>,
  412. ) {
  413. // Re-fetch the resource list
  414. }
  415. async fn on_resource_updated(
  416. &self,
  417. params: ResourceUpdatedNotificationParam,
  418. _context: NotificationContext<RoleClient>,
  419. ) {
  420. // Re-read the updated resource at params.uri
  421. }
  422. }
  423. ```
  424. **Example:** [`examples/servers/src/common/counter.rs`](examples/servers/src/common/counter.rs) (server), [`examples/clients/src/everything_stdio.rs`](examples/clients/src/everything_stdio.rs) (client)
  425. ---
  426. ## Prompts
  427. Prompts are reusable message templates that servers expose to clients. They accept typed arguments and return conversation messages. The `#[prompt]` macro handles argument validation and routing automatically.
  428. **MCP Spec:** [Prompts](https://modelcontextprotocol.io/specification/2026-07-28/server/prompts)
  429. ### Server-side
  430. Use the `#[prompt_router]`, `#[prompt]`, and `#[prompt_handler]` macros to define prompts declaratively. Arguments are defined as structs deriving `JsonSchema`.
  431. ```rust
  432. use rmcp::{
  433. ErrorData as McpError, RoleServer, ServerHandler, ServiceExt,
  434. handler::server::{router::prompt::PromptRouter, wrapper::Parameters},
  435. model::*,
  436. prompt, prompt_handler, prompt_router,
  437. schemars::JsonSchema,
  438. service::RequestContext,
  439. transport::stdio,
  440. };
  441. use serde::{Deserialize, Serialize};
  442. #[derive(Debug, Serialize, Deserialize, JsonSchema)]
  443. pub struct CodeReviewArgs {
  444. #[schemars(description = "Programming language of the code")]
  445. pub language: String,
  446. #[schemars(description = "Focus areas for the review")]
  447. pub focus_areas: Option<Vec<String>>,
  448. }
  449. #[derive(Clone)]
  450. pub struct MyServer {
  451. prompt_router: PromptRouter<Self>,
  452. }
  453. #[prompt_router]
  454. impl MyServer {
  455. fn new() -> Self {
  456. Self { prompt_router: Self::prompt_router() }
  457. }
  458. /// Simple prompt without parameters
  459. #[prompt(name = "greeting", description = "A simple greeting")]
  460. async fn greeting(&self) -> Vec<PromptMessage> {
  461. vec![PromptMessage::new_text(
  462. Role::User,
  463. "Hello! How can you help me today?",
  464. )]
  465. }
  466. /// Prompt with typed arguments
  467. #[prompt(name = "code_review", description = "Review code in a given language")]
  468. async fn code_review(
  469. &self,
  470. Parameters(args): Parameters<CodeReviewArgs>,
  471. ) -> Result<GetPromptResult, McpError> {
  472. let focus = args.focus_areas
  473. .unwrap_or_else(|| vec!["correctness".into()]);
  474. Ok(GetPromptResult::new(vec![
  475. PromptMessage::new_text(
  476. Role::User,
  477. format!("Review my {} code. Focus on: {}", args.language, focus.join(", ")),
  478. ),
  479. ])
  480. .with_description(format!("Code review for {}", args.language)))
  481. }
  482. }
  483. #[prompt_handler]
  484. impl ServerHandler for MyServer {
  485. fn get_info(&self) -> ServerConfig {
  486. ServerConfig::new(ServerCapabilities::builder().enable_prompts().build())
  487. }
  488. }
  489. ```
  490. Prompt functions support several return types:
  491. - `Vec<PromptMessage>` -- simple message list
  492. - `GetPromptResult` -- messages with an optional description
  493. - `Result<T, McpError>` -- either of the above, with error handling
  494. #### Image and embedded-resource content
  495. A `PromptMessage` can also carry an image or embedded resource. Use the
  496. dedicated constructors (image/audio require the `base64` feature):
  497. ```rust,ignore
  498. use rmcp::model::{PromptMessage, Role};
  499. // Image content — raw bytes are base64-encoded for you.
  500. let screenshot: &[u8] = load_png();
  501. let msg = PromptMessage::new_image(Role::User, screenshot, "image/png", None, None);
  502. // Embedded resource — inline a text resource by URI. Pass `Some(text)` for a
  503. // text resource, or `None` for a blob resource.
  504. let msg = PromptMessage::new_resource(
  505. Role::User,
  506. "file:///spec.md".to_string(),
  507. Some("text/markdown".to_string()),
  508. Some("# Specification\n...".to_string()),
  509. None, None, None,
  510. );
  511. # fn load_png() -> &'static [u8] { &[] }
  512. ```
  513. ### Client-side
  514. ```rust
  515. use rmcp::model::GetPromptRequestParams;
  516. // List all prompts
  517. let prompts = client.list_all_prompts().await?;
  518. // Get a prompt with arguments
  519. let result = client.get_prompt(GetPromptRequestParams {
  520. meta: None,
  521. name: "code_review".into(),
  522. arguments: Some(rmcp::object!({
  523. "language": "Rust",
  524. "focus_areas": ["performance", "safety"]
  525. })),
  526. }).await?;
  527. ```
  528. ### Notifications
  529. ```rust
  530. // Server: notify that available prompts have changed
  531. context.peer.notify_prompt_list_changed().await?;
  532. ```
  533. **Example:** [`examples/servers/src/prompt_stdio.rs`](examples/servers/src/prompt_stdio.rs) (server), [`examples/clients/src/everything_stdio.rs`](examples/clients/src/everything_stdio.rs) (client)
  534. ---
  535. ## Sampling
  536. > **Deprecated (SEP-2577):** Sampling is deprecated and will be removed in a future release. It remains fully functional for now. See [SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577).
  537. Sampling flips the usual direction: the server asks the client to run an LLM completion. The server sends a `create_message` request, the client processes it through its LLM, and returns the result.
  538. **MCP Spec:** [Sampling](https://modelcontextprotocol.io/specification/2026-07-28/client/sampling)
  539. ### Server-side (requesting sampling)
  540. Access the client's sampling capability through `context.peer.create_message()`:
  541. ```rust
  542. use rmcp::model::*;
  543. // Inside a ServerHandler method (e.g., call_tool):
  544. let response = context.peer.create_message(
  545. CreateMessageRequestParams::new(
  546. vec![SamplingMessage::user_text("Explain this error: connection refused")],
  547. 150,
  548. )
  549. .with_model_preferences(
  550. ModelPreferences::new()
  551. .with_hints(vec![ModelHint::new("claude")])
  552. .with_cost_priority(0.3)
  553. .with_speed_priority(0.8)
  554. .with_intelligence_priority(0.7),
  555. )
  556. .with_system_prompt("You are a helpful assistant.")
  557. .with_include_context(ContextInclusion::None)
  558. .with_temperature(0.7),
  559. ).await?;
  560. // Extract the response text
  561. let text = response.message.content
  562. .first()
  563. .and_then(|c| c.as_text())
  564. .map(|t| &t.text);
  565. ```
  566. ### Client-side (handling sampling)
  567. On the client side, implement `ClientHandler::create_message()`. This is where you'd call your actual LLM:
  568. ```rust
  569. use rmcp::{ClientHandler, model::*, service::{RequestContext, RoleClient}};
  570. #[derive(Clone, Default)]
  571. struct MyClient;
  572. impl ClientHandler for MyClient {
  573. async fn create_message(
  574. &self,
  575. params: CreateMessageRequestParams,
  576. _context: RequestContext<RoleClient>,
  577. ) -> Result<CreateMessageResult, ErrorData> {
  578. // Forward to your LLM, or return a mock response:
  579. let response_text = call_your_llm(&params.messages).await;
  580. Ok(CreateMessageResult::new(
  581. SamplingMessage::assistant_text(response_text),
  582. "my-model".into(),
  583. )
  584. .with_stop_reason(CreateMessageResult::STOP_REASON_END_TURN))
  585. }
  586. }
  587. ```
  588. **Example:** [`examples/servers/src/sampling_stdio.rs`](examples/servers/src/sampling_stdio.rs) (server), [`examples/clients/src/sampling_stdio.rs`](examples/clients/src/sampling_stdio.rs) (client)
  589. ---
  590. ## Elicitation
  591. Elicitation lets a server pause mid-operation to ask the user for input, in one
  592. of two modes: **form mode** (structured fields with a JSON Schema) or **URL
  593. mode** (send the user to a web page and wait for completion).
  594. **MCP Spec:** [Elicitation](https://modelcontextprotocol.io/specification/2026-07-28/client/elicitation)
  595. ### Server-side (form mode)
  596. Define a struct deriving `JsonSchema`, mark it `elicit_safe!`, and call
  597. `elicit::<T>()` on the peer. Schema validation, defaults, and enum choices all
  598. come from the type.
  599. ```rust,ignore
  600. use rmcp::{elicit_safe, model::*, service::{RequestContext, RoleServer}};
  601. use schemars::JsonSchema;
  602. use serde::{Deserialize, Serialize};
  603. #[derive(Debug, Serialize, Deserialize, JsonSchema)]
  604. #[schemars(description = "User information")]
  605. pub struct UserInfo {
  606. #[schemars(description = "User's name")]
  607. pub name: String,
  608. // Optional field; omitted if the user doesn't provide it.
  609. #[serde(default)]
  610. #[schemars(description = "Preferred greeting")]
  611. pub greeting: Option<String>,
  612. }
  613. // Whitelist the type for elicitation (schema-validated on both ends).
  614. elicit_safe!(UserInfo);
  615. #[tool(description = "Greet the user")]
  616. async fn greet(&self, ctx: RequestContext<RoleServer>) -> Result<CallToolResult, McpError> {
  617. // Returns Ok(Some(UserInfo)) if the user accepts.
  618. // Decline and cancel are returned as ElicitationError variants.
  619. match ctx.peer.elicit::<UserInfo>("Please provide your name").await {
  620. Ok(Some(info)) => Ok(CallToolResult::success(vec![ContentBlock::text(
  621. format!("Hello, {}!", info.name),
  622. )])),
  623. Ok(None) => Ok(CallToolResult::success(vec![ContentBlock::text(
  624. "No name provided.",
  625. )])),
  626. Err(e) => Ok(CallToolResult::error(vec![ContentBlock::text(
  627. format!("Elicitation failed: {e}"),
  628. )])),
  629. }
  630. }
  631. ```
  632. #### Enum values
  633. Enum fields become a choice list. `schemars` needs two hints to inline and type
  634. the enum correctly:
  635. ```rust,ignore
  636. #[derive(Debug, Serialize, Deserialize, JsonSchema, Default)]
  637. #[schemars(inline)] // inline the enum into the parent schema
  638. #[schemars(extend("type" = "string"))] // schemars omits `type` for enums; add it
  639. enum Priority {
  640. #[schemars(title = "Low priority")]
  641. #[default]
  642. Low,
  643. #[schemars(title = "High priority")]
  644. High,
  645. }
  646. ```
  647. See [`examples/servers/src/elicitation_enum_inference.rs`](examples/servers/src/elicitation_enum_inference.rs)
  648. for single-select, multi-select, titled, and defaulted enum forms.
  649. ### Server-side (URL mode)
  650. For flows a form can't capture (OAuth consent, a payment page), send the user to
  651. a URL. `elicit_url` returns the user's `ElicitationAction` rather than typed data:
  652. ```rust,ignore
  653. use rmcp::model::ElicitationAction;
  654. use url::Url;
  655. let action = ctx.peer.elicit_url(
  656. "Please complete setup in your browser",
  657. Url::parse("https://example.com/setup").unwrap(),
  658. "setup-123", // a unique elicitation id
  659. ).await?;
  660. match action {
  661. ElicitationAction::Accept => { /* user consented */ }
  662. ElicitationAction::Decline => { /* user declined */ }
  663. ElicitationAction::Cancel => { /* user aborted */ }
  664. }
  665. ```
  666. ### Client-side
  667. Implement `ClientHandler::create_elicitation()`, matching on the request variant
  668. to handle form vs. URL mode:
  669. ```rust,ignore
  670. use rmcp::{ClientHandler, model::*, service::{RequestContext, RoleClient}};
  671. impl ClientHandler for MyClient {
  672. async fn create_elicitation(
  673. &self,
  674. request: ElicitRequestParams,
  675. _context: RequestContext<RoleClient>,
  676. ) -> Result<ElicitResult, ErrorData> {
  677. match request {
  678. ElicitRequestParams::FormElicitationParams { message, .. } => {
  679. // Show `message` + the requested schema, collect input, then:
  680. Ok(ElicitResult {
  681. action: ElicitationAction::Accept,
  682. content: Some(rmcp::object!({ "name": "Ada" })),
  683. meta: None,
  684. })
  685. }
  686. ElicitRequestParams::UrlElicitationParams { url, .. } => {
  687. // Open `url`, wait for the user, then report the action.
  688. let _ = url;
  689. Ok(ElicitResult { action: ElicitationAction::Accept, content: None, meta: None })
  690. }
  691. }
  692. }
  693. }
  694. ```
  695. On completion the client sends a `notifications/elicitation/response`
  696. notification to release the waiting server-side `elicit_url` call.
  697. **Example:** [`examples/servers/src/elicitation_stdio.rs`](examples/servers/src/elicitation_stdio.rs) (form + URL), [`examples/servers/src/elicitation_enum_inference.rs`](examples/servers/src/elicitation_enum_inference.rs) (enum forms)
  698. ---
  699. ## Roots
  700. > **Deprecated (SEP-2577):** Roots is deprecated and will be removed in a future release. It remains fully functional for now. See [SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577).
  701. Roots tell servers which directories or projects the client is working in. A root is a URI (typically `file://`) pointing to a workspace or repository. Servers can query roots to know where to look for files and how to scope their work.
  702. **MCP Spec:** [Roots](https://modelcontextprotocol.io/specification/2026-07-28/client/roots)
  703. ### Server-side
  704. Ask the client for its root list, and handle change notifications:
  705. ```rust
  706. use rmcp::{ServerHandler, model::*, service::{NotificationContext, RoleServer}};
  707. impl ServerHandler for MyServer {
  708. // Query the client for its roots
  709. async fn call_tool(
  710. &self,
  711. request: CallToolRequestParams,
  712. context: RequestContext<RoleServer>,
  713. ) -> Result<CallToolResult, ErrorData> {
  714. let roots = context.peer.list_roots().await?;
  715. // Use roots.roots to understand workspace boundaries
  716. // ...
  717. }
  718. // Called when the client's root list changes
  719. async fn on_roots_list_changed(
  720. &self,
  721. _context: NotificationContext<RoleServer>,
  722. ) {
  723. // Re-fetch roots to stay current
  724. }
  725. }
  726. ```
  727. ### Client-side
  728. Clients declare roots capability and implement `list_roots()`:
  729. ```rust
  730. use rmcp::{ClientHandler, model::*};
  731. impl ClientHandler for MyClient {
  732. async fn list_roots(
  733. &self,
  734. _context: RequestContext<RoleClient>,
  735. ) -> Result<ListRootsResult, ErrorData> {
  736. Ok(ListRootsResult::new(vec![
  737. Root::new("file:///home/user/project").with_name("My Project"),
  738. ]))
  739. }
  740. }
  741. ```
  742. Clients notify the server when roots change:
  743. ```rust
  744. // After adding or removing a workspace root:
  745. client.notify_roots_list_changed().await?;
  746. ```
  747. ---
  748. ## Logging
  749. > **Deprecated (SEP-2577):** Logging is deprecated and will be removed in a future release. It remains fully functional for now. See [SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577).
  750. Servers can send structured log messages to clients. The client sets a minimum severity level, and the server sends messages through the peer notification interface.
  751. **MCP Spec:** [Logging](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/logging)
  752. ### Server-side
  753. Enable the logging capability, handle level changes from the client, and send log messages via the peer:
  754. ```rust
  755. use rmcp::{ServerHandler, model::*, service::RequestContext};
  756. impl ServerHandler for MyServer {
  757. fn get_info(&self) -> ServerConfig {
  758. ServerConfig::new(
  759. ServerCapabilities::builder()
  760. .enable_logging()
  761. .build(),
  762. )
  763. }
  764. // Client sets the minimum log level
  765. async fn set_level(
  766. &self,
  767. request: SetLevelRequestParams,
  768. _context: RequestContext<RoleServer>,
  769. ) -> Result<(), ErrorData> {
  770. // Store request.level and filter future log messages accordingly
  771. Ok(())
  772. }
  773. }
  774. // Send a log message from any handler with access to the peer:
  775. context.peer.notify_logging_message(
  776. LoggingMessageNotificationParam::new(
  777. LoggingLevel::Info,
  778. serde_json::json!({
  779. "message": "Processing completed",
  780. "items_processed": 42
  781. }),
  782. )
  783. .with_logger("my-server"),
  784. ).await?;
  785. ```
  786. Available log levels (from least to most severe): `Debug`, `Info`, `Notice`, `Warning`, `Error`, `Critical`, `Alert`, `Emergency`.
  787. ### Client-side
  788. Clients handle incoming log messages via `ClientHandler`:
  789. ```rust
  790. impl ClientHandler for MyClient {
  791. async fn on_logging_message(
  792. &self,
  793. params: LoggingMessageNotificationParam,
  794. _context: NotificationContext<RoleClient>,
  795. ) {
  796. println!("[{}] {}: {}", params.level,
  797. params.logger.unwrap_or_default(), params.data);
  798. }
  799. }
  800. ```
  801. Clients can also set the server's log level:
  802. ```rust
  803. client.set_level(SetLevelRequestParams::new(LoggingLevel::Warning)).await?;
  804. ```
  805. ---
  806. ## Completions
  807. Completions give auto-completion suggestions for prompt or resource template arguments. As a user fills in arguments, the client can ask the server for suggestions based on what's already been entered.
  808. **MCP Spec:** [Completions](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/completion)
  809. ### Server-side
  810. Enable the completions capability and implement the `complete()` handler. Use `request.context` to inspect previously filled arguments:
  811. ```rust
  812. use rmcp::{ErrorData as McpError, ServerHandler, model::*, service::RequestContext, RoleServer};
  813. impl ServerHandler for MyServer {
  814. fn get_info(&self) -> ServerConfig {
  815. ServerConfig::new(
  816. ServerCapabilities::builder()
  817. .enable_completions()
  818. .enable_prompts()
  819. .build(),
  820. )
  821. }
  822. async fn complete(
  823. &self,
  824. request: CompleteRequestParams,
  825. _context: RequestContext<RoleServer>,
  826. ) -> Result<CompleteResult, McpError> {
  827. let values = match &request.r#ref {
  828. // Completion for a prompt argument (`ref/prompt`).
  829. Reference::Prompt(prompt_ref) if prompt_ref.name == "sql_query" => {
  830. match request.argument.name.as_str() {
  831. "operation" => vec!["SELECT", "INSERT", "UPDATE", "DELETE"],
  832. "table" => vec!["users", "orders", "products"],
  833. "columns" => {
  834. // Adapt suggestions based on previously filled arguments
  835. if let Some(ctx) = &request.context {
  836. if let Some(op) = ctx.get_argument("operation") {
  837. match op.to_uppercase().as_str() {
  838. "SELECT" | "UPDATE" => {
  839. vec!["id", "name", "email", "created_at"]
  840. }
  841. _ => vec![],
  842. }
  843. } else { vec![] }
  844. } else { vec![] }
  845. }
  846. _ => vec![],
  847. }
  848. }
  849. // Completion for a resource-template argument (`ref/resource`). The
  850. // `uri` identifies the template (e.g. `users://{user_id}/profile`)
  851. // and `argument.name` is the template variable being completed.
  852. Reference::Resource(resource_ref)
  853. if resource_ref.uri == "users://{user_id}/profile" =>
  854. {
  855. match request.argument.name.as_str() {
  856. "user_id" => vec!["1", "2", "42"],
  857. _ => vec![],
  858. }
  859. }
  860. _ => vec![],
  861. };
  862. // Filter by the user's partial input
  863. let filtered: Vec<String> = values.into_iter()
  864. .map(String::from)
  865. .filter(|v| v.to_lowercase().contains(&request.argument.value.to_lowercase()))
  866. .collect();
  867. let completion = CompletionInfo::with_pagination(filtered, None, false)
  868. .map_err(|e| McpError::internal_error(e, None))?;
  869. Ok(CompleteResult::new(completion))
  870. }
  871. }
  872. ```
  873. ### Client-side
  874. ```rust
  875. use rmcp::model::*;
  876. // Completion for a prompt argument.
  877. let result = client.complete(CompleteRequestParams::new(
  878. Reference::for_prompt("sql_query"),
  879. ArgumentInfo::new("operation", "SEL"),
  880. )).await?;
  881. // result.completion.values contains suggestions like ["SELECT"]
  882. // Completion for a resource-template argument: reference the template by URI
  883. // and complete one of its variables (`user_id`).
  884. let resource_completion = client.complete(CompleteRequestParams::new(
  885. Reference::for_resource("users://{user_id}/profile"),
  886. ArgumentInfo::new("user_id", "4"),
  887. )).await?;
  888. // resource_completion.completion.values contains suggestions like ["42"]
  889. ```
  890. **Example:** [`examples/servers/src/completion_stdio.rs`](examples/servers/src/completion_stdio.rs)
  891. ---
  892. ## Notifications
  893. Notifications are fire-and-forget messages -- no response is expected. They cover progress updates, cancellation, and lifecycle events. Both sides can send and receive them.
  894. **MCP Spec:** [Notifications](https://modelcontextprotocol.io/specification/2026-07-28/basic#notifications)
  895. ### Progress notifications
  896. Servers can report progress during long-running operations:
  897. ```rust
  898. use rmcp::model::*;
  899. // Inside a tool handler:
  900. for i in 0..total_items {
  901. process_item(i).await;
  902. context.peer.notify_progress(
  903. ProgressNotificationParam::new(
  904. ProgressToken(NumberOrString::Number(i as i64)),
  905. i as f64,
  906. )
  907. .with_total(total_items as f64)
  908. .with_message(format!("Processing item {}/{}", i + 1, total_items)),
  909. ).await?;
  910. }
  911. ```
  912. ### Cancellation
  913. Either side can cancel an in-progress request:
  914. ```rust
  915. // Send a cancellation
  916. context.peer.notify_cancelled(CancelledNotificationParam::new(
  917. Some(the_request_id),
  918. Some("User requested cancellation".into()),
  919. )).await?;
  920. ```
  921. Handle cancellation in `ServerHandler` or `ClientHandler`:
  922. ```rust
  923. impl ServerHandler for MyServer {
  924. async fn on_cancelled(
  925. &self,
  926. params: CancelledNotificationParam,
  927. _context: NotificationContext<RoleServer>,
  928. ) {
  929. // Abort work for params.request_id
  930. }
  931. }
  932. ```
  933. ### Ping
  934. Either side can send a `ping` request to check that its counterpart is still
  935. responsive and the connection is alive. A ping carries no parameters and the
  936. receiver replies with an empty result. Because pings can flow in both
  937. directions, `rmcp` handles them symmetrically:
  938. - **Sending a ping** — construct a `PingRequest` and send it over the peer.
  939. A client pings the server with `ClientRequest::PingRequest`; a server pings
  940. the client with `ServerRequest::PingRequest`. `send_request` resolves once the
  941. empty response arrives, so a returned `Ok` confirms the peer is reachable:
  942. ```rust
  943. use rmcp::model::{PingRequest, ServerRequest};
  944. // From a server, ping the connected client to verify it is still alive.
  945. context.peer
  946. .send_request(ServerRequest::PingRequest(PingRequest::default()))
  947. .await?;
  948. ```
  949. ```rust
  950. use rmcp::model::{ClientRequest, PingRequest};
  951. // From a client, ping the server. `running` is the value returned by serve().
  952. running
  953. .send_request(ClientRequest::PingRequest(PingRequest::default()))
  954. .await?;
  955. ```
  956. - **Responding to a ping** — `rmcp` answers incoming pings automatically. The
  957. default `ping` method on `ServerHandler` and `ClientHandler` returns an empty
  958. result, so no code is required. Override it only if you want to run custom
  959. logic (for example, health checks) when a ping arrives:
  960. ```rust
  961. impl ServerHandler for MyServer {
  962. async fn ping(
  963. &self,
  964. _context: RequestContext<RoleServer>,
  965. ) -> Result<(), McpError> {
  966. // Custom liveness logic here, if any.
  967. Ok(())
  968. }
  969. }
  970. ```
  971. **MCP Spec:** [Ping](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/ping)
  972. ### Initialized notification
  973. Legacy clients send `initialized` after the `initialize` handshake completes.
  974. Clients using `ClientLifecycleMode::Discover` do not send this notification:
  975. ```rust
  976. // Sent automatically by rmcp during the legacy serve() handshake.
  977. // Servers handle it via:
  978. impl ServerHandler for MyServer {
  979. async fn on_initialized(
  980. &self,
  981. _context: NotificationContext<RoleServer>,
  982. ) {
  983. // Server is ready to receive requests
  984. }
  985. }
  986. ```
  987. ### List-changed notifications
  988. When available tools, prompts, or resources change, tell the client:
  989. ```rust
  990. context.peer.notify_tool_list_changed().await?;
  991. context.peer.notify_prompt_list_changed().await?;
  992. context.peer.notify_resource_list_changed().await?;
  993. ```
  994. **Example:** [`examples/servers/src/common/progress_demo.rs`](examples/servers/src/common/progress_demo.rs)
  995. ---
  996. ## Subscriptions
  997. Protocol `2026-07-28` replaces `resources/subscribe`, `resources/unsubscribe`, and
  998. the standalone HTTP GET stream with the transport-neutral, long-lived
  999. `subscriptions/listen` request. Each requested notification category is opt-in.
  1000. **MCP Spec:** [Subscriptions](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions)
  1001. ### Server-side
  1002. Declare the notification capabilities you serve, return the accepted subset,
  1003. and use the filter-enforcing subscription sink:
  1004. ```rust
  1005. use rmcp::{
  1006. ErrorData, ServerHandler,
  1007. model::*,
  1008. service::SubscriptionContext,
  1009. };
  1010. impl ServerHandler for MyServer {
  1011. fn get_info(&self) -> ServerConfig {
  1012. ServerConfig::new(
  1013. ServerCapabilities::builder()
  1014. .enable_tools()
  1015. .enable_tool_list_changed()
  1016. .build(),
  1017. )
  1018. }
  1019. fn accepted_subscription_filter(
  1020. &self,
  1021. requested: &SubscriptionFilter,
  1022. ) -> Option<SubscriptionFilter> {
  1023. Some(requested.clone())
  1024. }
  1025. async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
  1026. if context.accepted().tools_list_changed == Some(true) {
  1027. context.sink().notify_tool_list_changed().await
  1028. .map_err(|error| ErrorData::internal_error(error.to_string(), None))?;
  1029. }
  1030. context.cancelled().await;
  1031. Ok(())
  1032. }
  1033. }
  1034. ```
  1035. The SDK intersects the handler's filter with the requested categories and the
  1036. capabilities advertised by `get_info()`. It sends the acknowledgment before
  1037. `listen`, tags every sink notification with the listen request ID, and rejects
  1038. categories or resource URIs outside the accepted filter.
  1039. ### Client-side
  1040. ```rust
  1041. use rmcp::model::*;
  1042. let mut subscription = client.listen(
  1043. SubscriptionFilter::builder()
  1044. .tools_list_changed()
  1045. .resource_subscription("file:///config.json")
  1046. .build(),
  1047. ).await?;
  1048. println!("accepted: {:?}", subscription.acknowledged());
  1049. while let Some(notification) = subscription.next().await? {
  1050. println!("notification: {notification:?}");
  1051. }
  1052. subscription.cancel().await?;
  1053. ```
  1054. `listen()` buffers up to 64 notifications per subscription. Use
  1055. `listen_with_capacity()` to choose a different non-zero capacity; if a consumer
  1056. falls behind, `Subscription::end()` reports `SubscriptionEnd::Lagged`.
  1057. For older negotiated protocol versions, the deprecated `subscribe()` and
  1058. `unsubscribe()` APIs retain their legacy wire behavior. Modern Streamable HTTP
  1059. uses the listen POST response stream directly and does not use sessions, GET,
  1060. DELETE, or `Last-Event-ID`. After an abrupt transport close, call `listen`
  1061. again; subscription state is not resumed across HTTP or stdio reconnects.
  1062. See the
  1063. [modern subscription server](examples/servers/src/subscriptions_streamhttp.rs)
  1064. and [client](examples/clients/src/subscriptions_streamhttp.rs) examples.
  1065. ---
  1066. ## Multi-Round-Trip Requests
  1067. Protocol `2026-07-28` adds Multi-Round-Trip Requests (MRTR, SEP-2322): a server
  1068. can answer a `tools/call`, `prompts/get`, or `resources/read` with an
  1069. `InputRequiredResult` instead of a final result, asking the client to fulfill
  1070. one or more embedded server requests (elicitation, sampling, or roots) and then
  1071. retry. The exchange is stateless — the server carries its progress in an opaque
  1072. `requestState` that the client echoes back verbatim.
  1073. **MCP Spec:** [Multiple Round-Trip Requests](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#multiple-round-trip-requests)
  1074. ### Server-side
  1075. Return an `InputRequiredResult` via the outcome enum for the method
  1076. (`CallToolResponse`, `GetPromptResponse`, or `ReadResourceResponse`). The SDK
  1077. only forwards it to peers that negotiated `2026-07-28` or newer — older peers
  1078. get a protocol error instead.
  1079. ```rust, ignore
  1080. async fn call_tool(&self, request: CallToolRequestParams, _ctx: RequestContext<RoleServer>)
  1081. -> Result<CallToolResponse, ErrorData>
  1082. {
  1083. match request.request_state {
  1084. // First round: ask the client for input, seal progress into requestState.
  1085. None => {
  1086. let mut input_requests = InputRequests::new();
  1087. input_requests.insert("city".into(), InputRequest::Elicitation(elicit_city()));
  1088. let sealed = self.codec.seal_json(&json!({ "awaiting": "city" }))?;
  1089. Ok(InputRequiredResult::new(Some(input_requests), Some(sealed)).into())
  1090. }
  1091. // Retry round: verify the echoed state, read the responses, finish.
  1092. Some(sealed) => {
  1093. let _state = self.codec.open_json(&sealed)
  1094. .map_err(|_| ErrorData::invalid_params("tampered request state", None))?;
  1095. let city = request.input_responses.as_ref()
  1096. .and_then(|r| r.get("city"));
  1097. Ok(CallToolResult::success(vec![ContentBlock::text("It is sunny.")]).into())
  1098. }
  1099. }
  1100. }
  1101. ```
  1102. > **`requestState` is untrusted.** [SEP-2322 requires servers to validate
  1103. > it](https://modelcontextprotocol.io/seps/2322-MRTR#protocol-requirements-for-ephemeral-workflow)
  1104. > because the client echoes it back verbatim. A stateless server that stores
  1105. > meaningful data in it MUST verify integrity first. Enable the `request-state`
  1106. > feature and use `RequestStateCodec` to seal and open it (HMAC-tagged), or keep
  1107. > state server-side and use `requestState` only as an opaque handle.
  1108. For multi-replica deployments, use `RequestStateCodec::new_with_keyring` to
  1109. rotate signing keys without invalidating in-flight requests:
  1110. 1. Deploy the old and new keys everywhere, continuing to emit `rs1` with the
  1111. old key via `with_rs1_signing("old")`.
  1112. 2. Start emitting `rs2` with the new key while retaining the old key via
  1113. `with_rs1_fallback("old")`.
  1114. 3. After the maximum `requestState` lifetime has elapsed, remove the old key.
  1115. ### Client-side
  1116. The high-level `call_tool`, `get_prompt`, and `read_resource` helpers drive MRTR
  1117. automatically: they fulfill each embedded request through the local
  1118. `ClientHandler` and retry, up to `DEFAULT_MRTR_MAX_ROUNDS` (10).
  1119. ```rust, ignore
  1120. // Auto mode: the SDK fulfills embedded requests and retries for you.
  1121. let result = client.call_tool(CallToolRequestParams::new("weather")).await?;
  1122. // Choose a custom round cap.
  1123. let result = client
  1124. .call_tool_with_mrtr_max_rounds(CallToolRequestParams::new("weather"), 3)
  1125. .await?;
  1126. // Manual mode: get the intermediate InputRequiredResult and drive rounds yourself.
  1127. match client.call_tool_once(CallToolRequestParams::new("weather")).await? {
  1128. CallToolResponse::InputRequired(input_required) => { /* fulfill + retry */ }
  1129. CallToolResponse::Complete(result) => { /* done */ }
  1130. _ => {}
  1131. }
  1132. ```
  1133. **Example:** [`examples/servers/src/mrtr.rs`](examples/servers/src/mrtr.rs) (end-to-end server + client)
  1134. ---
  1135. ## Tasks (long-running tool invocations)
  1136. `rmcp` implements the [MCP Tasks extension](https://modelcontextprotocol.io/extensions/tasks/overview)
  1137. (SEP-2663, `io.modelcontextprotocol/tasks`). A client declares the extension in its
  1138. capabilities; the server then decides per request whether to materialize a `tools/call`
  1139. as a task, returning a `CreateTaskResult` (`resultType: "task"`). The client polls
  1140. `tasks/get`, answers in-task input requests via `tasks/update`, and may request
  1141. cooperative cancellation via `tasks/cancel`. Use `rmcp::task_manager::TaskManager`
  1142. to manage task lifecycles server-side.
  1143. ```rust, ignore
  1144. // Client: declare the tasks extension capability.
  1145. let caps = ClientCapabilities::builder().enable_tasks().build();
  1146. // Server: decide per request whether to materialize a task.
  1147. async fn call_tool(&self, request: CallToolRequestParams, context: RequestContext<RoleServer>)
  1148. -> Result<CallToolResponse, McpError>
  1149. {
  1150. let client_supports_tasks = context
  1151. .client_capabilities()
  1152. .is_some_and(|caps| caps.supports_tasks());
  1153. if client_supports_tasks {
  1154. let task = self.tasks.spawn(TaskOptions::default(), move |_ctx| {
  1155. Box::pin(async move { /* long-running work -> Ok(CallToolResult) */ })
  1156. });
  1157. return Ok(CallToolResponse::Task(CreateTaskResult::new(task)));
  1158. }
  1159. // ... fall back to synchronous execution
  1160. }
  1161. ```
  1162. See [`servers_task_stdio`](examples/servers/src/task_stdio.rs) and the matching
  1163. [`clients_task_stdio`](examples/clients/src/task_stdio.rs) for a runnable end-to-end example.
  1164. ## Caching
  1165. `rmcp` clients transparently cache responses that carry the
  1166. [SEP-2549](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching)
  1167. caching hints (`ttlMs` / `cacheScope`) for `server/discover`, `tools/list`,
  1168. `prompts/list`, `resources/list`, `resources/templates/list`, and `resources/read`.
  1169. Caching is on by default but only stores a response when the server sends a
  1170. positive `ttlMs`, so servers that omit the hint behave exactly as before. Entries
  1171. expire after their TTL, are partitioned by cache scope, and are invalidated
  1172. automatically by the matching `list_changed` / `resource updated` notifications.
  1173. No call-site changes are needed — existing calls benefit automatically:
  1174. ```rust, ignore
  1175. let tools = peer.list_tools(None).await?; // served from cache while fresh
  1176. let res = peer.read_resource(params).await?; // cached per-URI
  1177. ```
  1178. A cached response reports the `ttlMs` left on its entry, not the server's
  1179. original value, and a stale entry served after a failed re-fetch reports `0`.
  1180. To keep the hints when following every page, use the `list_all_*_with_cache_hint`
  1181. methods, which return a `MergedList` with the earliest `ttl_ms` and the strictest
  1182. `cache_scope` across pages.
  1183. Tune or disable it per connection via the `Peer`:
  1184. ```rust, ignore
  1185. use std::time::Duration;
  1186. use rmcp::ClientCacheConfig;
  1187. // Customize behavior.
  1188. peer.set_response_cache_config(
  1189. ClientCacheConfig::default()
  1190. .with_default_ttl(Duration::from_secs(30)) // TTL for servers that omit ttlMs
  1191. .with_max_ttl(Duration::from_secs(3600)) // upper bound on any TTL
  1192. .with_max_entries(1024)
  1193. .with_private_partition(user_id) // separate private caches per principal
  1194. .with_serve_stale_on_error(false), // surface errors instead of stale data
  1195. ).await;
  1196. // Or turn it off entirely.
  1197. peer.set_response_cache_config(ClientCacheConfig::disabled()).await;
  1198. // Manually flush.
  1199. peer.clear_response_cache().await;
  1200. ```
  1201. > **Note:** with the default `serve_stale_on_error`, a failed re-fetch returns the
  1202. > last cached response (even if expired) as `Ok(..)` instead of an error. Set
  1203. > `with_serve_stale_on_error(false)` if callers must observe fetch failures.
  1204. ## Standard HTTP Headers
  1205. Protocol `2026-07-28` standardizes a set of Streamable HTTP request headers
  1206. (SEP-2243) so proxies and gateways can route MCP traffic without parsing the
  1207. JSON body: `Mcp-Method`, `Mcp-Name`, and `Mcp-Param-*`. `rmcp` emits and
  1208. validates these automatically once a connection negotiates `2026-07-28` or
  1209. newer — no call-site changes are required, and older negotiated versions are
  1210. untouched.
  1211. **MCP Spec:** [Header standardization](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports#header)
  1212. - `Mcp-Method` — the JSON-RPC method (e.g. `tools/call`).
  1213. - `Mcp-Name` — the target name, sourced from `params.name` (`tools/call`,
  1214. `prompts/get`), `params.uri` (`resources/*`), or `params.taskId` (`tasks/*`).
  1215. - `Mcp-Param-*` — selected `tools/call` arguments, promoted from the tool's
  1216. input schema.
  1217. To promote a tool argument into a routing header, annotate its schema property
  1218. with `x-mcp-header`:
  1219. ```rust, ignore
  1220. // A `region` argument surfaces as the `Mcp-Param-Region` request header.
  1221. let schema = serde_json::json!({
  1222. "type": "object",
  1223. "properties": {
  1224. "region": { "type": "string", "x-mcp-header": "Region" }
  1225. }
  1226. });
  1227. ```
  1228. Annotations must be non-empty RFC 9110 tokens, case-insensitively unique, and
  1229. applied only to primitive (`string`/`integer`/`boolean`) properties. Nested
  1230. properties are allowed when every step from the root is a `properties` key; an
  1231. annotation under `items`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, or
  1232. `$ref` makes the tool invalid, and clients drop it from `tools/list`.
  1233. With `schemars`, a nested struct is emitted behind a `$ref` by default. Mark it
  1234. `#[schemars(inline)]` so its annotated fields stay on the `properties` path:
  1235. ```rust, ignore
  1236. #[derive(serde::Deserialize, schemars::JsonSchema)]
  1237. #[schemars(inline)]
  1238. struct Location {
  1239. #[schemars(extend("x-mcp-header" = "Region"))]
  1240. region: String,
  1241. }
  1242. #[derive(serde::Deserialize, schemars::JsonSchema)]
  1243. struct DeployRequest {
  1244. location: Location,
  1245. image: String,
  1246. }
  1247. ```
  1248. Values that cannot travel as a bare header (leading/trailing whitespace,
  1249. control/non-ASCII characters) are transparently Base64-wrapped as
  1250. `=?base64?<b64>?=`.
  1251. ---
  1252. ## Stateless Streamable HTTP
  1253. Per SEP-2567, `rmcp` serves the `2026-07-28` draft statelessly **automatically**:
  1254. no `Mcp-Session-Id`, no standalone GET/DELETE stream, and no `Last-Event-ID`
  1255. resumption. The `legacy_session_mode` flag below only controls behavior for
  1256. *legacy* protocol versions (`< 2026-07-28`).
  1257. **MCP Spec:** [Transports](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports)
  1258. ### Server-side
  1259. A default server already serves `2026-07-28` clients statelessly. To also serve
  1260. *legacy* clients without sessions, disable `legacy_session_mode` (formerly
  1261. `stateful_mode`; builder `with_stateful_mode`). Optionally set
  1262. `with_json_response(true)` so simple request/response tools reply with a single
  1263. `application/json` body instead of an SSE stream (the server still falls back to
  1264. `text/event-stream` if a handler emits a notification or server request first):
  1265. ```rust, ignore
  1266. use rmcp::transport::streamable_http_server::{
  1267. StreamableHttpService, StreamableHttpServerConfig,
  1268. session::local::LocalSessionManager,
  1269. };
  1270. let config = StreamableHttpServerConfig::default()
  1271. .with_legacy_session_mode(false) // stateless for legacy versions too
  1272. .with_json_response(true); // plain JSON replies for simple tools
  1273. let service = StreamableHttpService::new(
  1274. || Ok(Counter::new()), // a fresh handler per request
  1275. LocalSessionManager::default().into(),
  1276. config,
  1277. );
  1278. // `StreamableHttpService` is a Tower service — mount it on any router.
  1279. let router = axum::Router::new().nest_service("/mcp", service);
  1280. ```
  1281. > Because there is no per-session state, the `service_factory` runs per request.
  1282. > Keep shared state (DB pools, caches) in a `Clone` handle captured by the
  1283. > closure; don't rely on in-memory state surviving between requests.
  1284. >
  1285. > Modern-only servers can additionally call
  1286. > `with_stateless_protocol_metadata_required(true)` to reject the compatibility
  1287. > fallback for requests missing their per-request protocol signals. rmcp clients
  1288. > negotiated below `2026-07-28` do not attach that body metadata and will be
  1289. > rejected, so pair this option with a `supported_protocol_versions`
  1290. > implementation that advertises only `2026-07-28` and later.
  1291. ### Client-side
  1292. The Streamable HTTP client transport allows stateless operation by default
  1293. (`allow_stateless: true`), so no configuration is needed to talk to a stateless
  1294. server — it simply omits the session header when the server doesn't issue one:
  1295. ```rust, ignore
  1296. use rmcp::transport::StreamableHttpClientTransport;
  1297. // Defaults are stateless-friendly.
  1298. let transport = StreamableHttpClientTransport::from_uri("http://localhost:8000/mcp");
  1299. let client = ClientConfig::default().serve(transport).await?;
  1300. ```
  1301. **Example:** [`examples/servers/src/counter_streamhttp.rs`](examples/servers/src/counter_streamhttp.rs) (server), [`examples/clients/src/streamable_http.rs`](examples/clients/src/streamable_http.rs) (client)
  1302. ---
  1303. ## Transports
  1304. A transport moves JSON-RPC messages between client and server. Any `Transport`
  1305. impl can be passed to `.serve(..)`; `rmcp` ships the common ones behind Cargo
  1306. features.
  1307. **MCP Spec:** [Transports](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports)
  1308. | Transport | Feature(s) | Notes |
  1309. | ---------------------------- | -------------------------------------------- | ----- |
  1310. | **stdio** | `transport-io` (client + server) | Communicate over `stdin`/`stdout`; the standard way to launch local MCP servers as child processes. |
  1311. | **Child process** (client) | `transport-child-process` | Spawn a server binary and talk to it over its stdio. |
  1312. | **Streamable HTTP** (server) | `transport-streamable-http-server` | The current HTTP transport. Exposes a Tower service you can mount on any router. |
  1313. | **Streamable HTTP** (client) | `transport-streamable-http-client-reqwest` | HTTP client transport built on `reqwest`. |
  1314. | **Worker / in-process** | `transport-worker` | For embedding or testing without real I/O. |
  1315. ### stdio
  1316. ```rust,ignore
  1317. use rmcp::{ServiceExt, transport::stdio};
  1318. // Server: serve over stdin/stdout.
  1319. let server = MyServer.serve(stdio()).await?;
  1320. server.waiting().await?;
  1321. ```
  1322. ```rust,ignore
  1323. use rmcp::{ServiceExt, transport::{TokioChildProcess, ConfigureCommandExt}};
  1324. use tokio::process::Command;
  1325. // Client: launch a server binary and talk to it over its stdio.
  1326. let transport = TokioChildProcess::new(Command::new("uvx").configure(|cmd| {
  1327. cmd.arg("mcp-server-git");
  1328. }))?;
  1329. let client = ().serve(transport).await?;
  1330. ```
  1331. ### Streamable HTTP
  1332. `StreamableHttpService` is a Tower service — mount it on any `axum`/`hyper`
  1333. router (see [Stateless Streamable HTTP](#stateless-streamable-http) for the full
  1334. server example). The client transport connects with a single URI:
  1335. ```rust,ignore
  1336. use rmcp::transport::StreamableHttpClientTransport;
  1337. let transport = StreamableHttpClientTransport::from_uri("http://localhost:8000/mcp");
  1338. let client = ClientConfig::default().serve(transport).await?;
  1339. ```
  1340. The client allows up to 16 ordinary http POSTs at once. Configure this with
  1341. `StreamableHttpClientTransportConfig::with_uri(url).max_concurrent_requests(n)`;
  1342. `1` keeps ordinary POSTs serial, and `0` is treated as `1`. An open sse response
  1343. stream does not count against this limit. Cancellation and replies use a
  1344. separate queue with one extra POST slot. Configure their timeout with
  1345. `control_request_timeout` (default: five seconds). The timeout starts when the
  1346. POST starts, excluding time in the queue. Cancellation stops a queued or active
  1347. POST immediately.
  1348. For an open legacy response stream, the client stops reading but keeps the stream
  1349. alive until the cancellation send finishes or is dropped. This lets custom http
  1350. adapters handle cancellation before their stream state is removed.
  1351. Session recovery waits up to five seconds for old POSTs, then stops any that
  1352. remain. Those POSTs are not retried because the server may have processed them.
  1353. Configure this wait and the separate
  1354. reinitialization timeout with `session_recovery_timeout`. Callers still decide
  1355. which tools may run at the same time and which need approval.
  1356. #### Server-Sent Events (SSE)
  1357. Streamable HTTP responses arrive as either a single `application/json` body or a
  1358. `text/event-stream` (Server-Sent Events) stream when the server pushes
  1359. notifications or requests before the result. `rmcp` handles both automatically
  1360. (SSE parsing lives behind the `client-side-sse` feature). There is no separate
  1361. "SSE transport" to configure — it's an implementation detail of Streamable HTTP.
  1362. #### Legacy HTTP+SSE transport (`2024-11-05`) — intentionally not provided
  1363. The standalone two-endpoint **HTTP+SSE transport** defined in protocol revision
  1364. `2024-11-05` (a separate `GET` SSE channel plus a `POST` message endpoint) is a
  1365. **deliberate non-goal** for `rmcp`. It was [replaced by Streamable HTTP in the
  1366. `2025-03-26` revision](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports),
  1367. and `rmcp` targets current spec revisions (`2025-11-25` and `2026-07-28`), so it
  1368. ships **no legacy HTTP+SSE client or server transport**.
  1369. What to use instead:
  1370. - **New client/server code** — use [Streamable HTTP](#streamable-http). It carries
  1371. the same SSE streaming semantics over a single endpoint and is the transport all
  1372. supported spec revisions expect.
  1373. - **Server-to-client streaming** (push notifications, resource updates) — this is
  1374. built into Streamable HTTP; see [Subscriptions](#subscriptions).
  1375. - **Talking to a legacy `2024-11-05`-only server** — front it with a proxy that
  1376. speaks Streamable HTTP, or pin a dependency to a release that predates the
  1377. transport's removal. `rmcp` will not add the legacy transport back.
  1378. This is a supported-surface decision, not a missing feature: every transport
  1379. `rmcp` implements is listed in the [Transports](#transports) table above.
  1380. ---
  1381. ## Pagination
  1382. List operations (`tools/list`, `prompts/list`, `resources/list`,
  1383. `resources/templates/list`) are paginated via a `next_cursor`. The `list_all_*`
  1384. helpers walk every page for you:
  1385. ```rust,ignore
  1386. // Fetches all pages transparently.
  1387. let tools = client.list_all_tools().await?;
  1388. let prompts = client.list_all_prompts().await?;
  1389. let resources = client.list_all_resources().await?;
  1390. ```
  1391. To page manually, call the single-page method and follow `next_cursor` until
  1392. it's `None`:
  1393. ```rust,ignore
  1394. use rmcp::model::PaginatedRequestParams;
  1395. let mut cursor = None;
  1396. loop {
  1397. let page = client
  1398. .list_tools(Some(PaginatedRequestParams { meta: None, cursor }))
  1399. .await?;
  1400. for tool in &page.tools {
  1401. // handle each tool
  1402. }
  1403. cursor = page.next_cursor;
  1404. if cursor.is_none() {
  1405. break;
  1406. }
  1407. }
  1408. ```
  1409. On the server, return a `next_cursor` from your `list_*` handler when more pages
  1410. remain (`None` when complete).
  1411. **MCP Spec:** [Pagination](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/pagination)
  1412. ---
  1413. ## Capability & Protocol Version Negotiation
  1414. ### Capabilities
  1415. At initialization, client and server exchange **capabilities** so each side
  1416. knows what the other supports. Declare yours with the `ServerCapabilities`
  1417. builder in `get_info()`:
  1418. ```rust,ignore
  1419. use rmcp::model::{ServerCapabilities, ServerConfig};
  1420. fn get_info(&self) -> ServerConfig {
  1421. ServerConfig::new(
  1422. ServerCapabilities::builder()
  1423. .enable_tools()
  1424. .enable_prompts()
  1425. .enable_resources()
  1426. .enable_resources_subscribe()
  1427. .enable_tool_list_changed()
  1428. .enable_logging()
  1429. .build(),
  1430. )
  1431. }
  1432. ```
  1433. Clients do the same via `ClientCapabilities::builder()`. Macros like
  1434. `#[tool_handler]` / `#[prompt_handler]` set the relevant flags automatically.
  1435. After connecting, read the peer's capabilities via `peer.peer_info()`.
  1436. ### Protocol version
  1437. MCP is versioned by date. `rmcp` negotiates automatically on connect — the
  1438. client offers a preferred `ProtocolVersion` and falls back to one the server
  1439. supports:
  1440. ```rust,ignore
  1441. use rmcp::model::ProtocolVersion;
  1442. ProtocolVersion::LATEST; // newest stable version this SDK defaults to
  1443. ProtocolVersion::V_2026_07_28; // a specific version constant
  1444. ProtocolVersion::KNOWN_VERSIONS; // every version this SDK understands
  1445. ```
  1446. Version-specific behavior (SEP-2243 headers, SEP-2567 stateless serving, the
  1447. SEP-2575 subscription model) is gated on the negotiated version, so older clients
  1448. keep working while newer ones opt in.
  1449. **MCP Spec:** [Versioning and Compatibility](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning)
  1450. ---
  1451. ## JSON Schema 2020-12
  1452. Deriving `schemars::JsonSchema` on your parameter and result types generates
  1453. [JSON Schema draft 2020-12](https://json-schema.org/) — the dialect the MCP spec
  1454. requires — for the tool's `inputSchema` and `outputSchema`.
  1455. ```rust,ignore
  1456. use rmcp::schemars;
  1457. #[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
  1458. struct SearchParams {
  1459. /// Full-text query.
  1460. query: String,
  1461. /// Maximum number of results.
  1462. #[serde(default)]
  1463. limit: Option<u32>,
  1464. }
  1465. ```
  1466. Field names, types, and doc comments flow into the schema — no manual authoring
  1467. needed. As of `2026-07-28` (SEP-2106), `outputSchema` may be any JSON Schema type
  1468. (not only `object`) and `structuredContent` may be any JSON value.
  1469. ---
  1470. ## Examples
  1471. See [examples](examples/README.md).
  1472. ## OAuth Support
  1473. See [Oauth_support](docs/OAUTH_SUPPORT.md) for details.
  1474. ## Related Resources
  1475. - [MCP Specification](https://modelcontextprotocol.io/specification/2026-07-28)
  1476. - [Schema](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2026-07-28/schema.ts)
  1477. ## Related Projects
  1478. ### Extending `rmcp`
  1479. - [rmcp-actix-web](https://gitlab.com/lx-industries/rmcp-actix-web) - An `actix_web` backend for `rmcp`
  1480. - [rmcp-openapi](https://gitlab.com/lx-industries/rmcp-openapi) - Transform OpenAPI definition endpoints into MCP tools
  1481. ### Built with `rmcp`
  1482. - [goose](https://github.com/block/goose) - An open-source, extensible AI agent that goes beyond code suggestions
  1483. - [apollo-mcp-server](https://github.com/apollographql/apollo-mcp-server) - MCP server that connects AI agents to GraphQL APIs via Apollo GraphOS
  1484. - [rustfs-mcp](https://github.com/rustfs/rustfs/tree/main/crates/mcp) - High-performance MCP server providing S3-compatible object storage operations for AI/LLM integration
  1485. - [containerd-mcp-server](https://github.com/jokemanfire/mcp-containerd) - A containerd-based MCP server implementation
  1486. - [rmcp-openapi-server](https://gitlab.com/lx-industries/rmcp-openapi/-/tree/main/crates/rmcp-openapi-server) - High-performance MCP server that exposes OpenAPI definition endpoints as MCP tools
  1487. - [nvim-mcp](https://github.com/linw1995/nvim-mcp) - A MCP server to interact with Neovim
  1488. - [terminator](https://github.com/mediar-ai/terminator) - AI-powered desktop automation MCP server with cross-platform support and >95% success rate
  1489. - [stakpak-agent](https://github.com/stakpak/agent) - Security-hardened terminal agent for DevOps with MCP over mTLS, streaming, secret tokenization, and async task management
  1490. - [video-transcriber-mcp-rs](https://github.com/nhatvu148/video-transcriber-mcp-rs) - High-performance MCP server for transcribing videos from 1000+ platforms using whisper.cpp
  1491. - [NexusCore MCP](https://github.com/sjkim1127/Nexuscore_MCP) - Advanced malware analysis & dynamic instrumentation MCP server with Frida integration and stealth unpacking capabilities
  1492. - [spreadsheet-mcp](https://github.com/PSU3D0/spreadsheet-mcp) - Token-efficient MCP server for spreadsheet analysis with automatic region detection, recalculation, screenshot, and editing support for LLM agents
  1493. - [hyper-mcp](https://github.com/hyper-mcp-rs/hyper-mcp) - A fast, secure MCP server that extends its capabilities through WebAssembly (WASM) plugins
  1494. - [rudof-mcp](https://github.com/rudof-project/rudof/tree/master/rudof_mcp) - RDF validation and data processing MCP server with ShEx/SHACL validation, SPARQL queries, and format conversion. Supports stdio and streamable HTTP transports with full MCP capabilities (tools, prompts, resources, logging, completions, tasks)
  1495. - [MCPMate](https://github.com/loocor/MCPMate) - Desktop app for progressive MCP management: start with guided server import, then grow into multi-client profiles and Unify meta tools to keep tool exposure, token use, and runtime state under control, with more options for efficiency, cost, and reliability
  1496. - [McpMux](https://github.com/mcpmux/mcp-mux) - Desktop app to configure MCP servers once at McpMux, connect every AI client (Cursor, Claude Desktop, VS Code, Windsurf) through a single encrypted local gateway with Spaces for project organization, FeatureSets to switch toolsets per client, and a built-in server registry
  1497. - [systemprompt-template](https://github.com/systempromptio/systemprompt-template) - Single-binary Rust runtime providing MCP governance — authentication, authorisation, rate-limiting, audit trails, and cost tracking for AI agents. Self-hosted, air-gap capable, 3,300+ req/s with sub-5ms governance overhead
  1498. - [jilebi-mcp](https://github.com/datron/jilebi) - an extensible MCP server through plugins in Javascript with a secure permissions model
  1499. - [Voltip](https://github.com/sunerpy/voltip) - Push-to-talk dictation app whose local MCP server (Streamable HTTP, token-protected) lets coding agents read its dictionary, rules and correction history, and add dictionary entries the user approves
  1500. - [polymarket-agent](https://github.com/Mattbusel/polymarket-agent) - Polymarket CLI and stdio MCP server that lets agents search markets, read order books and prices, and place, list or cancel CLOB orders (dry-run supported)
  1501. - [tokio-prompt-orchestrator](https://github.com/Mattbusel/tokio-prompt-orchestrator) - LLM proxy with request deduplication, circuit breakers and a spend cap, whose stdio MCP server lets agents run inference, batch prompts, inspect pipeline health and the dead-letter queue, and reconfigure workers
  1502. ## Development
  1503. ### Tips for Contributors
  1504. See [docs/CONTRIBUTE.MD](docs/CONTRIBUTE.MD) to get some tips for contributing.
  1505. ### Triage
  1506. New issues and pull requests are labeled by an automated pass and then assigned to
  1507. the maintainer on weekly rotation, who owns the final call. See
  1508. [docs/CONTRIBUTE.MD](docs/CONTRIBUTE.MD#triage) for the rotation and the response-time
  1509. expectations.
  1510. ### Using Dev Container
  1511. If you want to use dev container, see [docs/DEVCONTAINER.md](docs/DEVCONTAINER.md) for instructions on using Dev Container for development.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.