### Run Simplest STDIO Server Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Execute the 'hello_world' example to start the simplest STDIO server. This is a good starting point for understanding basic server setup. ```bash cargo run -p turbomcp --example hello_world ``` -------------------------------- ### Basic gRPC Server Setup Source: https://github.com/epistates/turbomcp/blob/main/docs/api/grpc.md Configure and start a basic MCP gRPC server with a 'hello' tool. This example demonstrates the core server building process. ```rust use tonic::transport::Server; use turbomcp_grpc::McpGrpcServer; use turbomcp_types::{Tool, ToolInputSchema}; #[tokio::main] async fn main() -> Result<(), Box> { let server = McpGrpcServer::builder() .server_info("my-server", "1.0.0") .add_tool( Tool::new("hello", "Says hello").with_schema( ToolInputSchema::default() .add_property("name", serde_json::json!({"type": "string"})) .require_property("name"), ), ) .build(); Server::builder() .add_service(server.into_service()) .serve("[::1]:50051".parse()?) .await?; Ok(()) } ``` -------------------------------- ### Run Protected Resource Server Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Demonstrates protected resource metadata for authentication. This example prints configuration and validation behavior without starting a full authorization server. ```bash cargo run -p turbomcp-auth --example protected_resource_server ``` -------------------------------- ### Serve Tags Versioning Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Run the 'tags_versioning' example with the '--serve' flag to start its STDIO server. This allows for interactive testing of tag and versioning features. ```bash cargo run -p turbomcp --example tags_versioning -- --serve ``` -------------------------------- ### Run TurboMCP Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/CONTRIBUTING.md Execute an example from the project to verify the setup. ```bash cargo run --example calculator ``` -------------------------------- ### Run STDIO Examples with Default Features Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Execute STDIO examples like 'calculator' and 'stateful' which only require the default 'stdio' feature. These examples demonstrate basic server functionality. ```bash cargo run -p turbomcp --example calculator ``` ```bash cargo run -p turbomcp --example stateful ``` -------------------------------- ### Implement a Basic Calculator Server Source: https://github.com/epistates/turbomcp/blob/main/docs/api/server.md A complete example showing a server definition with a tool handler and a main function to start the server via stdio. ```rust use turbomcp::prelude::*;\n\n#[derive(Clone)]\nstruct Calculator;\n\n#[turbomcp::server(name = "calculator", version = "1.0.0")]\nimpl Calculator {\n #[tool("Add two numbers")]\n async fn add(&self, a: f64, b: f64) -> McpResult {\n Ok(a + b)\n }\n}\n\n#[tokio::main]\nasync fn main() -> Result<(), Box> {\n Calculator.run_stdio().await?;\n Ok(())\n} ``` -------------------------------- ### Run Turbomcp Client Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-client/README.md Instructions on how to run the provided client examples using Cargo. These examples demonstrate different transport mechanisms like TCP and Unix sockets. ```bash cargo run --example tcp_client cargo run --example unix_client ``` -------------------------------- ### Running the Petstore Example with Cargo Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-openapi/README.md Command to compile and run the petstore example using Cargo. This demonstrates how to execute the provided example code. ```bash cargo run -p turbomcp-openapi --example petstore ``` -------------------------------- ### Run TCP Server Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Start a TCP server using the 'tcp_server' example. This requires the 'tcp' feature to be enabled. Run this in one terminal. ```bash cargo run -p turbomcp --example tcp_server --features tcp ``` -------------------------------- ### Run Tags Versioning Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Execute the 'tags_versioning' example to demonstrate tool/resource/prompt tags and version metadata. By default, it prints metadata and exits. ```bash cargo run -p turbomcp --example tags_versioning ``` -------------------------------- ### Run OAuth2 Auth Code Flow Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Demonstrates OAuth 2.1 URL generation for the auth code flow. This example prints configuration and validation behavior without starting a full authorization server. ```bash cargo run -p turbomcp-auth --example oauth2_auth_code_flow ``` -------------------------------- ### Run Tower Rate Limiting Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Demonstrates Tower rate limiting with the `middleware` feature. This example prints configuration and validation behavior without starting a full authorization server. ```bash cargo run -p turbomcp-auth --example tower_rate_limiting --features middleware ``` -------------------------------- ### Initialize Telemetry with Default Configuration Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-telemetry/README.md Quick start example for initializing telemetry with a service name, version, and log level. This sets up basic logging and tracing. ```rust use turbomcp_telemetry::{TelemetryConfig, TelemetryGuard}; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize telemetry let config = TelemetryConfig::builder() .service_name("my-mcp-server") .service_version("1.0.0") .log_level("info,turbomcp=debug") .build(); let _guard = config.init()?; // Your MCP server code here... Ok(()) } ``` -------------------------------- ### Run Metadata-Only Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Execute examples like 'visibility', 'composition', and 'middleware' which are designed to print metadata and exit. These are useful for inspecting configuration and capabilities. ```bash cargo run -p turbomcp --example visibility ``` ```bash cargo run -p turbomcp --example composition ``` ```bash cargo run -p turbomcp --example middleware ``` -------------------------------- ### Run Middleware Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Demonstrates typed middleware by wrapping a server with logging, metrics, and access-control layers. The example then calls through the layered handler directly. ```bash cargo run -p turbomcp --example middleware ``` -------------------------------- ### Compile All Example Targets Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Compiles all example targets in the workspace with all features enabled. ```bash cargo check --workspace --examples --all-features ``` -------------------------------- ### Example: REST API Adapter Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/README.md This example demonstrates how to run the REST API adapter using the stdio backend to connect to a Python server. Ensure the backend command is correctly specified. ```bash turbomcp-proxy adapter rest \ --backend stdio --cmd "python server.py" \ --bind 127.0.0.1:3000 ``` -------------------------------- ### Example Server with Tool Handlers Source: https://github.com/epistates/turbomcp/blob/main/docs/api/macros.md This example demonstrates a server with two tool handlers, `add` and `multiply`, using the `#[tool]` macro. The `main` function shows how to run the server using `run_stdio().await`. ```rust #[derive(Clone)] struct Calculator; #[turbomcp::server(name = "calculator", version = "1.0.0")] impl Calculator { #[tool("Add two numbers")] async fn add(&self, a: f64, b: f64) -> McpResult { Ok(a + b) } #[tool("Multiply two numbers")] async fn multiply(&self, a: f64, b: f64) -> McpResult { Ok(a * b) } } #[tokio::main] async fn main() -> Result<(), Box> { Calculator.run_stdio().await?; Ok(()) } ``` -------------------------------- ### Run TurboMCP Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-client/README.md Execute example binaries from the TurboMCP workspace, such as the TCP client example. ```bash cargo run --example tcp_client ``` -------------------------------- ### Complete Macro Example Source: https://github.com/epistates/turbomcp/blob/main/docs/api/wasm.md A comprehensive example demonstrating the usage of #[server], #[tool], #[resource], and #[prompt] macros within an implementation block. ```APIDOC ### Complete Macro Example ```rust use turbomcp_wasm::prelude::*; use serde::Deserialize; #[derive(Clone)] struct Calculator; #[derive(Deserialize, schemars::JsonSchema)] struct AddArgs { a: i64, b: i64, } #[derive(Deserialize, schemars::JsonSchema)] struct MulArgs { a: i64, b: i64, } #[server(name = "calculator", version = "2.0.0", description = "Math operations")] impl Calculator { #[tool("Add two numbers")] async fn add(&self, args: AddArgs) -> i64 { args.a + args.b } #[tool("Multiply two numbers")] async fn multiply(&self, args: MulArgs) -> i64 { args.a * args.b } #[tool("Get calculator info")] async fn info(&self) -> String { "Calculator v2.0".to_string() } #[resource("config://calculator")] async fn config(&self, uri: String) -> ResourceResult { ResourceResult::json(&uri, &serde_json::json!({"precision": 10})) } #[prompt("Math help")] async fn help(&self) -> PromptResult { PromptResult::user("I can add and multiply numbers. Try: add 2 3") } } #[event(fetch)] async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result { Calculator.into_mcp_server().handle(req).await } ``` ``` -------------------------------- ### Run OAuth 2.1 Authorization Code Flow Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-auth/README.md Execute this command to run the example demonstrating the OAuth 2.1 Authorization Code Flow. ```bash cargo run --example oauth2_auth_code_flow ``` -------------------------------- ### Function Documentation Example Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/development.md Standard format for documenting functions including arguments, returns, and examples. ```rust /// Calculate the sum of two numbers. /// /// # Arguments /// /// * `a` - First number /// * `b` - Second number /// /// # Returns /// /// Sum of `a` and `b` /// /// # Examples /// /// ``` /// use turbomcp::math::add; /// /// assert_eq!(add(2, 3), 5); /// ``` pub fn add(a: i32, b: i32) -> i32 { a + b } ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/epistates/turbomcp/blob/main/docs/README.md Command to install the required Python packages for building the documentation. ```bash pip install mkdocs mkdocs-material ``` -------------------------------- ### Run Unix Socket Server Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/examples/README.md Start a Unix socket server using the 'unix_server' example. This requires the 'unix' feature and is suitable for Unix-like systems. Run this in one terminal. ```bash cargo run -p turbomcp --example unix_server --features unix ``` -------------------------------- ### Example: GraphQL API Adapter Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/README.md This example shows how to run the GraphQL API adapter using a TCP backend. The adapter will bind to the specified address and port. ```bash turbomcp-proxy adapter graphql \ --backend tcp --tcp localhost:5000 \ --bind 127.0.0.1:4000 ``` -------------------------------- ### Run Runtime Proxy Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/examples/README.md Demonstrates `RuntimeProxyBuilder`, backend/frontend configuration, security validation, and proxy metrics. Some attempted backends are intentionally invalid so the example can show validation errors without requiring external services. ```bash cargo run -p turbomcp-proxy --example runtime_proxy ``` -------------------------------- ### Run Minimal Turbomcp Server Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/README.md Execute these commands to run basic Turbomcp server examples. These demonstrate core functionalities like a simple hello world, a calculator, and macro-based servers. ```bash cargo run --example hello_world ``` ```bash cargo run --example calculator ``` ```bash cargo run --example macro_server ``` -------------------------------- ### Run Protected Resource Server Example with RFC 9728 Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-auth/README.md Execute this command to run the example that implements a protected resource server compliant with RFC 9728. ```bash cargo run --example protected_resource_server ``` -------------------------------- ### Complete Turbomcp Server Example Source: https://github.com/epistates/turbomcp/blob/main/docs/architecture/context-lifecycle.md A full example demonstrating how to set up a turbomcp server with custom middleware (`RequestIdMiddleware`), built-in middleware (`LoggingMiddleware`, `MetricsMiddleware`), and a handler function (`process_data`). Requires `tokio` for async runtime. ```rust use turbomcp::prelude::*; #[server] pub struct MyServer; // Custom middleware pub struct RequestIdMiddleware; #[async_trait] impl Middleware for RequestIdMiddleware { async fn process( &self, request: JsonRpcRequest, ctx: &RequestContext, next: Next<'_>, ) -> McpResult { println!("Request ID: {}", ctx.request_id()); let response = next.run(request, ctx).await; println!("Response ready for: {}", ctx.request_id()); response } } #[tool] pub async fn process_data( data: String, ctx: Context, logger: Logger, ) -> McpResult { logger .with_field("request_id", ctx.request_id().to_string()) .with_field("data_len", data.len()) .info("Processing data") .await?; // Simulate processing tokio::time::sleep(Duration::from_millis(100)).await; Ok(format!("Processed: {}", data)) } #[tokio::main] async fn main() -> Result<()> { MyServer::new() .with_middleware(RequestIdMiddleware) .with_middleware(LoggingMiddleware::new()) .with_middleware(MetricsMiddleware::new()) .stdio() .run() .await } ``` -------------------------------- ### Run Schema Export Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/examples/README.md Generates OpenAPI 3.1, GraphQL SDL, and Protobuf 3 definitions from an MCP server capability snapshot. With no arguments it uses a built-in mock spec so the example is always runnable. ```bash # Self-contained mock spec; no backend required cargo run -p turbomcp-proxy --example schema_export # Real STDIO backend cargo run -p turbomcp-proxy --example schema_export -- \ --backend stdio --cmd "your-mcp-server" # Real TCP backend cargo run -p turbomcp-proxy --example schema_export -- \ --backend tcp --tcp 127.0.0.1:8765 # Real Unix socket backend cargo run -p turbomcp-proxy --example schema_export -- \ --backend unix --unix /tmp/turbomcp-demo.sock ``` -------------------------------- ### Run Tower Middleware Rate Limiting Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-auth/README.md Execute this command to run the example demonstrating Tower middleware for rate limiting. Ensure the 'middleware' feature is enabled. ```bash cargo run --example tower_rate_limiting --features middleware ``` -------------------------------- ### Run Cargo Examples Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/development.md Commands to list and run specific examples provided within the Cargo project, with options for features and debug output. ```bash # List all examples cargo run --example # Run specific example cargo run --example hello_world cargo run --example macro_server cargo run --example http_app # Run with features cargo run --example http_app --features http,simd # Run with debug output RUST_LOG=debug cargo run --example macro_server ``` -------------------------------- ### Quick Start with McpHandler Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-server/README.md Demonstrates how to implement the McpHandler trait and use the #[server] macro to create a callable RPC service. The `run()` method starts the server using default STDOUT/STDIO transport. ```APIDOC ## Quick Start Any type that implements `McpHandler` (the `#[server]` macro generates one for you) gets the `run*` and `builder()` methods automatically via blanket impls. ```rust,ignore use turbomcp::prelude::*; #[derive(Clone)] struct Calculator; #[server(name = "calculator", version = "1.0.0")] impl Calculator { /// Add two numbers #[tool] async fn add(&self, a: i64, b: i64) -> i64 { a + b } } #[tokio::main] async fn main() -> McpResult<()> { // STDIO by default Calculator.run().await } ``` ``` -------------------------------- ### Run Turbomcp Server Pattern Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/README.md Explore advanced server patterns by running these examples. They cover state management, validation, composition, middleware, visibility, and tag/versioning strategies. ```bash cargo run --example stateful ``` ```bash cargo run --example validation ``` ```bash cargo run --example composition ``` ```bash cargo run --example middleware ``` ```bash cargo run --example visibility ``` ```bash cargo run --example tags_versioning ``` -------------------------------- ### Install Turbomcp-Proxy from Source Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/README.md Installs the turbomcp-proxy binary by building it directly from the source code. This is useful for development or when using a specific commit. ```bash cd crates/turbomcp-proxy cargo install --path . ``` -------------------------------- ### Run Composition Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Demonstrates prefixed tool names, resource aggregation, duplicate-prefix handling, and direct handler invocation. Use this to understand advanced server composition. ```bash cargo run -p turbomcp --example composition ``` -------------------------------- ### Configure server settings Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/documentation.md Examples for setting up server configuration, including defaults and environment-specific presets. ```rust use turbomcp::config::*; let config = ServerConfig { // Connection settings max_connections: 1000, // Default: 1000 connection_timeout: Duration::from_secs(30), // Default: 30s idle_timeout: Duration::from_secs(300), // Default: 5min // Request limits max_request_size: 1024 * 1024, // Default: 1MB max_response_size: 10 * 1024 * 1024, // Default: 10MB // Performance worker_threads: 4, // Default: num_cpus use_simd: true, // Default: false }; ``` ```rust // Development config let dev_config = ServerConfig::development(); // Production config let prod_config = ServerConfig::production(); // Custom config let custom_config = ServerConfig::default() .with_max_connections(5000) .with_connection_timeout(Duration::from_secs(60)) .with_simd(true); ``` -------------------------------- ### Initialize OpenTelemetry with TurboMCP Telemetry Source: https://github.com/epistates/turbomcp/blob/main/docs/guide/observability.md Quick start example for initializing OpenTelemetry with custom service name, version, OTLP endpoint, Prometheus port, and log level. This setup enables full observability for your MCP server. ```rust use turbomcp_telemetry::{TelemetryConfig, TelemetryGuard}; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize OpenTelemetry let config = TelemetryConfig::builder() .service_name("my-mcp-server") .service_version("1.0.0") .otlp_endpoint("http://jaeger:4317") .prometheus_port(9090) .log_level("info,turbomcp=debug") .build(); let _guard = config.init()?; // Your MCP server runs with full observability let server = McpServer::new() .stdio() .run() .await?; Ok(()) } ``` -------------------------------- ### Struct Documentation Example Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/development.md Standard format for documenting structs and their usage. ```rust /// MCP server instance. /// /// The server manages handlers, middleware, and transport protocols. /// /// # Examples /// /// ``` /// use turbomcp::prelude::*; /// /// #[tokio::main] /// async fn main() -> Result<()> { /// McpServer::new() /// .stdio() /// .run() /// .await /// } /// ``` pub struct McpServer { // fields... } ``` -------------------------------- ### Run Schema Export Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Covers schema export for the proxy. Runs with a built-in mock spec by default. TCP and Unix backend examples require a live MCP backend. ```bash cargo run -p turbomcp-proxy --example schema_export ``` -------------------------------- ### Run Visibility Example Source: https://github.com/epistates/turbomcp/blob/main/docs/examples/advanced.md Demonstrates `VisibilityLayer` for exposing different tools or resources based on tags, names, or session-specific grants. Prefer a small allowlist plus read-only annotations for AI-facing deployments. ```bash cargo run -p turbomcp --example visibility ``` -------------------------------- ### JavaScript MCP Client Setup Source: https://github.com/epistates/turbomcp/blob/main/docs/deployment/edge.md Set up a new Cloudflare Worker project and install the turbomcp-wasm package for using the MCP client. ```bash npm create cloudflare@latest my-mcp-worker cd my-mcp-worker npm install turbomcp-wasm ``` -------------------------------- ### Cloudflare Access Authentication Setup Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-wasm/README.md Example of how to integrate Cloudflare Access for authentication in a production environment. This is the recommended approach for zero-trust security. ```rust use turbomcp_wasm::auth::CloudflareAccessAuthenticator; let auth = CloudflareAccessAuthenticator::new("your-team", "your-audience-tag"); let protected = server.with_auth(auth); ``` -------------------------------- ### Run Local Development Server Source: https://github.com/epistates/turbomcp/blob/main/docs/README.md Starts a local server to preview documentation changes in real-time. ```bash mkdocs serve ``` -------------------------------- ### Run TCP Backend Introspection Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/examples/README.md Shows how to configure a TCP backend, initialize the MCP client connection, and print tools/resources/prompts discovered from the backend. ```bash # Terminal 1: start the workspace TCP MCP server cargo run -p turbomcp --example tcp_server --features tcp # Terminal 2: connect and introspect it cargo run -p turbomcp-proxy --example tcp_backend ``` -------------------------------- ### Integration Test Full Workflow Source: https://github.com/epistates/turbomcp/blob/main/docs/api/client.md Perform integration testing by starting a `TestServer`, creating a client, and executing a sequence of operations. Includes basic setup and cleanup. ```rust #[tokio::test] async fn test_full_workflow() { // Start test server let server = tokio::spawn(async { TestServer.run_stdio().await.unwrap(); }); // Give server time to start tokio::time::sleep(Duration::from_millis(100)).await; // Create client let transport = StdioTransport::new(); let client = Client::new(transport); // Test operations client.initialize().await.unwrap(); let tools = client.list_tools().await.unwrap(); assert!(!tools.is_empty()); // Cleanup server.abort(); } ``` -------------------------------- ### Developer API Setup Source: https://github.com/epistates/turbomcp/blob/main/docs/guide/architecture.md Shows how to set up a server and a tool using the main `turbomcp` SDK, including prelude imports and attribute macros. ```rust use turbomcp::prelude::*; #[server] struct MyServer; #[tool] async fn my_tool(input: String) -> McpResult { Ok(input) } ``` -------------------------------- ### Create a dynamic time resource Source: https://github.com/epistates/turbomcp/blob/main/docs/api/macros.md Generate dynamic resources, such as the current server time, by implementing the resource handler logic. This example uses the `chrono` crate to get the current UTC time. ```rust /// Current server time #[resource("time://now")] async fn current_time(&self, uri: String, ctx: &RequestContext) -> McpResult { use chrono::Utc; let now = Utc::now().to_rfc3339(); Ok(ResourceResult::text(&uri, now)) } ``` -------------------------------- ### Install TurboMCP CLI Source: https://github.com/epistates/turbomcp/blob/main/docs/getting-started/first-server.md Installs the TurboMCP command-line interface tool. ```bash cargo install turbomcp-cli ``` -------------------------------- ### Basic STDIO Client Initialization and Usage Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-client/README.md Demonstrates creating a client with STDIO transport, initializing the connection, listing available tools, and calling a specific tool with arguments. Ensure the server is running and accessible via STDIO. ```rust use turbomcp_client::Client; use turbomcp_transport::stdio::StdioTransport; #[tokio::main] async fn main() -> turbomcp_protocol::Result<()> { // Create client with STDIO transport let transport = StdioTransport::new(); let client = Client::new(transport); // Initialize connection let result = client.initialize().await?; println!("Connected to: {}", result.server_info.name); // List and call tools let tools = client.list_tools().await?; for tool in &tools { println!("Tool: {} - {}", tool.name, tool.description.as_deref().unwrap_or("No description")); } // Call a tool let result = client.call_tool( "calculator", Some(std::collections::HashMap::from([ ("operation".to_string(), serde_json::json!("add")), ("a".to_string(), serde_json::json!(5)), ("b".to_string(), serde_json::json!(3)), ])), None, // optional task metadata ).await?; println!("Result: {:?}", result); Ok(()) } ``` -------------------------------- ### Structure bad documentation examples Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/documentation.md An example of poor documentation structure to avoid. ```markdown ## Dependency Injection You can inject dependencies into tools. Here's how: [Giant wall of text with no structure] [Code example with no context] [Another wall of text] ``` -------------------------------- ### Quick Start WebSocket Client Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-websocket/README.md Demonstrates how to create and connect a WebSocket client transport using the provided configuration. ```rust use turbomcp_websocket::{WebSocketBidirectionalTransport, WebSocketBidirectionalConfig}; use turbomcp_transport_traits::Transport; #[tokio::main] async fn main() -> Result<(), Box> { // Create client configuration let config = WebSocketBidirectionalConfig::client("ws://localhost:8080".to_string()) .with_max_concurrent_elicitations(5); // Create and connect transport let transport = WebSocketBidirectionalTransport::new(config).await?; transport.connect().await?; // Use the transport... Ok(()) } ``` -------------------------------- ### Run Turbomcp Capability Builders and Testing Examples Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/README.md Explore examples related to capability builders and testing utilities within Turbomcp. These examples showcase type-state builders and test client interactions. ```bash cargo run --example type_state_builders_demo ``` ```bash cargo run --example test_client ``` -------------------------------- ### Install Turbomcp CLI Tools Source: https://github.com/epistates/turbomcp/blob/main/crates/README.md Install the Turbomcp command-line interface tools using Cargo. ```bash # Install CLI tools ``` ```bash cargo install --path turbomcp-cli ``` -------------------------------- ### Install turbomcp-cli from Source Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-cli/README.md Clones the turbomcp repository and installs the turbomcp-cli from the local source code. ```bash git clone https://github.com/Epistates/turbomcp.git cd turbomcp cargo install --path crates/turbomcp-cli ``` -------------------------------- ### Test Server with CLI Source: https://github.com/epistates/turbomcp/blob/main/docs/getting-started/quick-start.md Commands to install the CLI and interact with the running server. ```bash # Install CLI if you haven't\ncargo install turbomcp-cli\n\n# List tools\nturbomcp-cli tools list --command "./target/debug/your-server"\n\n# Call the tool\nturbomcp-cli tools call hello --arguments '{"name": "World"}' \\\n --command "./target/debug/your-server" ``` -------------------------------- ### Rustdoc Module Documentation Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/documentation.md Example of documenting a Rust module, including its purpose, overview, and usage examples. ```rust //! # Module Name //! //! Brief description of module purpose. //! //! ## Overview //! //! Detailed explanation of what this module provides. //! //! ## Examples //! //! ``` //! use turbomcp::module_name::Type; //! //! let instance = Type::new(); //! ``` pub mod my_module; ``` -------------------------------- ### Test documentation examples Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/documentation.md Demonstrates how to include hidden test code within documentation examples and run them. ```rust use turbomcp::prelude::*; #[tool] pub async fn add(a: i32, b: i32) -> McpResult { Ok(a + b) } # #[tokio::test] # async fn test_add() { # assert_eq!(add(2, 3).await.unwrap(), 5); # } ``` ```bash # Test documentation examples cargo test --doc ``` -------------------------------- ### Initialize Connection and Negotiate Capabilities Source: https://github.com/epistates/turbomcp/blob/main/docs/api/client.md Establishes the connection and inspects server capabilities like tools, resources, and prompts. ```rust let init_result = client.initialize().await?; println!("Server: {} v{}", init_result.server_info.name, init_result.server_info.version ); // Check server capabilities if init_result.capabilities.tools.is_some() { println!("Server supports tools"); } if init_result.capabilities.resources.is_some() { println!("Server supports resources"); } if init_result.capabilities.prompts.is_some() { println!("Server supports prompts"); } ``` -------------------------------- ### JSON-RPC 2.0 Request Example Source: https://github.com/epistates/turbomcp/blob/main/docs/api/protocol.md Example of a JSON-RPC 2.0 request with an ID, method, parameters, and version. ```json { "jsonrpc": "2.0", "method": "tools/call", "params": {"name": "get_weather", "arguments": {}}, "id": 1 } ``` -------------------------------- ### Implement Tool Handlers Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/documentation.md Examples demonstrating the progression from basic tool definitions to production-ready implementations using dependency injection. ```rust #[tool] pub async fn hello(name: String) -> McpResult { Ok(format!("Hello, {}!", name)) } ``` ```rust #[tool] pub async fn hello( name: String, logger: Logger, ) -> McpResult { logger.info("Greeting user").await?; Ok(format!("Hello, {}!", name)) } ``` ```rust #[tool] #[description("Greet a user by name")] pub async fn hello( #[description("User's name")] name: String, ctx: Context, logger: Logger, db: Database, ) -> McpResult { logger .with_field("request_id", ctx.request_id().to_string()) .with_field("name", &name) .info("Greeting user") .await?; // Log interaction db.execute( "INSERT INTO greetings (name, timestamp) VALUES ($1, $2)", &[&name, &Utc::now()], ).await?; Ok(format!("Hello, {}!", name)) } ``` -------------------------------- ### Install turbomcp-cli from Crates.io Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-cli/README.md Installs the latest stable version or a specific version of the turbomcp-cli using Cargo. ```bash cargo install turbomcp-cli ``` ```bash cargo install turbomcp-cli --version 3.1.4 ``` -------------------------------- ### Install cargo-fuzz Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-protocol/fuzz/README.md Installs cargo-fuzz, a tool for fuzz testing Rust projects. Requires nightly Rust. ```bash cargo install cargo-fuzz ``` -------------------------------- ### Start gRPC Server (Development) Source: https://github.com/epistates/turbomcp/blob/main/docs/guide/transports.md Configure and start a gRPC server without TLS for development purposes. ```rust // Without TLS (development) tonic::transport::Server::builder() .add_service(server.into_service()) .serve("[::1]:50051".parse()?) .await?; ``` -------------------------------- ### JSON-RPC 2.0 Notification Example Source: https://github.com/epistates/turbomcp/blob/main/docs/api/protocol.md Example of a JSON-RPC 2.0 notification, which has a method and parameters but no ID as no response is expected. ```json { "jsonrpc": "2.0", "method": "resources/updated", "params": {} } ``` -------------------------------- ### JSON-RPC 2.0 Response Example Source: https://github.com/epistates/turbomcp/blob/main/docs/api/protocol.md Example of a JSON-RPC 2.0 response containing a result and the corresponding request ID. ```json { "jsonrpc": "2.0", "result": {"temperature": 72}, "id": 1 } ``` -------------------------------- ### Calculator Server Implementation Source: https://github.com/epistates/turbomcp/blob/main/README.md This example demonstrates how to define a server using the `#[server]` macro, implementing the `add` and `multiply` tools. The server can then be run using `run_stdio()`. ```APIDOC ## Calculator Server Implementation ### Description This example demonstrates how to define a server using the `#[server]` macro, implementing the `add` and `multiply` tools. The server can then be run using `run_stdio()`. ### Server Definition ```rust #[derive(Clone)] struct Calculator; #[server(name = "calculator", version = "1.0.0")] impl Calculator { /// Add two numbers together. #[tool] async fn add(&self, a: i64, b: i64) -> i64 { a + b } /// Multiply two numbers. #[tool] async fn multiply(&self, a: i64, b: i64) -> i64 { a * b } } ``` ### Running the Server ```rust #[tokio::main] async fn main() -> Result<(), Box> { Calculator.run_stdio().await?; Ok(()) } ``` ### Client Connection Configuration (Claude Desktop) ```json { "mcpServers": { "calculator": { "command": "/path/to/your/server", "args": [] } } } ``` ``` -------------------------------- ### Create Next.js App and Install Turbomcp Source: https://github.com/epistates/turbomcp/blob/main/docs/deployment/edge.md Initializes a new Next.js project and installs the Turbomcp WASM package. ```bash npx create-next-app@latest my-mcp-app cd my-mcp-app npm install turbomcp-wasm ``` -------------------------------- ### Install Turbomcp-Proxy from crates.io Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-proxy/README.md Installs the turbomcp-proxy binary using Cargo from the crates.io registry. This is the recommended method for most users. ```bash cargo install turbomcp-proxy ``` -------------------------------- ### Organize documentation sections Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/documentation.md Example of proper section nesting for dependency injection documentation. ```markdown ## Dependency Injection ### Overview TurboMCP provides compile-time dependency injection... ### Injectable Types Built-in types you can inject: #### Context Request metadata and correlation IDs. ```rust #[tool] pub async fn my_tool(ctx: Context) -> McpResult { // ... } ``` #### Logger Structured logging with correlation. ```rust #[tool] pub async fn my_tool(logger: Logger) -> McpResult { // ... } ``` ### Custom Dependencies Register your own types... ``` -------------------------------- ### List and Call Tools with Turbomcp Client Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-client/README.md Demonstrates how to list available tools, retrieve their names, and invoke a tool with specific arguments. Ensure the client is initialized before use. ```rust use std::collections::HashMap; // List available tools let tools = client.list_tools().await?; for tool in &tools { println!("{}: {}", tool.name, tool.description.as_deref().unwrap_or("")); } // List tool names only let names = client.list_tool_names().await?; // Call a tool let mut args = HashMap::new(); args.insert("text".to_string(), serde_json::json!("Hello, world!")); let result = client.call_tool("echo", Some(args), None).await?; ``` -------------------------------- ### Install and Run Cargo Fuzz Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/development.md Instructions for installing `cargo-fuzz` (requires nightly Rust) and running fuzz tests for protocol parsers. ```bash # Install cargo-fuzz (requires nightly Rust) cargo install cargo-fuzz # Run JSON-RPC parser fuzzing cd crates/turbomcp-protocol cargo +nightly fuzz run fuzz_jsonrpc_parsing ``` -------------------------------- ### Build TurboMCP WASM Server with Tools, Resources, and Prompts Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-wasm/README.md Example of setting up a TurboMCP WASM server, defining tools, static and dynamic resources, and prompts with their respective handlers. ```rust use turbomcp_wasm::wasm_server::*; use worker::*; #[event(fetch)] async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result { let server = McpServer::builder("full-server", "1.0.0") // Tools - ergonomic API .tool("search", "Search the database", search_handler) // Static resource .resource( "config://settings", "Application Settings", "Current application configuration", |_uri| async move { ResourceResult::json("config://settings", &serde_json::json!({ "theme": "dark", "language": "en" })) }, ) // Dynamic resource template .resource_template( "user://{id}", "User Profile", "Get user profile by ID", |uri| async move { let id = uri.split('/').last().unwrap_or("unknown"); Ok(ResourceResult::text(&uri, format!("User {}", id))) }, ) // Prompt with no arguments .prompt_no_args( "greeting", "Generate a greeting", || async move { PromptResult::user("Hello! How can I help?") }, ) .build(); server.handle(req).await } ``` -------------------------------- ### Initialize and Use gRPC Client Source: https://github.com/epistates/turbomcp/blob/main/docs/api/grpc.md Connect to the gRPC server, initialize the client, and make sample calls to list tools and call a tool. ```rust use turbomcp_grpc::McpGrpcClient; #[tokio::main] async fn main() -> Result<(), Box> { let mut client = McpGrpcClient::connect("http://[::1]:50051").await?; let init_result = client.initialize().await?; println!("Connected to: {:?}", init_result.server_info); let tools = client.list_tools().await?; println!("Available tools: {:?}", tools); let result = client .call_tool("hello", Some(serde_json::json!({"name": "World"}))) .await?; println!("Result: {:?}", result); Ok(()) } ``` -------------------------------- ### Execute Server Tools Source: https://github.com/epistates/turbomcp/blob/main/docs/api/client.md Demonstrates building arguments and calling a tool, followed by handling different response content types. ```rust use std::collections::HashMap; // Build arguments let mut args = HashMap::new(); args.insert("city".to_string(), serde_json::json!("San Francisco")); args.insert("units".to_string(), serde_json::json!("metric")); // Call tool let result = client.call_tool("get_weather", Some(args)).await?; // Parse result match result.content { ToolCallContent::Text { text } => { println!("Result: {}", text); } ToolCallContent::Image { data, mime_type } => { println!("Got image: {} ({} bytes)", mime_type, data.len()); } ToolCallContent::Resource { uri, text, blob } => { println!("Got resource: {}", uri); } } ``` -------------------------------- ### Module Documentation Example Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/development.md Standard format for documenting modules using doc comments. ```rust //! # Module Name //! //! Brief description of what this module does. //! //! ## Examples //! //! ``` //! use turbomcp::prelude::*; //! //! let server = McpServer::new(); //! ``` mod my_module; ``` -------------------------------- ### VS Code Debugger Configuration for Cargo Examples Source: https://github.com/epistates/turbomcp/blob/main/docs/contributing/development.md A `launch.json` configuration for VS Code to debug a specific Cargo example using the LLDB debugger. ```json { "version": "0.2.0", "configurations": [ { "type": "lldb", "request": "launch", "name": "Debug example 'hello_world'", "cargo": { "args": ["build", "--example", "hello_world"], "filter": { "name": "hello_world", "kind": "example" } }, "args": [], "cwd": "${workspaceFolder}" } ] } ``` -------------------------------- ### Kibana Log Query Examples Source: https://github.com/epistates/turbomcp/blob/main/docs/deployment/monitoring.md Provides example queries for Kibana to filter TurboMCP logs by service and error level, or by service and request ID. ```text service:turbomcp AND level:error service:turbomcp AND request_id:550e8400* ``` -------------------------------- ### Conventional Commits: Fix Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/CONTRIBUTING.md Example of a conventional commit message for a bug fix, including a scope, subject, body, and a breaking change note. ```bash fix(uri): prevent directory traversal in template matching Security fix for URI template parameter extraction that could allow directory traversal attacks. BREAKING CHANGE: URI parameters now validate against allowed patterns ``` -------------------------------- ### Server Implementation with Handler Macros Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-macros/MIGRATION.md Example demonstrating the usage of `#[server]`, `#[tool]`, `#[resource]`, and `#[prompt]` macros for defining a server with different types of handlers. Schema generation is always enabled. ```rust use turbomcp::prelude::*; #[derive(Clone)] struct MyServer; #[server(name = "my-server", version = "1.0.0")] impl MyServer { /// Compute the sum of two integers #[tool] async fn add( &self, #[description("First operand")] a: i64, #[description("Second operand")] b: i64, ) -> i64 { a + b } /// Application configuration #[resource("config://app", mime_type = "application/json")] async fn config(&self, uri: String, ctx: &RequestContext) -> String { r#"{"debug": false}"#.to_string() } /// Greeting prompt #[prompt] async fn greet(&self, name: String, ctx: &RequestContext) -> String { format!("Hello, {}! How can I help you today?", name) } } ``` -------------------------------- ### Define and Run a Calculator Server with TurboMCP Source: https://github.com/epistates/turbomcp/blob/main/README.md Implement a Calculator server using the turbomcp SDK. This example defines 'add' and 'multiply' tools and runs the server over stdio. Ensure tokio is enabled for async operations. ```rust use turbomcp::prelude::*; #[derive(Clone)] struct Calculator; #[server(name = "calculator", version = "1.0.0")] impl Calculator { /// Add two numbers together. #[tool] async fn add(&self, a: i64, b: i64) -> i64 { a + b } /// Multiply two numbers. #[tool] async fn multiply(&self, a: i64, b: i64) -> i64 { a * b } } #[tokio::main] async fn main() -> Result<(), Box> { Calculator.run_stdio().await?; Ok(()) } ``` -------------------------------- ### Conventional Commits: Feature Example Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp/CONTRIBUTING.md Example of a conventional commit message for a new feature, including a scope, subject, body, and footer to close an issue. ```bash feat(server): add OAuth 2.0 authentication support Implements complete OAuth 2.0 flow with PKCE support: - Authorization code flow with state parameter - Token refresh and validation - Comprehensive error handling Closes #456 ``` -------------------------------- ### Initialize and Use McpClient Source: https://github.com/epistates/turbomcp/blob/main/docs/api/wasm.md Shows basic initialization of the McpClient, setting authentication and timeout, listing tools, and calling a tool. ```javascript import init, { McpClient } from 'turbomcp-wasm'; async function main() { await init(); const client = new McpClient("https://api.example.com/mcp") .withAuth("token") .withTimeout(30000); await client.initialize(); const tools = await client.listTools(); console.log("Tools:", tools); const result = await client.callTool("hello", { name: "World" }); console.log("Result:", result); } main().catch(console.error); ``` -------------------------------- ### Install turbomcp-wasm Client (NPM) Source: https://github.com/epistates/turbomcp/blob/main/crates/turbomcp-wasm/README.md Install the turbomcp-wasm client library using npm. This is the primary method for integrating the client into your JavaScript or TypeScript projects. ```bash npm install turbomcp-wasm ```