Skip to main content

Crate turul_mcp_client

Crate turul_mcp_client 

Source
Expand description

§MCP Client Library

Production-ready Rust client for Model Context Protocol (MCP) servers.

Connect to MCP servers with full protocol compliance, multiple transport options, and automatic session management. Supports both synchronous and streaming operations with comprehensive error handling and recovery mechanisms.

Crates.io Documentation License

§Features

  • Multi-transport: HTTP and Server-Sent Events (SSE), with stdio planned
  • Full Protocol: Complete MCP 2025-11-25 specification support
  • High Performance: Built on Tokio with async/await throughout
  • Session Management: Automatic connection handling and recovery
  • Real-time Streaming: SSE support for progress and notifications
  • Error Handling: Comprehensive error types with automatic retry
  • Configurable: Timeouts, retries, connection pooling

§Installation

[dependencies]
turul-mcp-client = "0.3"
tokio = { version = "1.0", features = ["full"] }

§Quick Start

use turul_mcp_client::{McpClient, McpClientBuilder, transport::HttpTransport};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let transport = HttpTransport::new("http://localhost:8080/mcp")?;
    let client = McpClientBuilder::new()
        .with_transport(Box::new(transport))
        .build();

    client.connect().await?;

    let tools = client.list_tools().await?;
    println!("Available tools: {:?}", tools);

    Ok(())
}

§Transport Types

§HTTP Transport (Streamable HTTP)

The Streamable HTTP transport sends each MCP request as an independent HTTP POST. There is no persistent connection — session continuity is maintained via the Mcp-Session-Id header that the server returns during initialization and that the client includes on all subsequent requests.

transport.connect() only marks the transport as logically ready; it performs no network I/O. The first real validation happens when McpClient::connect() sends the initialize POST followed by notifications/initialized. If the server is unreachable or rejects the handshake, the error surfaces there.

use turul_mcp_client::transport::HttpTransport;

let transport = HttpTransport::new("http://localhost:8080/mcp")?;

§SSE Transport (HTTP+SSE, legacy)

For servers using the pre-2025-03-26 SSE-based protocol. Like the HTTP transport, connect() is a no-op marker — the SSE subscription is established lazily during message exchange.

use turul_mcp_client::transport::SseTransport;

let transport = SseTransport::new("http://localhost:8080/mcp")?;

§Future Transports

Stdio transports are planned for future releases:

// Coming soon:
// StdioTransport::new("./mcp-server-executable")

§Common Operations

§Tool Execution

// List available tools
let tools = client.list_tools().await?;
println!("Available tools: {:?}", tools);

// Execute a tool
let result = client.call_tool("calculator", serde_json::json!({
    "operation": "add",
    "a": 5,
    "b": 3
})).await?;
println!("Result: {:?}", result);

§Resource Access

// List available resources
let resources = client.list_resources().await?;

// Discover dynamic URI templates
let templates = client.list_resource_templates().await?;

// Read a specific resource
let content = client.read_resource("file://config.json").await?;
println!("Resource content: {:?}", content);

§Prompt Templates

// List available prompts
let prompts = client.list_prompts().await?;

// Get a prompt with arguments
let prompt = client.get_prompt("code_review", Some(serde_json::json!({
    "language": "rust",
    "code": "fn main() { println!(\"Hello!\"); }"
}))).await?;

§Configuration

The client supports extensive configuration:


// Create a client with default configuration
let client = McpClientBuilder::new()
    .build();

§Real-time Streaming

For real-time notifications and progress updates:

// Get available tools from server
let tools = client.list_tools().await?;
println!("Available tools: {}", tools.len());

§Examples

Complete examples available at: github.com/aussierobots/turul-mcp-framework/tree/main/examples

  • Basic Client - Simple tool execution
  • Streaming Client - Real-time notifications
  • HTTP Client - Production HTTP integration
  • Retry Logic - Error handling and recovery
  • Monitoring - Connection health and metrics

Re-exports§

pub use client::McpClient;
pub use client::McpClientBuilder;
pub use client::ToolCallResponse;
pub use config::ClientConfig;
pub use config::RetryConfig;
pub use config::TimeoutConfig;
pub use error::McpClientError;
pub use error::McpClientResult;
pub use session::SessionInfo;
pub use session::SessionManager;
pub use session::SessionState;
pub use transport::Transport;
pub use transport::TransportType;

Modules§

client
Main MCP client implementation
completion
Core MCP protocol types and message structures MCP Completion Protocol Types
config
Configuration types for MCP client
content
Core MCP protocol types and message structures Content types for MCP 2025-11-25 specification
elicitation
Core MCP protocol types and message structures MCP Elicitation Protocol Types
error
Error types for MCP client operations
icons
Core MCP protocol types and message structures MCP Icon Types
initialize
Core MCP protocol types and message structures MCP Initialize Protocol Types
json_rpc
Core MCP protocol types and message structures JSON-RPC 2.0 Implementation for MCP 2025-11-25
logging
Core MCP protocol types and message structures MCP Logging Protocol Types
meta
Core MCP protocol types and message structures _meta Field Support for MCP 2025-11-25
notifications
Core MCP protocol types and message structures MCP Notifications Protocol Types
param_extraction
Core MCP protocol types and message structures Parameter extraction utilities for MCP protocol
ping
Core MCP protocol types and message structures MCP Ping Protocol Types
prelude
MCP Client Prelude
prompts
Core MCP protocol types and message structures MCP Prompts Protocol Types
resources
Core MCP protocol types and message structures MCP Resources Protocol Types
roots
Core MCP protocol types and message structures MCP Roots Protocol Types
sampling
Core MCP protocol types and message structures MCP Sampling Protocol Types
schema
Core MCP protocol types and message structures JSON Schema Support for MCP
session
Session management for MCP client
streaming
Streaming support for MCP client
tasks
Core MCP protocol types and message structures MCP Tasks Protocol Types
tools
Core MCP protocol types and message structures MCP Tools Protocol Types
traits
Core MCP protocol types and message structures Traits for JSON-RPC types as per MCP specification (2025-11-25)
transport
Transport layer for MCP client
version
Core MCP protocol types and message structures MCP Protocol Version Support

Macros§

client_error
Convenience macro for creating generic errors
impl_serde_extractor
Core MCP protocol types and message structures Macro to implement SerdeParamExtractor for any Params type that implements Deserialize

Structs§

Annotations
Core MCP protocol types and message structures Annotations for resources, prompts, and tools (matches TypeScript Annotations per MCP 2025-11-25). See MCP spec
BlobResourceContents
Core MCP protocol types and message structures Binary resource contents (matches TypeScript BlobResourceContents exactly)
CallToolRequest
Core MCP protocol types and message structures Complete tools/call request (matches TypeScript CallToolRequest interface)
CallToolResult
Core MCP protocol types and message structures Result for tools/call (per MCP spec)
CancelTaskParams
Core MCP protocol types and message structures Parameters for tasks/cancel request
CancelTaskRequest
Core MCP protocol types and message structures Complete tasks/cancel request
CancelTaskResult
Core MCP protocol types and message structures Result for tasks/cancel — flattens Task fields per TS Result & Task
CancelledNotification
Core MCP protocol types and message structures Method: “notifications/cancelled”
ClientCapabilities
Core MCP protocol types and message structures Capabilities that a client may support (per MCP 2025-11-25)
CreateTaskResult
Core MCP protocol types and message structures Returned when a task-augmented request is accepted (instead of the operation’s direct result).
ElicitCreateParams
Core MCP protocol types and message structures Parameters for elicitation/create request (per MCP spec)
ElicitCreateRequest
Core MCP protocol types and message structures Complete elicitation/create request (matches TypeScript ElicitRequest interface)
ElicitResult
Core MCP protocol types and message structures The client’s response to an elicitation request (per MCP spec)
ElicitationBuilder
Core MCP protocol types and message structures Builder for creating common elicitation patterns
ElicitationCompleteNotification
Core MCP protocol types and message structures Method: “notifications/elicitation/complete” (per MCP 2025-11-25)
ElicitationSchema
Core MCP protocol types and message structures Restricted schema for elicitation (only primitive types, no nesting) - per MCP spec
EmptyParams
Core MCP protocol types and message structures
EmptyResult
Core MCP protocol types and message structures Empty result for successful operations (per MCP spec)
GetPromptRequest
Core MCP protocol types and message structures Complete prompts/get request (matches TypeScript GetPromptRequest interface)
GetPromptResult
Core MCP protocol types and message structures Result for prompts/get (per MCP spec)
GetTaskParams
Core MCP protocol types and message structures Parameters for tasks/get request
GetTaskPayloadParams
Core MCP protocol types and message structures Parameters for tasks/result request (retrieves the original operation’s result)
GetTaskPayloadRequest
Core MCP protocol types and message structures Complete tasks/result request
GetTaskRequest
Core MCP protocol types and message structures Complete tasks/get request
GetTaskResult
Core MCP protocol types and message structures Result for tasks/get — flattens Task fields per TS Result & Task
Icon
Core MCP protocol types and message structures Icon for tools, resources, prompts, and implementations. Icons are display hints — most implementations do not need icons. See MCP spec
Implementation
Core MCP protocol types and message structures Describes the name and version of an MCP implementation
InitializeRequest
Core MCP protocol types and message structures Parameters for initialize request
InitializeResult
Core MCP protocol types and message structures Result payload for initialize (per MCP spec)
InitializedNotification
Core MCP protocol types and message structures Method: “notifications/initialized”
JsonRpcError
Core MCP protocol types and message structures JSON-RPC 2.0 error object
JsonRpcNotification
Core MCP protocol types and message structures A JSON-RPC 2.0 notification (no response expected)
JsonRpcRequest
Core MCP protocol types and message structures A standard JSON-RPC 2.0 request
JsonRpcResponse
Core MCP protocol types and message structures A standard JSON-RPC 2.0 response
ListPromptsRequest
Core MCP protocol types and message structures Complete prompts/list request (matches TypeScript ListPromptsRequest interface)
ListPromptsResult
Core MCP protocol types and message structures Result for prompts/list (per MCP spec)
ListResourcesRequest
Core MCP protocol types and message structures Complete resources/list request (matches TypeScript ListResourcesRequest interface)
ListResourcesResult
Core MCP protocol types and message structures Result for resources/list (per MCP spec)
ListTasksParams
Core MCP protocol types and message structures Parameters for tasks/list request
ListTasksRequest
Core MCP protocol types and message structures Complete tasks/list request
ListTasksResult
Core MCP protocol types and message structures Result for tasks/list (extends PaginatedResult)
ListToolsRequest
Core MCP protocol types and message structures Complete tools/list request (matches TypeScript ListToolsRequest interface)
ListToolsResult
Core MCP protocol types and message structures Result for tools/list (per MCP spec) - extends PaginatedResult
LoggingMessageNotification
Core MCP protocol types and message structures Method: “notifications/message”
LoggingMessageNotificationParams
Core MCP protocol types and message structures
Meta
Core MCP protocol types and message structures Structured _meta field for MCP 2025-11-25
MetaCursor
Core MCP protocol types and message structures Cursor for pagination support
Notification
Core MCP protocol types and message structures Base notification structure following MCP TypeScript specification
NotificationParams
Core MCP protocol types and message structures Base notification parameters that can include _meta
PaginatedResponse
Core MCP protocol types and message structures Helper for pagination responses
PingRequest
Core MCP protocol types and message structures Request for ping (per MCP spec)
ProgressNotification
Core MCP protocol types and message structures Method: “notifications/progress”
ProgressNotificationParams
Core MCP protocol types and message structures
ProgressResponse
Core MCP protocol types and message structures Helper for progress responses
ProgressToken
Core MCP protocol types and message structures Progress token for tracking long-running operations
Prompt
Core MCP protocol types and message structures A prompt descriptor (matches TypeScript Prompt interface exactly)
PromptArgument
Core MCP protocol types and message structures Argument definition for prompts (extends BaseMetadata per MCP spec)
PromptListChangedNotification
Core MCP protocol types and message structures Method: “notifications/prompts/list_changed” (per MCP spec)
PromptMessage
Core MCP protocol types and message structures Message content for prompts (matches MCP PromptMessage interface exactly)
ReadResourceRequest
Core MCP protocol types and message structures Complete resources/read request (matches TypeScript ReadResourceRequest interface)
ReadResourceResult
Core MCP protocol types and message structures Result for resources/read (per MCP spec)
RequestParams
Core MCP protocol types and message structures JSON-RPC params object with optional _meta and method-specific arguments
Resource
Core MCP protocol types and message structures A resource descriptor (matches TypeScript Resource interface) Resource extends BaseMetadata, so it includes name and title fields
ResourceListChangedNotification
Core MCP protocol types and message structures Method: “notifications/resources/list_changed” (per MCP spec)
ResourceReference
Core MCP protocol types and message structures Resource reference for resource links (matches TypeScript Resource interface)
ResourceSubscription
Core MCP protocol types and message structures Resource subscription parameters
ResourceUpdatedNotification
Core MCP protocol types and message structures Method: “notifications/resources/updated”
ResourceUpdatedNotificationParams
Core MCP protocol types and message structures
ResultWithMeta
Core MCP protocol types and message structures A generic result wrapper that combines data with optional _meta information
RootsListChangedNotification
Core MCP protocol types and message structures Method: “notifications/roots/list_changed” (per MCP spec)
ServerCapabilities
Core MCP protocol types and message structures Capabilities that a server may support
SubscribeRequest
Core MCP protocol types and message structures Complete resources/subscribe request (per MCP spec)
Task
Core MCP protocol types and message structures Core task descriptor per MCP 2025-11-25. See MCP spec
TaskMetadata
Core MCP protocol types and message structures Task metadata for task-augmented requests. Added to CallToolParams, CreateMessageParams, ElicitCreateParams to indicate that the operation should create a task.
TaskStatusNotification
Core MCP protocol types and message structures Method: “notifications/tasks/status” (per MCP 2025-11-25)
TasksCancelCapabilities
Core MCP protocol types and message structures Signals support for tasks/cancel — presence means supported, extensible via extra
TasksCapabilities
Core MCP protocol types and message structures Capabilities for tasks (per MCP 2025-11-25)
TasksListCapabilities
Core MCP protocol types and message structures Signals support for tasks/list — presence means supported, extensible via extra
TasksRequestCapabilities
Core MCP protocol types and message structures Describes which request types support task augmentation
TasksToolCallCapabilities
Core MCP protocol types and message structures Signals support for task-augmented tools/call — presence means supported
TasksToolCapabilities
Core MCP protocol types and message structures Tool-level task capabilities
TextResourceContents
Core MCP protocol types and message structures Text resource contents (matches TypeScript TextResourceContents exactly)
Tool
Core MCP protocol types and message structures Tool definition
ToolExecution
Core MCP protocol types and message structures Execution configuration for a tool (per MCP 2025-11-25)
ToolListChangedNotification
Core MCP protocol types and message structures Method: “notifications/tools/list_changed” (per MCP spec)
ToolSchema
Core MCP protocol types and message structures JSON Schema definition for tool input/output (matches TypeScript spec exactly) Must be an object with type: “object”, properties, and required fields
UnsubscribeRequest
Core MCP protocol types and message structures Complete resources/unsubscribe request (per MCP spec)

Enums§

ContentBlock
Core MCP protocol types and message structures Content block union type matching MCP 2025-11-25 specification exactly
ElicitAction
Core MCP protocol types and message structures User action in response to elicitation
IconTheme
Core MCP protocol types and message structures Theme preference for an icon (light or dark mode). See MCP spec
JsonRpcMessage
Core MCP protocol types and message structures Unified JSON-RPC message type
JsonSchema
Core MCP protocol types and message structures A JSON Schema definition
LegacyRequestParams
Core MCP protocol types and message structures Parameters for a JSON-RPC request
McpError
Core MCP protocol types and message structures MCP-specific errors
McpVersion
Core MCP protocol types and message structures Supported MCP protocol versions
PrimitiveSchemaDefinition
Core MCP protocol types and message structures Restricted schema definitions that only allow primitive types without nested objects or arrays (per MCP spec).
ProgressTokenValue
Core MCP protocol types and message structures Progress token value — can be a string or a number per MCP 2025-11-25. See MCP spec
RequestId
Core MCP protocol types and message structures A uniquely identifying ID for a JSON-RPC request. Can be a string or a number, but never null.
ResourceContent
Core MCP protocol types and message structures Union type for resource contents (matches TypeScript union)
ResourceContents
Core MCP protocol types and message structures Resource contents union type (matches TypeScript TextResourceContents | BlobResourceContents)
ResponseResult
Core MCP protocol types and message structures Result data for a JSON-RPC response
StringFormat
Core MCP protocol types and message structures String format constraints
TaskStatus
Core MCP protocol types and message structures Task status enum per MCP 2025-11-25. See MCP spec
TaskSupport
Core MCP protocol types and message structures Whether a tool supports long-running task execution (per MCP 2025-11-25)

Constants§

CURRENT_VERSION
Core MCP protocol types and message structures The current MCP protocol version implemented by this crate
MCP_VERSION
Core MCP protocol types and message structures The MCP protocol version implemented by this crate

Traits§

HasData
Core MCP protocol types and message structures
HasDataParam
Core MCP protocol types and message structures
HasMeta
Core MCP protocol types and message structures
HasMetaParam
Core MCP protocol types and message structures
HasProgressTokenParam
Core MCP protocol types and message structures
JsonRpcNotificationTrait
Core MCP protocol types and message structures
JsonRpcRequestTrait
Core MCP protocol types and message structures
JsonRpcResponseTrait
Core MCP protocol types and message structures
Params
Core MCP protocol types and message structures
RpcResult
Core MCP protocol types and message structures
WithMeta
Core MCP protocol types and message structures Trait for types that can include _meta fields

Type Aliases§

McpResult
Core MCP protocol types and message structures Common result type for MCP operations
ToolResult
Core MCP protocol types and message structures Tool result type - an alias for ContentBlock to maintain backward compatibility while ensuring MCP 2025-11-25 specification compliance