### Run Client Collection Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the client collection example. This example shows how to manage multiple MCP clients, storing them in a HashMap and performing operations on each. ```bash cargo run -p mcp-client-examples --example clients_collection ``` -------------------------------- ### Run OAuth examples Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/OAUTH_SUPPORT.md Commands to execute the provided OAuth client and server examples. ```bash # Run the OAuth server cargo run -p mcp-server-examples --example servers_complex_auth_streamhttp # Run the OAuth client (in another terminal) cargo run -p mcp-client-examples --example clients_oauth_client ``` -------------------------------- ### Run Sampling Standard I/O Client Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the sampling standard I/O client example. This client demonstrates how to use the sampling tool by connecting to a server and calling the 'ask_llm' tool. ```bash cargo run -p mcp-client-examples --example clients_sampling_stdio ``` -------------------------------- ### Run OAuth Client Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the OAuth client example. This client demonstrates authentication with an MCP server using OAuth, including setting up a local HTTP server for callbacks. ```bash cargo run -p mcp-client-examples --example clients_oauth_client ``` -------------------------------- ### Run Full-Featured Standard I/O Client Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the full-featured standard I/O client example. This client demonstrates all MCP client capabilities, including calling various tools and managing resources. ```bash cargo run -p mcp-client-examples --example clients_everything_stdio ``` -------------------------------- ### Run Git Standard I/O Client Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the Git standard I/O client example. This client communicates with a Git-related MCP server using standard input/output. ```bash cargo run -p mcp-client-examples --example clients_git_stdio ``` -------------------------------- ### Run Streamable HTTP Client Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the streamable HTTP client example. This client communicates with an MCP server using HTTP streaming transport. ```bash cargo run -p mcp-client-examples --example clients_streamable_http ``` -------------------------------- ### Run Memory Standard I/O Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the memory standard I/O server example. This is a minimal server implementation using stdio transport, suitable as a starting point for custom servers. ```bash cargo run -p mcp-server-examples --example servers_memory_stdio ``` -------------------------------- ### Build WASI-p2 MCP Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/wasi/README.md Compiles the example project for the wasm32-wasip2 target. ```sh cargo build -p wasi-mcp-example --target wasm32-wasip2 ``` -------------------------------- ### Run Task Standard I/O Client Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/clients/README.md Launches the task-based invocation client example. This client exercises the task lifecycle against a server, including synchronous calls and asynchronous task polling. ```bash cargo run -p mcp-client-examples --example clients_task_stdio ``` -------------------------------- ### Start an RMCP Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Initializes and starts an RMCP server using the provided service and transport. This call completes the server's initialization process. ```rust // this call will finish the initialization process let server = service.serve(transport).await?; ``` -------------------------------- ### Build MCP Server Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/README.md Builds the standard input/output MCP server binary using Cargo. Ensure you are in the rust-sdk directory. ```sh cargo build --release -p mcp-server-examples --example servers_counter_stdio ``` -------------------------------- ### Server-side Completions Setup Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implement `ServerHandler` to enable completions and prompts capabilities. Handle the `complete` function to provide suggestions based on request context. ```rust use rmcp::{ErrorData as McpError, ServerHandler, model::*, service::RequestContext, RoleServer}; impl ServerHandler for MyServer { fn get_info(&self) -> ServerInfo { ServerInfo { capabilities: ServerCapabilities::builder() .enable_completions() .enable_prompts() .build(), ..Default::default() } } async fn complete( &self, request: CompleteRequestParams, _context: RequestContext, ) -> Result { let values = match &request.r#ref { Reference::Prompt(prompt_ref) if prompt_ref.name == "sql_query" => { match request.argument.name.as_str() { "operation" => vec!["SELECT", "INSERT", "UPDATE", "DELETE"], "table" => vec!["users", "orders", "products"], "columns" => { // Adapt suggestions based on previously filled arguments if let Some(ctx) = &request.context { if let Some(op) = ctx.get_argument("operation") { match op.to_uppercase().as_str() { "SELECT" | "UPDATE" => { vec!["id", "name", "email", "created_at"] } _ => vec![], } } else { vec![] } } else { vec![] } } _ => vec![], } } _ => vec![], }; // Filter by the user's partial input let filtered: Vec = values.into_iter() .map(String::from) .filter(|v| v.to_lowercase().contains(&request.argument.value.to_lowercase())) .collect(); Ok(CompleteResult { completion: CompletionInfo { values: filtered, total: None, has_more: Some(false), }, }) } } ``` -------------------------------- ### Install Cargo LLVM Coverage Tool Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/CONTRIBUTE.MD Install the 'cargo-llvm-cov' tool for code coverage analysis. This requires the 'llvm-tools-preview' component for Rust. ```shell cargo install cargo-llvm-cov rustup component add llvm-tools-preview ``` -------------------------------- ### Run Progress Demo Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the progress demo server example. This server demonstrates how to send progress notifications during long-running operations using a stream processor tool. ```bash cargo run -p mcp-server-examples --example servers_progress_demo -- {stdio|http|all} ``` -------------------------------- ### Run Task Demo Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the task demo server example. This server demonstrates task-based tool invocation for long-running operations, contrasting with regular synchronous tools. ```bash cargo run -p mcp-server-examples --example servers_task_stdio ``` -------------------------------- ### Run Simple Chat Client Commands Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/simple-chat-client/README.md Demonstrates various command-line arguments for running the simple chat client, including displaying help, outputting default configuration, and starting a chat session with custom configurations or models. ```bash ./simple_chat --help ``` ```bash ./simple_chat config > config.toml ``` ```bash ./simple_chat --config my_config.toml chat ``` ```bash ./simple_chat --config my_config.toml --model gpt-4o-mini chat ``` -------------------------------- ### Start an RMCP Client with Tokio Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Initializes an RMCP client by spawning a server process using tokio. The server is configured with npx and the '@modelcontextprotocol/server-everything' package. ```rust use rmcp::{ServiceExt, transport::{TokioChildProcess, ConfigureCommandExt}}; use tokio::process::Command; #[tokio::main] async fn main() -> Result<(), Box> { let client = ().serve(TokioChildProcess::new(Command::new("npx").configure(|cmd| { cmd.arg("-y").arg("@modelcontextprotocol/server-everything"); }))?).await?; Ok(()) } ``` -------------------------------- ### Run Prompt Standard I/O Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the prompt standard I/O server example. This server demonstrates the prompt framework, including code review and debugging prompts with JSON schema argument handling. ```bash cargo run -p mcp-server-examples --example servers_prompt_stdio ``` -------------------------------- ### Run WASI-p2 MCP Example Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/wasi/README.md Executes the compiled WASM module using the MCP inspector and a WASM runtime. ```sh npx @modelcontextprotocol/inspector wasmtime target/wasm32-wasip2/debug/wasi_mcp_example.wasm ``` -------------------------------- ### Initialize and start OAuthState Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/OAUTH_SUPPORT.md Manage the authorization lifecycle using OAuthState. Scopes can be auto-selected or provided explicitly. ```rust // initialize oauth state machine let mut oauth_state = OAuthState::new(&server_url, None) .await .context("Failed to initialize oauth state machine")?; // start authorization - pass empty scopes to let the SDK auto-select oauth_state .start_authorization(&[], MCP_REDIRECT_URI, Some("My MCP Client")) .await .context("Failed to start authorization")?; ``` ```rust oauth_state .start_authorization(&["mcp", "profile"], MCP_REDIRECT_URI, Some("My MCP Client")) .await .context("Failed to start authorization")?; ``` -------------------------------- ### Run Counter Standard I/O Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the counter standard I/O server example. This server provides basic counter operations using standard input/output for communication. ```bash cargo run -p mcp-server-examples --example servers_counter_stdio ``` -------------------------------- ### Run Counter Streamable HTTP Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the counter streamable HTTP server example using axum. This server communicates over HTTP with streaming capabilities. ```bash cargo run -p mcp-server-examples --example servers_counter_streamhttp ``` -------------------------------- ### Interact with an RMCP Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Demonstrates sending requests and notifications to an initialized RMCP server. Examples include listing roots and sending a cancellation notification. ```rust // request let roots = server.list_roots().await?; // or send notification server.notify_cancelled(...).await?; ``` -------------------------------- ### Run Simple Auth Streamable HTTP Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the simple authentication streamable HTTP server example. This server demonstrates token-based authentication using the Authorization header for protected MCP endpoints. ```bash cargo run -p mcp-server-examples --example servers_simple_auth_streamhttp ``` -------------------------------- ### Client-side Setting Server Log Level Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Set the server's minimum log level from the client. This example sets the level to `Warning`. ```rust client.set_level(SetLevelRequestParams { level: LoggingLevel::Warning, meta: None, }).await?; ``` -------------------------------- ### Server-side Tool Router with Server Handler Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Use the `#[tool_router(server_handler)]` macro for tools-only servers to simplify wiring. This example demonstrates a calculator tool. ```rust use rmcp::{handler::server::wrapper::Parameters, schemars, tool, tool_router, ServiceExt, transport::stdio}; #[derive(Debug, serde::Deserialize, schemars::JsonSchema)] struct AddParams { a: i32, b: i32, } #[derive(Clone)] struct Calculator; #[tool_router(server_handler)] impl Calculator { #[tool(description = "Add two numbers")] fn add(&self, Parameters(AddParams { a, b }): Parameters) -> String { (a + b).to_string() } } #[tokio::main] async fn main() -> anyhow::Result<()> { let service = Calculator.serve(stdio()).await?; service.waiting().await?; Ok(()) } ``` -------------------------------- ### GET /oauth/authorize Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/src/html/mcp_oauth_index.html Initiates the OAuth authorization flow by redirecting the user to the authorization server. ```APIDOC ## GET /oauth/authorize ### Description Initiates the OAuth authorization flow. ### Method GET ### Endpoint /oauth/authorize ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be "code" - **client_id** (string) - Required - Client identifier - **redirect_uri** (string) - Required - URI to redirect after authorization - **scope** (string) - Optional - Requested scope - **state** (string) - Optional - State value for CSRF prevention ``` -------------------------------- ### Run Elicitation Standard I/O Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the elicitation standard I/O server example. This server demonstrates elicitation for user input, such as collecting a user's name, using type-safe APIs and JSON schema validation. ```bash cargo run -p mcp-server-examples --example servers_elicitation_stdio ``` -------------------------------- ### Server-side Logging Setup and Message Sending Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implement `ServerHandler` to enable logging capabilities and send structured log messages. Handle client-set log level changes and filter messages accordingly. ```rust use rmcp::{ServerHandler, model::*, service::RequestContext}; impl ServerHandler for MyServer { fn get_info(&self) -> ServerInfo { ServerInfo { capabilities: ServerCapabilities::builder() .enable_logging() .build(), ..Default::default() } } // Client sets the minimum log level async fn set_level( &self, request: SetLevelRequestParams, _context: RequestContext, ) -> Result<(), ErrorData> { // Store request.level and filter future log messages accordingly Ok(()) } } // Send a log message from any handler with access to the peer: context.peer.notify_logging_message(LoggingMessageNotificationParam { level: LoggingLevel::Info, logger: Some("my-server".into()), data: serde_json::json!({ "message": "Processing completed", "items_processed": 42 }), }).await?; ``` -------------------------------- ### Run Elicitation with Enum Inference Config Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the elicitation server example that uses enum inference configuration. This server demonstrates elicitation prompts with schema generation and enum inference. ```bash cargo run -p mcp-server-examples --example servers_elicitation_enum_inference ``` -------------------------------- ### Server-side Resource Management Implementation Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implements the `ServerHandler` trait to manage resources, enabling the resources capability and defining `list_resources` and `read_resource` methods. This example exposes configuration and insights resources. ```rust use rmcp::{ ErrorData as McpError, RoleServer, ServerHandler, ServiceExt, model::*, service::RequestContext, transport::stdio, }; use serde_json::json; #[derive(Clone)] struct MyServer; impl ServerHandler for MyServer { fn get_info(&self) -> ServerInfo { ServerInfo { capabilities: ServerCapabilities::builder() .enable_resources() .build(), ..Default::default() } } async fn list_resources( &self, _request: Option, _context: RequestContext, ) -> Result { Ok(ListResourcesResult { resources: vec![ RawResource::new("file:///config.json", "config").no_annotation(), RawResource::new("memo://insights", "insights").no_annotation(), ], next_cursor: None, meta: None, }) } async fn read_resource( &self, request: ReadResourceRequestParams, _context: RequestContext, ) -> Result { match request.uri.as_str() { "file:///config.json" => Ok(ReadResourceResult { contents: vec![ResourceContents::text(r#"{{\"key\": \"value\"}}"#, &request.uri)], }), "memo://insights" => Ok(ReadResourceResult { contents: vec![ResourceContents::text("Analysis results...", &request.uri)], }), _ => Err(McpError::resource_not_found( "resource_not_found", Some(json!({ "uri": request.uri })) )), } } async fn list_resource_templates( &self, _request: Option, _context: RequestContext, ) -> Result { Ok(ListResourceTemplatesResult { resource_templates: vec![], next_cursor: None, meta: None, }) } } ``` -------------------------------- ### Run Complex Auth Streamable HTTP Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/README.md Executes the complex authentication streamable HTTP server example. This server implements a full OAuth 2.0 authorization server with streamable HTTP MCP transport, including client registration and token validation. ```bash cargo run -p mcp-server-examples --example servers_complex_auth_streamhttp ``` -------------------------------- ### Client-side Completion Request Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Sends a completion request to the server for a given prompt and argument. Useful for getting suggestions or completing partial inputs. ```rust use rmcp::model::*; let result = client.complete(CompleteRequestParams { meta: None, r#ref: Reference::Prompt(PromptReference { name: "sql_query".into(), }), argument: ArgumentInfo { name: "operation".into(), value: "SEL".into(), }, context: None, }).await?; // result.completion.values contains suggestions like ["SELECT"] ``` -------------------------------- ### Server-side Tool Handler with Multiple Capabilities Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Use explicit `#[tool_handler]` when custom server metadata or multiple capabilities (tools + prompts) are needed. This example also shows a calculator tool. ```rust use rmcp::{handler::server::wrapper::Parameters, schemars, tool, tool_router, tool_handler, ServerHandler, ServiceExt}; #[derive(Debug, serde::Deserialize, schemars::JsonSchema)] struct AddParams { a: i32, b: i32, } #[derive(Clone)] struct Calculator; #[tool_router] impl Calculator { #[tool(description = "Add two numbers")] fn add(&self, Parameters(AddParams { a, b }): Parameters) -> String { (a + b).to_string() } } #[tool_handler(name = "calculator", version = "1.0.0", instructions = "A simple calculator")] impl ServerHandler for Calculator {} ``` -------------------------------- ### List and Read Resources Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Demonstrates how to list all resources and read a specific resource using its URI. Handles pagination automatically for listing resources. ```rust use rmcp::model::{ReadResourceRequestParams}; // List all resources (handles pagination automatically) let resources = client.list_all_resources().await?; // Read a specific resource by URI let result = client.read_resource(ReadResourceRequestParams { meta: None, uri: "file:///config.json".into(), }).await?; // List resource templates let templates = client.list_all_resource_templates().await?; ``` -------------------------------- ### Instantiate a Simple RMCP Service Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Creates an instance of a basic RMCP service, such as a 'Counter' service, which can then be served. ```rust let service = common::counter::Counter::new(); ``` -------------------------------- ### Client-side Prompt Interaction Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Demonstrates how a client can interact with server-side prompts. Includes listing all available prompts and invoking a specific prompt with arguments. ```rust use rmcp::model::GetPromptRequestParams; // List all prompts let prompts = client.list_all_prompts().await?; // Get a prompt with arguments let result = client.get_prompt(GetPromptRequestParams { meta: None, name: "code_review".into(), arguments: Some(rmcp::object!({ "language": "Rust", "focus_areas": ["performance", "safety"] })), }).await?; ``` -------------------------------- ### Configure Claude Desktop MCP Servers (Windows) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/README.md Add or update this section in your `claude_desktop_config.json` to register a new MCP server. This configuration is for Windows systems. ```json { "mcpServers": { "counter": { "command": "PATH-TO/rust-sdk/target/release/examples/servers_counter_stdio.exe", "args": [] } } } ``` -------------------------------- ### Manage RMCP Service Shutdown Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Shows how to wait for a service to shut down or to actively cancel it. Both methods return a quit reason. ```rust let quit_reason = server.waiting().await?; // or cancel it let quit_reason = server.cancel().await?; ``` -------------------------------- ### Implement Create Message Handler (Client) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Client-side implementation of the create_message handler, responsible for processing sampling requests and calling the actual LLM. It returns a CreateMessageResult. ```rust use rmcp::{ClientHandler, model::*, service::{RequestContext, RoleClient}}; #[derive(Clone, Default)] struct MyClient; impl ClientHandler for MyClient { async fn create_message( &self, params: CreateMessageRequestParams, _context: RequestContext, ) -> Result { // Forward to your LLM, or return a mock response: let response_text = call_your_llm(¶ms.messages).await; Ok(CreateMessageResult { message: SamplingMessage::assistant_text(response_text), model: "my-model".into(), stop_reason: Some(CreateMessageResult::STOP_REASON_END_TURN.into()), }) } } ``` -------------------------------- ### Use MCP Inspector Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/README.md Launches the Model Context Protocol (MCP) Inspector tool using npx. This tool is useful for inspecting MCP interactions. ```sh npx @modelcontextprotocol/inspector ``` -------------------------------- ### Client-side Tool Invocation Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Demonstrates how to list all available tools and call a specific tool by its name using the client. Requires `CallToolRequestParams`. ```rust use rmcp::model::CallToolRequestParams; // List all tools let tools = client.list_all_tools().await?; // Call a tool by name let result = client.call_tool(CallToolRequestParams::new("add")).await?; ``` -------------------------------- ### List Roots and Handle Notifications (Server) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Server-side code to query the client for its workspace roots and to handle notifications when the client's roots change. This helps servers understand workspace boundaries. ```rust use rmcp::{ServerHandler, model::*, service::{NotificationContext, RoleServer}}; impl ServerHandler for MyServer { // Query the client for its roots async fn call_tool( &self, request: CallToolRequestParams, context: RequestContext, ) -> Result { let roots = context.peer.list_roots().await?; // Use roots.roots to understand workspace boundaries // ... } // Called when the client's root list changes async fn on_roots_list_changed( &self, _context: NotificationContext, ) { // Re-fetch roots to stay current } } ``` -------------------------------- ### Configure Claude Desktop MCP Servers (MacOS/Linux) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/README.md Add or update this section in your `claude_desktop_config.json` to register a new MCP server. This configuration is for MacOS and Linux systems. ```json { "mcpServers": { "counter": { "command": "PATH-TO/rust-sdk/target/release/examples/servers_counter_stdio", "args": [] } } } ``` -------------------------------- ### Implement List Roots Handler (Client) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Client-side implementation of the list_roots handler, which returns a list of workspace roots. Each root is defined by a URI and an optional name. ```rust use rmcp::{ClientHandler, model::*}; impl ClientHandler for MyClient { async fn list_roots( &self, _context: RequestContext, ) -> Result { Ok(ListRootsResult { roots: vec![ Root { uri: "file:///home/user/project".into(), name: Some("My Project".into()), }, ], }) } } ``` -------------------------------- ### Run Code Formatting and Linting Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/CONTRIBUTE.MD Execute the 'just fix' command to automatically format code and run clippy for linting. This ensures code quality and consistency. ```shell just fix ``` -------------------------------- ### Handle Initialized Notification Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Servers handle the `initialized` notification via the `on_initialized` method. This indicates the client is ready. ```rust impl ServerHandler for MyServer { async fn on_initialized( &self, _context: NotificationContext, ) { // Server is ready to receive requests } } ``` -------------------------------- ### Handle authorization URL and callback Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/OAUTH_SUPPORT.md Retrieve the authorization URL for user interaction and process the callback parameters. ```rust // get authorization URL and guide user to open it let auth_url = oauth_state.get_authorization_url().await?; println!("Please open the following URL in your browser for authorization:\n{}", auth_url); // handle callback - in real applications, this is typically done in a callback server let auth_code = "Authorization code (`code` param) obtained from browser after user authorization"; let csrf_token = "CSRF token (`state` param) obtained from browser after user authorization"; oauth_state.handle_callback(auth_code, csrf_token).await?; ``` -------------------------------- ### Interact with MCP Server Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/README.md Once Claude Desktop is running and the server is configured, you can interact with the server using specific chat commands. These commands allow you to test various functionalities of the server. ```text counter.say_hello ``` ```text counter.increment ``` ```text counter.get_value ``` ```text counter.sum {"a": 3, "b": 4} ``` -------------------------------- ### Server-side Subscription Handlers Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implements `subscribe` and `unsubscribe` handlers to manage client subscriptions to resources. Requires enabling resource subscription capabilities. ```rust use rmcp::{ErrorData as McpError, ServerHandler, model::*, service::RequestContext, RoleServer}; use std::sync::Arc; use tokio::sync::Mutex; use std::collections::HashSet; #[derive(Clone)] struct MyServer { subscriptions: Arc>>, } impl ServerHandler for MyServer { fn get_info(&self) -> ServerInfo { ServerInfo { capabilities: ServerCapabilities::builder() .enable_resources() .enable_resources_subscribe() .build(), ..Default::default() } } async fn subscribe( &self, request: SubscribeRequestParams, _context: RequestContext, ) -> Result<(), McpError> { self.subscriptions.lock().await.insert(request.uri); Ok(()) } async fn unsubscribe( &self, request: UnsubscribeRequestParams, _context: RequestContext, ) -> Result<(), McpError> { self.subscriptions.lock().await.remove(&request.uri); Ok(()) } } ``` -------------------------------- ### Define Task-Supported Tool Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Annotate a tool with `execution(task_support = "required")` to indicate it supports task-based invocations. Implement `ServerHandler` with `#[task_handler]` to generate necessary task endpoints. ```rust #[tool( description = "Sum two numbers after a 2-second delay", execution(task_support = "required") )] async fn slow_sum(/* ... */) -> Result { /* ... */ } #[tool_handler] #[task_handler] impl ServerHandler for TaskDemo {} ``` -------------------------------- ### Enable OAuth features in Cargo.toml Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/OAUTH_SUPPORT.md Add the necessary features to your dependencies to enable OAuth support. ```toml [dependencies] rmcp = { version = "0.1", features = ["auth", "transport-streamable-http-client-reqwest"] } ``` -------------------------------- ### Subscribe and Unsubscribe to Resource Updates Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Use `client.subscribe` to receive updates for a specific resource URI. Call `client.unsubscribe` when updates are no longer needed. ```rust use rmcp::model::*; // Subscribe to updates for a resource client.subscribe(SubscribeRequestParams { meta: None, uri: "file:///config.json".into(), }).await?; // Unsubscribe when no longer needed client.unsubscribe(UnsubscribeRequestParams { meta: None, uri: "file:///config.json".into(), }).await?; ``` -------------------------------- ### Define a tools-only server with tool_router Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/crates/rmcp-macros/README.md Use the server_handler flag within the tool_router macro to automatically generate handler methods for a tools-only server. ```rust use rmcp::{tool, tool_router}; #[derive(Clone)] struct MyServer; #[tool_router(server_handler)] impl MyServer { #[tool(description = "Say hello")] async fn hello(&self) -> String { "Hello, world!".into() } } ``` -------------------------------- ### Create Message for Sampling (Server) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Server-side code to request an LLM completion from a client using the create_message API. It includes parameters for messages, model preferences, and system prompts. ```rust use rmcp::model::*; // Inside a ServerHandler method (e.g., call_tool): let response = context.peer.create_message(CreateMessageRequestParams { meta: None, task: None, messages: vec![SamplingMessage::user_text("Explain this error: connection refused")], model_preferences: Some(ModelPreferences { hints: Some(vec![ModelHint { name: Some("claude".into()) }]), cost_priority: Some(0.3), speed_priority: Some(0.8), intelligence_priority: Some(0.7), }), system_prompt: Some("You are a helpful assistant.".into()), include_context: Some(ContextInclusion::None), temperature: Some(0.7), max_tokens: 150, stop_sequences: None, metadata: None, tools: None, tool_choice: None, }).await?; // Extract the response text let text = response.message.content .first() .and_then(|c| c.as_text()) .map(|t| &t.text); ``` -------------------------------- ### Client-side Logging Message Handling Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implement `ClientHandler` to process incoming log messages from the server. Log messages are printed to the console. ```rust impl ClientHandler for MyClient { async fn on_logging_message( &self, params: LoggingMessageNotificationParam, _context: NotificationContext, ) { println!("[{}] {}: {}", params.level, params.logger.unwrap_or_default(), params.data); } } ``` -------------------------------- ### Configure VS Code Coverage Gutters Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/CONTRIBUTE.MD Configure the 'Coverage Gutters' VS Code extension to recognize lcov output. Specify the coverage file name and the base directory for coverage reports. ```json { "coverage-gutters.coverageFileNames": [ "coverage.lcov", ], "coverage-gutters.coverageBaseDir": "target/llvm-cov-target", } ``` -------------------------------- ### Server-side Prompt Definition Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Defines server-side prompts using declarative macros. Supports prompts with no arguments and prompts with typed arguments derived from structs implementing JsonSchema. ```rust use rmcp::{ ErrorData as McpError, RoleServer, ServerHandler, ServiceExt, handler::server::{router::prompt::PromptRouter, wrapper::Parameters}, model::*, prompt, prompt_handler, prompt_router, schemars::JsonSchema, service::RequestContext, transport::stdio, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, JsonSchema)] pub struct CodeReviewArgs { #[schemars(description = "Programming language of the code")] pub language: String, #[schemars(description = "Focus areas for the review")] pub focus_areas: Option>, } #[derive(Clone)] pub struct MyServer { prompt_router: PromptRouter, } #[prompt_router] impl MyServer { fn new() -> Self { Self { prompt_router: Self::prompt_router() } } /// Simple prompt without parameters #[prompt(name = "greeting", description = "A simple greeting")] async fn greeting(&self) -> Vec { vec![PromptMessage::new_text( PromptMessageRole::User, "Hello! How can you help me today?", )] } /// Prompt with typed arguments #[prompt(name = "code_review", description = "Review code in a given language")] async fn code_review( &self, Parameters(args): Parameters, ) -> Result { let focus = args.focus_areas .unwrap_or_else(|| vec!["correctness".into()]); Ok(GetPromptResult { description: Some(format!("Code review for {}", args.language)), messages: vec![ PromptMessage::new_text( PromptMessageRole::User, format!("Review my {} code. Focus on: {}", args.language, focus.join(", ")), ), ], }) } } #[prompt_handler] impl ServerHandler for MyServer { fn get_info(&self) -> ServerInfo { ServerInfo { capabilities: ServerCapabilities::builder().enable_prompts().build(), ..Default::default() } } } ``` -------------------------------- ### Configure Authorized Streamable HTTP Transport Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/OAUTH_SUPPORT.md Create an authorized client and transport layer for communicating with the MCP server. ```rust let am = oauth_state .into_authorization_manager() .ok_or_else(|| anyhow::anyhow!("Failed to get authorization manager"))?; let client = AuthClient::new(reqwest::Client::default(), am); let transport = StreamableHttpClientTransport::with_client( client, StreamableHttpClientTransportConfig::with_uri(MCP_SERVER_URL), ); // create client and connect to MCP server let client_service = ClientInfo::default(); let client = client_service.serve(transport).await?; ``` -------------------------------- ### Define RMCP Transport with Tokio IO Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Sets up the transport layer for an RMCP service using standard input and output streams from tokio. ```rust use tokio::io::{stdin, stdout}; let transport = (stdin(), stdout()); ``` -------------------------------- ### Add RMCP Crate Dependency Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Specify the RMCP crate version in your Cargo.toml file. The 'server' feature is enabled for server-side implementations. ```toml rmcp = { version = "0.16.0", features = ["server"] } ``` ```toml rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", branch = "main" } ``` -------------------------------- ### Define a server with separate tool_handler Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/crates/rmcp-macros/README.md Use separate tool_router and tool_handler blocks when custom arguments or additional handler traits are required. ```rust use rmcp::{tool, tool_router, tool_handler, ServerHandler}; #[derive(Clone)] struct MyServer; #[tool_router] impl MyServer { #[tool(description = "Say hello")] async fn hello(&self) -> String { "Hello, world!".into() } } #[tool_handler] impl ServerHandler for MyServer {} ``` -------------------------------- ### Request scope upgrade Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/docs/OAUTH_SUPPORT.md Handle 403 insufficient_scope errors by requesting additional scopes. ```rust match oauth_state.request_scope_upgrade("admin:write", MCP_REDIRECT_URI).await { Ok(auth_url) => { // open auth_url in browser, handle callback as before println!("Re-authorize at: {}", auth_url); } Err(e) => { eprintln!("Scope upgrade failed: {}", e); } } ``` -------------------------------- ### POST /oauth/token Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/src/html/mcp_oauth_index.html Exchanges an authorization code for an access token. ```APIDOC ## POST /oauth/token ### Description Exchanges the authorization code for a third-party access token. ### Method POST ### Endpoint /oauth/token ### Parameters #### Request Body - **grant_type** (string) - Required - Must be "authorization_code" - **code** (string) - Required - The authorization code - **client_id** (string) - Required - Client identifier - **client_secret** (string) - Required - Client secret - **redirect_uri** (string) - Required - Redirect URI used in authorization request ``` -------------------------------- ### Notify Prompt List Changed (Server) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Server-side notification to inform clients that the available prompts have changed. This is a simple async call to the peer. ```rust use rmcp::model::*; // Server: notify that available prompts have changed context.peer.notify_prompt_list_changed().await?; ``` -------------------------------- ### MCP SSE Endpoints Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/examples/servers/src/html/mcp_oauth_index.html Endpoints for establishing and communicating over an SSE connection, requiring an OAuth token. ```APIDOC ## SSE Endpoints ### Description Endpoints for MCP communication over SSE. These require a valid OAuth token. ### Endpoints - **GET /mcp/sse** - SSE connection endpoint - **POST /mcp/message** - Message endpoint ``` -------------------------------- ### Handle Resource Update Notifications Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implement the `ClientHandler` trait to define how your client reacts to resource updates. The `on_resource_updated` method is called when a resource changes. ```rust impl ClientHandler for MyClient { async fn on_resource_updated( &self, params: ResourceUpdatedNotificationParam, _context: NotificationContext, ) { // Re-read the resource at params.uri } } ``` -------------------------------- ### Handle Cancellation Notification Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Implement the `on_cancelled` method in your handler to abort work when a cancellation notification is received. ```rust impl ServerHandler for MyServer { async fn on_cancelled( &self, params: CancelledNotificationParam, _context: NotificationContext, ) { // Abort work for params.request_id } } ``` -------------------------------- ### Notify Resource List Changes Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Notifies the client that the list of available tools, prompts, or resources has changed. Call these methods when updates occur. ```rust context.peer.notify_tool_list_changed().await?; context.peer.notify_prompt_list_changed().await?; context.peer.notify_resource_list_changed().await?; ``` -------------------------------- ### Resource Notifications Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Shows how servers can notify clients about changes to the resource list or specific resource updates. Clients handle these notifications via the ClientHandler trait. ```rust // Notify that the resource list has changed (clients should re-fetch) context.peer.notify_resource_list_changed().await?; // Notify that a specific resource was updated context.peer.notify_resource_updated(ResourceUpdatedNotificationParam { uri: "file:///config.json".into(), }).await?; ``` ```rust impl ClientHandler for MyClient { async fn on_resource_list_changed( &self, _context: NotificationContext, ) { // Re-fetch the resource list } async fn on_resource_updated( &self, params: ResourceUpdatedNotificationParam, _context: NotificationContext, ) { // Re-read the updated resource at params.uri } } ``` -------------------------------- ### Server Progress Notification Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Sends progress updates during a long-running operation. Use this to inform the client about the status of tasks. ```rust use rmcp::model::*; // Inside a tool handler: for i in 0..total_items { process_item(i).await; context.peer.notify_progress(ProgressNotificationParam { progress_token: ProgressToken(NumberOrString::Number(i as i64)), progress: i as f64, total: Some(total_items as f64), message: Some(format!("Processing item {}/{}", i + 1, total_items)), }).await?; } ``` -------------------------------- ### Notify Roots List Changed (Client) Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Client-side notification to inform the server that the list of workspace roots has changed. This should be called after adding or removing roots. ```rust // After adding or removing a workspace root: client.notify_roots_list_changed().await?; ``` -------------------------------- ### Send Cancellation Notification Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Notifies the other side that a request has been cancelled. Include a reason for the cancellation. ```rust // Send a cancellation context.peer.notify_cancelled(CancelledNotificationParam { request_id: the_request_id, reason: Some("User requested cancellation".into()), }).await?; ``` -------------------------------- ### Notify Resource Updated Source: https://github.com/modelcontextprotocol/rust-sdk/blob/main/README.md Notifies the client that a specific subscribed resource has been updated. Call this when a resource's content changes. ```rust // Check if the resource has subscribers, then notify context.peer.notify_resource_updated(ResourceUpdatedNotificationParam { uri: "file:///config.json".into(), }).await?; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.