### Basic Echo Server and Client Setup with Streamable HTTP (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Demonstrates the fundamental concepts of MCP development with a simple server and client setup. It highlights the ergonomic API methods for starting servers and connecting clients using high-performance Streamable HTTP transport. ```rust let server = UltraFastServer::new(server_info, server_capabilities) .with_tool_handler(Arc::new(EchoToolHandler)); server.run_streamable_http("127.0.0.1", 8080).await?; ``` ```rust let client = UltraFastClient::new(client_info, client_capabilities); client.connect_streamable_http("http://127.0.0.1:8080/mcp").await?; ``` -------------------------------- ### Build and Run Individual Example using Cargo Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Instructions to build and run a specific example from the `ultrafast-mcp` project. This involves navigating to the example directory, building the example, and then running the server and client binaries in separate terminals. ```bash # Navigate to example directory cd examples/01-basic-echo # Build the example cargo build # Run server (in one terminal) cargo run --bin server # Run client (in another terminal) cargo run --bin client ``` -------------------------------- ### Build All Examples in Workspace using Cargo Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Command to build all examples within the `ultrafast-mcp` project's workspace. Assumes the command is run from the project root. ```bash # From the project root cargo build --workspace ``` -------------------------------- ### Run Server Components (Bash) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Start the echo server application. You can choose between STDIO (subprocess) or HTTP (network) modes, with HTTP requiring host and port configuration. ```bash # Start STDIO server (subprocess mode) cargo run --bin basic-echo-server -- stdio # Start HTTP server (network mode) cargo run --bin basic-echo-server -- http --host 127.0.0.1 --port 8080 ``` -------------------------------- ### Run File Operations Server (HTTP) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Starts the file operations server using the HTTP transport for network communication. You can configure the host, port, and allowed directories. ```bash # Default host and port (127.0.0.1:8080) ./target/release/file-ops-server http # Custom host and port ./target/release/file-ops-server http --host 0.0.0.0 --port 9000 # With allowed directories ./target/release/file-ops-server http --allowed-directories /tmp /var/log ``` -------------------------------- ### Bash Development Setup Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md A placeholder for bash commands related to setting up the development environment. This snippet indicates where installation or configuration scripts would be located. ```bash # Development setup commands would go here # Example: npm install, make build, etc. ``` -------------------------------- ### Build and Run MCP Client Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/03-everything-server/README.md Commands to compile and execute the MCP client, which connects to the running HTTP server for interaction. ```bash # Build the client cargo build --release # Run the client (will connect to server via HTTP) ./target/release/client ``` -------------------------------- ### Clone, Build, and Run UltraFast MCP Project Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md This snippet details the initial steps to get the UltraFast MCP project running. It covers cloning the repository, building the project with Cargo, running tests, and executing an example. Prerequisites include Git and a Rust development environment. ```Shell git clone https://github.com/techgopal/ultrafast-mcp.git cd ultrafast-mcp cargo build cargo test cargo run --example basic-echo ``` -------------------------------- ### Add ultrafast-mcp with Features using Cargo Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Demonstrates how to add the `ultrafast-mcp` crate to a Rust project using `cargo add` with different feature flags for various functionalities like minimal setup, HTTP transport, authentication, and monitoring. ```bash # Minimal setup (STDIO only) cargo add ultrafast-mcp --features="minimal" # HTTP server with OAuth cargo add ultrafast-mcp --features="http-with-auth" # Production setup with monitoring cargo add ultrafast-mcp --features="http-with-auth,monitoring-full" # All features enabled cargo add ultrafast-mcp --features="full" ``` -------------------------------- ### Install ultrafast-mcp with all features enabled Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Installs the ultrafast-mcp crate with the 'full' feature flag, enabling all available functionalities for a comprehensive setup. ```bash cargo add ultrafast-mcp --features="full" ``` -------------------------------- ### Build Project Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Builds the UltraFast MCP file operations server and client using Cargo. The `--release` flag optimizes the build for performance. ```bash cargo build --release ``` -------------------------------- ### Connect UltraFastClient via Streamable HTTP (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Shows how to create an `UltraFastClient` and connect it using the recommended Streamable HTTP transport. Requires client info and capabilities. ```rust // Create client let client = UltraFastClient::new(client_info, client_capabilities); // Connect with Streamable HTTP - just one line! client.connect_streamable_http("http://127.0.0.1:8080/mcp").await?; ``` -------------------------------- ### Basic File Operations Client Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Starts the file operations client in HTTP mode, connecting to a local server. The client automatically tests various file operations including creating directories, writing, reading, listing, and searching files. ```bash # Create a directory ./target/release/file-ops-client http --server-url http://localhost:8080 # The client will automatically test: # - Creating directories # - Writing files # - Reading files (full content, head, tail) # - Listing directories # - Getting file information # - Searching files # - Editing files # - Moving files ``` -------------------------------- ### Run Automated Test Script Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Executes the automated test script to build the project, start the server, run client tests, and clean up. This script ensures the project is built and tested thoroughly. ```bash ./test_http.sh ``` -------------------------------- ### Run File Operations Server (STDIO) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Starts the file operations server using the STDIO transport for local communication. You can specify allowed directories to restrict file access. ```bash # Use current directory as allowed directory ./target/release/file-ops-server stdio # Specify allowed directories ./target/release/file-ops-server stdio --allowed-directories /tmp /home/user/documents ``` -------------------------------- ### Configure Basic Auth for UltraFast MCP Client (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Demonstrates setting up Basic Authentication for the UltraFast MCP client using username and password credentials. ```rust // Client-side let client = UltraFastClient::new(info, capabilities) .with_basic_auth("username".to_string(), "password".to_string()); ``` -------------------------------- ### Build Components (Bash) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Commands to build the project's components, including the server, client, and demo applications. Use `--release` for optimized builds. ```bash # Build all components cargo build --release # Build specific component cargo build --release --bin basic-echo-server cargo build --release --bin basic-echo-client cargo build --release --bin basic-echo-demo ``` -------------------------------- ### Configure Allowed Directories Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Starts the file operations server in HTTP mode, specifying allowed directories for file operations. This enhances security by restricting access to only designated paths. Defaults to the current directory if not specified. ```bash # Allow access to multiple directories ./target/release/file-ops-server http --allowed-directories /tmp /home/user /var/log # Default: current directory (.) ``` -------------------------------- ### Create UltraFastServer in Rust Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Demonstrates creating an `UltraFastServer` instance using the builder pattern. It initializes server information, capabilities, and optional tool, resource, and prompt handlers. Requires the `ultrafast-mcp` crate. ```rust let server = UltraFastServer::new( ServerInfo { name: "example-server".to_string(), version: "1.0.0".to_string(), description: Some("Example server description".to_string()), // ... other fields }, ServerCapabilities { tools: Some(ToolsCapability { list_changed: Some(true) }), resources: Some(ResourcesCapability { /* ... */ }), prompts: Some(PromptsCapability { /* ... */ }), // ... other capabilities } ) .with_tool_handler(Arc::new(MyToolHandler)) .with_resource_handler(Arc::new(MyResourceHandler)) // Optional .with_prompt_handler(Arc::new(MyPromptHandler)) // Optional .build()?; ``` -------------------------------- ### Install ultrafast-mcp with minimal features Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Installs the ultrafast-mcp crate with the 'minimal' feature flag, which typically includes core functionality and STDIO transport for a lightweight setup. ```bash cargo add ultrafast-mcp --features="minimal" ``` -------------------------------- ### Connect UltraFastClient via stdio (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Illustrates creating an `UltraFastClient` and connecting it using stdio transport for local subprocess communication. Requires client info and capabilities. ```rust // Create client let client = UltraFastClient::new(client_info, client_capabilities); // Connect with stdio for local subprocess communication client.connect_stdio().await?; ``` -------------------------------- ### Complete MCP Implementation with All Capabilities (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md An advanced example demonstrating the full spectrum of MCP capabilities, including tools, resources, prompts, and advanced data processing. It covers text analysis, dynamic resource serving, and prompt generation with context. ```rust // Example of multiple trait implementations (ToolHandler, ResourceHandler, PromptHandler) // Example of advanced data generation and processing // Example of text analysis capabilities (e.g., sentiment detection) // Example of dynamic resource management // Example of prompt generation with context // Example of complete MCP protocol implementation ``` -------------------------------- ### Connect UltraFastClient with Custom Transport (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Demonstrates creating an `UltraFastClient` and connecting it using a custom transport configuration, such as Streamable HTTP with authentication. Requires client info, capabilities, and transport configuration. ```rust // Create client let client = UltraFastClient::new(client_info, client_capabilities); // Configure custom transport let transport_config = TransportConfig::Streamable { base_url: "http://127.0.0.1:8080/mcp".to_string(), auth_token: Some("your-auth-token".to_string()), session_id: Some("your-session-id".to_string()), }; let transport = create_transport(transport_config).await?; client.connect_with_transport(transport).await?; ``` -------------------------------- ### Run Client Components (Bash) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Connect to the echo server using the client application. For STDIO, the server can be automatically spawned. For HTTP, specify the server URL. ```bash # Connect to STDIO server (spawns server automatically) cargo run --bin basic-echo-client -- stdio --spawn-server # Connect to HTTP server cargo run --bin basic-echo-client -- http --url http://127.0.0.1:8080 ``` -------------------------------- ### Configure HTTP Server Host and Port Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Starts the file operations server in HTTP mode, allowing customization of the host and port. This enables flexible network configuration for the server. Defaults to 127.0.0.1:8080. ```bash # Custom host and port ./target/release/file-ops-server http --host 0.0.0.0 --port 9000 # Default: 127.0.0.1:8080 ``` -------------------------------- ### Connect MCP Inspector to HTTP Server Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/03-everything-server/README.md Instructions for connecting the MCP Inspector tool to the running HTTP server, either directly via URL or using a configuration file. ```bash # Connect using URL http://127.0.0.1:8080 ``` ```bash # Launch Inspector with config file npx @modelcontextprotocol/inspector --config mcp-inspector-config.json --server everything-server-streamable-http ``` -------------------------------- ### Cargo Command for OAuth Feature Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Command to build and run the project with the OAuth feature enabled, which is required for certain authentication functionalities. ```Bash cargo run --features oauth ``` -------------------------------- ### MCP Filesystem Server Tools Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md API documentation for the MCP filesystem server tools, detailing their parameters, return values, and functionality for file and directory operations. ```APIDOC MCP Filesystem Server Tools: read_file: Reads a file from disk. Parameters: path (string): The path to the file. head (number, optional): Number of lines to read from the beginning. tail (number, optional): Number of lines to read from the end. Returns: File content and path. read_multiple_files: Reads multiple files simultaneously. Parameters: paths (array of strings): An array of file paths. Returns: Array of file contents with paths. write_file: Writes content to a file, overwriting existing content. Parameters: path (string): The path to the file. content (string): The content to write. Returns: Success status and message. edit_file: Makes line-based edits to a text file. Parameters: path (string): The path to the file. edits (array of edit operations): Operations to apply to the file. dry_run (boolean, optional): If true, shows diff without applying changes. Returns: Success status, diff output, and message. create_directory: Creates a new directory. Parameters: path (string): The path for the new directory. Returns: Success status and message. list_directory: Lists files and directories within a given path. Parameters: path (string): The directory path to list. Returns: Array of directory entries with metadata. list_directory_with_sizes: Lists files and directories with their sizes and allows sorting. Parameters: path (string): The directory path to list. sort_by (string, optional): Sort order, can be "name" or "size". Returns: Array of directory entries with sizes. directory_tree: Generates a recursive tree view of a directory. Parameters: path (string): The root directory path. Returns: JSON tree structure representing the directory. move_file: Moves or renames a file or directory. Parameters: source (string): The original path. destination (string): The new path. Returns: Success status and message. search_files: Searches for files matching a pattern within a directory. Parameters: path (string): The directory to search within. pattern (string): The glob pattern to match files. exclude_patterns (array of strings, optional): Patterns to exclude from results. Returns: Array of matching file paths. get_file_info: Retrieves detailed metadata for a file. Parameters: path (string): The path to the file. Returns: File size, timestamps, permissions, and type. list_allowed_directories: Lists all directories that the server is permitted to access. Parameters: None Returns: Array of allowed directory paths. ``` -------------------------------- ### Rust Prompt Handler Implementation Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Shows an example of implementing a prompt handler function in Rust, which takes a prompt name and executes specific logic based on the name, returning errors for unknown prompts. ```rust use ultrafast_mcp::{McpResult, McpError}; // Implement prompt handler (example signature) // async fn get_prompt(&self, request: ultrafast_mcp::GetPromptRequest) -> McpResult { // match request.name.as_str() { // "my_prompt" => self.handle_my_prompt(request).await, // _ => Err(McpError::not_found(format!("Prompt not found: {}", request.name))), // } // } ``` -------------------------------- ### Build and Run MCP Server Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/03-everything-server/README.md Commands to compile and launch the Streamable HTTP MCP server. The server will be accessible on port 8080, with a monitoring dashboard available on port 8081. ```bash # Build the server cargo build --release # Run the server (will start on 0.0.0.0:8080) ./target/release/everything-server-streamable-http ``` -------------------------------- ### Rust Resource Handler Implementation Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Demonstrates how to implement a resource handler function in Rust, matching resource URIs to specific handling logic and returning errors for not found resources. ```rust use ultrafast_mcp::{McpResult, McpError}; // Implement resource handler (example signature) // async fn read_resource(&self, request: ultrafast_mcp::ReadResourceRequest) -> McpResult { // match request.uri.as_str() { // "my://resource" => self.handle_my_resource().await, // _ => Err(McpError::not_found(format!("Resource not found: {}", request.uri))), // } // } ``` -------------------------------- ### Install ultrafast-mcp with HTTP, Auth, and Full Monitoring Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Installs the ultrafast-mcp crate with 'http-with-auth' and 'monitoring-full' features, providing HTTP transport, OAuth, and a complete monitoring suite. ```bash cargo add ultrafast-mcp --features="http-with-auth,monitoring-full" ``` -------------------------------- ### Call Echo Tool via STDIO Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Shows how to use the STDIO transport to communicate with the UltraFast MCP server. This example pipes a JSON-RPC request containing the 'echo' tool call to the server's standard input. ```bash echo '{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "echo", "arguments": {"message": "Hello!"}}}' | \ cargo run --bin basic-echo-server -- stdio ``` -------------------------------- ### Configure Bearer Token Auth for UltraFast MCP Client/Server (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Demonstrates configuring Bearer Token authentication for both UltraFast MCP server and client using JWT secrets or access tokens. Includes an example for setting up automatic token refresh for clients. ```rust // Server-side let server = UltraFastServer::new(info, capabilities) .with_bearer_auth( "your-jwt-secret-key".to_string(), vec!["read".to_string(), "write".to_string()], ); // Client-side let client = UltraFastClient::new(info, capabilities) .with_bearer_auth("your-access-token".to_string()); // With auto-refresh let client = UltraFastClient::new(info, capabilities) .with_bearer_auth_refresh( "your-access-token".to_string(), || async { // Call your token refresh endpoint Ok::("new-refreshed-token".to_string()) }, ); ``` -------------------------------- ### Configure HTTP Transport Authentication Methods (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Demonstrates configuring various authentication methods directly on the HTTP transport layer for UltraFast MCP clients. ```rust use ultrafast_mcp_transport::streamable_http::client::StreamableHttpClientConfig; // Bearer token let config = StreamableHttpClientConfig::default() .with_bearer_auth("your-access-token".to_string()); // API key let config = StreamableHttpClientConfig::default() .with_api_key_auth("your-api-key".to_string()); // Basic auth let config = StreamableHttpClientConfig::default() .with_basic_auth("username".to_string(), "password".to_string()); // OAuth let config = StreamableHttpClientConfig::default() .with_oauth_auth(oauth_config); // Custom headers let config = StreamableHttpClientConfig::default() .with_custom_auth() .with_auth_method(ultrafast_mcp_auth::AuthMethod::custom() .with_header("X-Custom-Header".to_string(), "custom-value".to_string())); ``` -------------------------------- ### Run File Operations Client (STDIO) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Runs the file operations client using the STDIO transport to connect to a local server. ```bash ./target/release/file-ops-client stdio ``` -------------------------------- ### Configure MCP Inspector Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Provides instructions for integrating the UltraFast MCP server with MCP Inspector. This involves copying a configuration file to the MCP Inspector directory to automatically spawn and connect to the server. ```bash # Example: Copy config to MCP Inspector directory (adjust path as needed) cp mcp-inspector-config.json ~/.config/mcp-inspector/ # Or use with MCP Inspector directly mcp-inspector --config mcp-inspector.json ``` -------------------------------- ### Echo Tool Example Response Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md An example of the structured JSON response returned by the echo tool. It includes the echoed message along with metadata such as timestamp, echo counter, server ID, and transport type. ```json { "message": "Hello from UltraFast MCP!", "timestamp": "2024-01-15T10:30:00Z", "echo_count": 42, "server_id": "echo-server-12345", "transport": "Http" } ``` -------------------------------- ### Run Comprehensive Demo (Bash) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Execute the main demo application to test both STDIO and HTTP transports. Options are available to specifically run only one transport type. ```bash cargo run --bin basic-echo-demo cargo run --bin basic-echo-demo -- stdio cargo run --bin basic-echo-demo -- http ``` -------------------------------- ### Integrating Authentication into Client Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Demonstrates how to add bearer authentication to an existing client instance using the `with_bearer_auth` method. This configures the client to use an access token for authentication. ```Rust // Existing client code let client = UltraFastClient::new(info, capabilities) .with_elicitation_handler(Arc::new(my_elicitation_handler)) // Add authentication .with_bearer_auth("your-access-token".to_string()); ``` -------------------------------- ### Install ultrafast-mcp with HTTP and OAuth features Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Installs the ultrafast-mcp crate with combined 'http-with-auth' feature, enabling HTTP transport and OAuth 2.1 authentication, building upon STDIO and core functionalities. ```bash cargo add ultrafast-mcp --features="http-with-auth" ``` -------------------------------- ### Cargo Command without OAuth Feature Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Command to build and run the project without the OAuth feature, resulting in limited authentication functionality. ```Bash cargo run ``` -------------------------------- ### Configure OAuth 2.1 Auth for UltraFast MCP Client (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Sets up OAuth 2.1 authentication for the UltraFast MCP client, requiring configuration of client credentials, URLs, and scopes. ```rust // Client-side let oauth_config = ultrafast_mcp_auth::OAuthConfig { client_id: "your-client-id".to_string(), client_secret: "your-client-secret".to_string(), auth_url: "https://auth.example.com/oauth/authorize".to_string(), token_url: "https://auth.example.com/oauth/token".to_string(), redirect_uri: "http://localhost:8080/callback".to_string(), scopes: vec!["read".to_string(), "write".to_string()], }; let client = UltraFastClient::new(info, capabilities) .with_oauth_auth(oauth_config); ``` -------------------------------- ### Server Transport Selection (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md This Rust code snippet demonstrates how to select and run the server based on command-line arguments for the transport type (STDIO or HTTP). It handles parsing arguments and configuring the server accordingly. ```rust // Transport selection via CLI let args = Args::parse(); // Run with chosen transport match args.transport { TransportType::Stdio => { server.run_stdio().await?; } TransportType::Http => { let config = HttpTransportConfig { /* ... */ }; server.run_streamable_http_with_config(config).await?; } } ``` -------------------------------- ### Debugging Server (Bash) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Instructions for running the server with debug logging enabled. This helps in diagnosing issues by increasing the verbosity of output, particularly for the `rust` logging framework. ```bash # Enable debug logging RUST_LOG=debug cargo run --bin basic-echo-server -- stdio # Run with specific log level RUST_LOG=ultrafast_mcp=debug cargo run --bin basic-echo-client -- http ``` -------------------------------- ### Configure Custom Header Auth for UltraFast MCP Client (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Enables flexible custom header-based authentication for the UltraFast MCP client, allowing multiple headers to be added. ```rust // Client-side let client = UltraFastClient::new(info, capabilities) .with_custom_auth() .with_auth(ultrafast_mcp_auth::AuthMethod::custom() .with_header("X-Custom-Header".to_string(), "custom-value".to_string()) .with_header("X-Another-Header".to_string(), "another-value".to_string())); ``` -------------------------------- ### Rust Tool Request/Response Serialization Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Defines the Serde structures for tool requests and responses, including input parameters and optional configurations. It also shows the signature for implementing a tool handler function. ```rust use std::collections::HashMap; use serde::{Deserialize, Serialize}; // Define request/response structures #[derive(Deserialize)] struct MyToolRequest { input: String, options: Option>, } #[derive(Serialize)] struct MyToolResponse { result: String, metadata: HashMap, } // Implement tool handler (example signature) // async fn handle_my_tool(&self, request: MyToolRequest) -> ultrafast_mcp::McpResult { // // Validate input // // Process request // // Return structured response // } ``` -------------------------------- ### Configure API Key Auth for UltraFast MCP Client (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Shows how to configure API Key authentication for the UltraFast MCP client. Supports specifying a custom header name for the API key. ```rust // Client-side let client = UltraFastClient::new(info, capabilities) .with_api_key_auth("your-api-key".to_string()); // With custom header name let client = UltraFastClient::new(info, capabilities) .with_api_key_auth_custom("your-api-key".to_string(), "X-Custom-API-Key".to_string()); ``` -------------------------------- ### Client-side Authentication Middleware Usage Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Illustrates the usage of the client-side authentication middleware for generating authentication headers. It shows how to create an authentication method (e.g., Bearer token) and obtain the necessary headers for outgoing requests. ```Rust use ultrafast_mcp_auth::{ClientAuthMiddleware, AuthMethod}; // Create auth middleware with Bearer token let auth_method = AuthMethod::bearer("your-access-token".to_string()); let mut auth_middleware = ClientAuthMiddleware::new(auth_method); // Get authentication headers match auth_middleware.get_headers().await { Ok(headers) => { for (key, value) in headers { println!("{}: {}", key, value); } } Err(e) => { println!("Failed to get auth headers: {:?}", e); } } ``` -------------------------------- ### Run File Operations Client (HTTP) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Runs the file operations client using the HTTP transport to connect to a remote or local server. You can specify the server URL. ```bash # Default server URL ./target/release/file-ops-client http # Custom server URL ./target/release/file-ops-client http --server-url http://localhost:9000 ``` -------------------------------- ### Build Rust Project with Cargo Source: https://github.com/techgopal/ultrafast-mcp/blob/main/CONTRIBUTING.md Commands to build Rust crates using Cargo, supporting all targets, specific crates, and examples. Ensures the project is compiled correctly. ```bash cargo build --all-targets --all-features cargo build -p ultrafast-mcp-core cargo build --examples ``` -------------------------------- ### Integrating Authentication into Server Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Shows how to add bearer authentication to an existing server instance using the `with_bearer_auth` method. This configures the server to use JWT secrets and required scopes for authentication. ```Rust // Existing server code let server = UltraFastServer::new(info, capabilities) .with_tool_handler(Arc::new(my_tool_handler)) .with_resource_handler(Arc::new(my_resource_handler)) // Add authentication .with_bearer_auth("your-jwt-secret".to_string(), vec!["read".to_string()]); ``` -------------------------------- ### Install ultrafast-mcp with HTTP and OAuth Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Demonstrates how to create a new Rust project and add the ultrafast-mcp dependency with specific features enabled for HTTP transport and OAuth 2.1 authentication. ```bash cargo new my-mcp-server cd my-mcp-server cargo add ultrafast-mcp --features="http,oauth" ``` -------------------------------- ### Rust Usage Example Source: https://github.com/techgopal/ultrafast-mcp/blob/main/crates/ultrafast-mcp-test-utils/README.md Demonstrates how to import and use the test utilities from the `ultrafast_mcp_test_utils` crate in a Rust project. It shows the basic import statement required to access assertions, fixtures, and mocks. ```rust use ultrafast_mcp_test_utils::{assertions, fixtures, mocks}; // Use test utilities in your tests ``` -------------------------------- ### Authentication Methods and Middleware for MCP Clients/Servers (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Demonstrates comprehensive authentication support for MCP, including various methods like Bearer token, API key, Basic, Custom Headers, and OAuth 2.1. It covers server-side validation, client-side management, and HTTP transport integration. ```rust // Example of Bearer token authentication with JWT validation // Example of API key authentication with custom headers // Example of Basic authentication with username/password // Example of Custom header authentication // Example of OAuth 2.1 authentication with PKCE // Example of auto-refresh tokens // Example of server-side authentication middleware // Example of client-side authentication middleware // Example of HTTP transport authentication integration ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Enables debug logging for both the file operations server and client by setting the RUST_LOG environment variable. This is useful for troubleshooting and understanding the internal workings of the application. ```bash RUST_LOG=debug ./target/release/file-ops-server http RUST_LOG=debug ./target/release/file-ops-client http ``` -------------------------------- ### Test Network Connection Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Uses netcat (nc) to manually test the network connection to the UltraFast MCP server on its default port, verifying basic network reachability. ```bash nc -v 127.0.0.1 8080 ``` -------------------------------- ### Debug Server Logs Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Command to run the basic-echo-server with debug logging enabled and capture the output to a file. This is useful for diagnosing issues with the server's operation. ```bash RUST_LOG=debug cargo run --bin basic-echo-server -- http 2>&1 | tee server.log ``` -------------------------------- ### MCP Filesystem API Operations Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/02-file-operations/README.md Describes common operations available through the MCP Filesystem API, accessible via HTTP. These operations cover file and directory management, including reading, writing, creating, listing, and searching. ```APIDOC MCP Filesystem API Operations: - read_file(path: str) - Description: Reads the content of a file. - Parameters: - path: The path to the file to read. - Returns: File content as string or bytes. - create_directory(path: str) - Description: Creates a new directory at the specified path. - Parameters: - path: The path for the new directory. - Returns: Success status. - list_directory(path: str) - Description: Lists the contents of a directory. - Parameters: - path: The path to the directory to list. - Returns: List of files and subdirectories. - search_files(pattern: str) - Description: Searches for files matching a given pattern. - Parameters: - pattern: The search pattern (e.g., glob pattern). - Returns: List of matching file paths. - get_file_info(path: str) - Description: Retrieves metadata and information about a file or directory. - Parameters: - path: The path to the file or directory. - Returns: File information (size, modification time, etc.). ``` -------------------------------- ### Implement ToolHandler Trait in Rust Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md Shows how to implement the `ToolHandler` trait for custom tool logic. This includes handling tool calls by name and listing available tools. Requires `async_trait` and `ultrafast_mcp` crates. ```rust @async_trait::async_trait impl ultrafast_mcp::ToolHandler for MyToolHandler { async fn handle_tool_call(&self, call: ultrafast_mcp::ToolCall) -> ultrafast_mcp::McpResult { match call.name.as_str() { "my_tool" => self.handle_my_tool(request).await, _ => Err(ultrafast_mcp::McpError::method_not_found(format!("Unknown tool: {}", call.name))), } } async fn list_tools(&self, _request: ultrafast_mcp::ListToolsRequest) -> ultrafast_mcp::McpResult { // Return list of available tools } } ``` -------------------------------- ### Client Transport Connection (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md This Rust code snippet shows the client-side logic for connecting to the echo server. It dynamically chooses the connection method (STDIO or HTTP) based on parsed command-line arguments. ```rust // Connect based on transport type match args.transport { TransportType::Stdio => { client.connect_stdio().await?; } TransportType::Http => { client.connect_streamable_http(&args.url).await?; } } ``` -------------------------------- ### Server-side Authentication Middleware Usage Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Demonstrates how to set up and use the server-side authentication middleware for request validation and scope checking. It involves creating a token validator, configuring the middleware with required scopes, and validating incoming request headers. ```Rust use ultrafast_mcp_auth::{ServerAuthMiddleware, TokenValidator, AuthContext}; use std::collections::HashMap; // Create token validator let token_validator = TokenValidator::new("your-jwt-secret".to_string()); // Create auth middleware let auth_middleware = ServerAuthMiddleware::new(token_validator) .with_required_scopes(vec!["read".to_string(), "write".to_string()]); // Validate request let mut headers = HashMap::new(); headers.insert("Authorization".to_string(), "Bearer your-jwt-token".to_string()); match auth_middleware.validate_request(&headers).await { Ok(auth_context) => { println!("Authentication successful"); println!("User ID: {:?}", auth_context.user_id); println!("Scopes: {:?}", auth_context.scopes); println!("Authenticated: {}", auth_context.is_authenticated); } Err(e) => { println!("Authentication failed: {:?}", e); } } ``` -------------------------------- ### Echo Tool Input Schema Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Defines the schema for the 'echo' tool's input, specifying the 'message' parameter. It includes its type, description, maximum length, and a default value. ```APIDOC Echo Tool Schema: name: echo description: Echo back a message with timestamp and metadata input_schema: type: object properties: message: type: string description: Message to echo back (max 1000 characters, optional) maxLength: 1000 default: "Hello, World!" ``` -------------------------------- ### File Operations Server with Complex Tool Handling (Rust) Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/README.md A comprehensive file operations server showcasing file system integration and complex tool handling. It supports multiple file operations like read, write, list, delete, search, and move, along with robust path validation. ```rust // Example of file reading with head/tail support // Example of directory listing with size information // Example of file search and pattern matching // Example of directory tree generation // Example of file moving and renaming // Example of comprehensive error handling and validation ``` -------------------------------- ### Call Echo Tool via HTTP Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md Demonstrates how to invoke the 'echo' tool on the UltraFast MCP server using the HTTP transport with curl. It sends a POST request with a JSON payload specifying the tool name and its arguments. ```bash curl -X POST http://127.0.0.1:8080/tools/call \ -H "Content-Type: application/json" \ -d '{"name": "echo", "arguments": {"message": "Hello from curl!"}}' ``` -------------------------------- ### Check Server Health Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/01-basic-echo/README.md A command to verify if the UltraFast MCP server is running and accessible via HTTP. It sends a GET request to the '/health' endpoint. ```bash curl http://127.0.0.1:8080/health ``` -------------------------------- ### Rust: Create MCP Server Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Demonstrates how to set up a basic MCP server using the UltraFast MCP framework. It includes defining a tool handler for a 'greet' function, specifying input/output schemas, and running the server with STDIO transport. ```rust use ultrafast_mcp::prelude::*; use serde::{Deserialize, Serialize}; use std::sync::Arc; #[derive(Deserialize)] struct GreetRequest { name: String, greeting: Option, } #[derive(Serialize)] struct GreetResponse { message: String, timestamp: String, } // Implement the tool handler struct GreetToolHandler; #[async_trait::async_trait] impl ToolHandler for GreetToolHandler { async fn handle_tool_call(&self, call: ToolCall) -> MCPResult { match call.name.as_str() { "greet" => { // Parse the arguments let args: GreetRequest = serde_json::from_value( call.arguments.unwrap_or_default() )?; // Generate the response let greeting = args.greeting.unwrap_or_else(|| "Hello".to_string()); let message = format!("{}, {}!", greeting, args.name); Ok(ToolResult { content: vec![ToolContent::text(message)], is_error: Some(false), }) } _ => Err(MCPError::method_not_found( format!("Unknown tool: {}", call.name) )), } } async fn list_tools(&self, _request: ListToolsRequest) -> MCPResult { Ok(ListToolsResponse { tools: vec![Tool { name: "greet".to_string(), description: "Greet a person by name".to_string(), input_schema: serde_json::json!({ "type": "object", "properties": { "name": {"type": "string"}, "greeting": {"type": "string", "default": "Hello"} }, "required": ["name"] }), output_schema: None, }], next_cursor: None, }) } } #[tokio::main] async fn main() -> anyhow::Result<()> { // Create server configuration let server_info = ServerInfo { name: "greeting-server".to_string(), version: "1.0.0".to_string(), description: Some("A simple greeting server".to_string()), authors: None, homepage: None, license: None, repository: None, }; let capabilities = ServerCapabilities { tools: Some(ToolsCapability { list_changed: Some(true) }), ..Default::default() }; // Create and configure the server let server = UltraFastServer::new(server_info, capabilities) .with_tool_handler(Arc::new(GreetToolHandler)); // Start the server with STDIO transport server.run_stdio().await?; Ok(()) } ``` -------------------------------- ### Rust: Create MCP Client Source: https://github.com/techgopal/ultrafast-mcp/blob/main/README.md Demonstrates how to set up a basic MCP client using the UltraFast MCP framework. It shows how to connect to a server via STDIO, call a tool with arguments, and process the response. ```rust use ultrafast_mcp::prelude::*; use serde_json::json; #[tokio::main] async fn main() -> anyhow::Result<()> { // Create client configuration let client_info = ClientInfo { name: "greeting-client".to_string(), version: "1.0.0".to_string(), authors: None, description: Some("A simple greeting client".to_string()), homepage: None, repository: None, license: None, }; let capabilities = ClientCapabilities::default(); // Create the client let client = UltraFastClient::new(client_info, capabilities); // Connect to the server using STDIO client.connect_stdio().await?; // Call a tool let tool_call = ToolCall { name: "greet".to_string(), arguments: Some(json!({ "name": "Alice", "greeting": "Hello there" })), }; let result = client.call_tool(tool_call).await?; println!("Server response: {:?}", result); // Disconnect client.disconnect().await?; Ok(()) } ``` -------------------------------- ### Error Handling with AuthResult Source: https://github.com/techgopal/ultrafast-mcp/blob/main/examples/04-authentication-example/README.md Provides an example of how to handle potential authentication errors using the `AuthResult` enum. It demonstrates matching against specific error variants like `InvalidToken`, `MissingScope`, and `NetworkError`. ```Rust use ultrafast_mcp_auth::{AuthError, AuthResult}; async fn handle_auth_error(result: AuthResult<()>) { match result { Ok(()) => println!("Authentication successful"), Err(AuthError::InvalidToken(message)) => { eprintln!("Invalid token: {}", message); // Handle invalid token } Err(AuthError::MissingScope { scope }) => { eprintln!("Missing scope: {}", scope); // Handle permission error } Err(AuthError::NetworkError(message)) => { eprintln!("Network error: {}", message); // Handle network error } Err(e) => { eprintln!("Authentication error: {:?}", e); // Handle other errors } } } ```