88use std:: ffi:: { CStr , CString } ;
99use std:: os:: raw:: c_char;
1010use std:: ptr;
11- use std:: sync:: Mutex ;
11+ use std:: sync:: { Mutex , OnceLock } ;
1212
1313use rmcp:: transport:: { SseClientTransport , StreamableHttpClientTransport } ;
1414use rmcp:: { ServiceExt , RoleClient } ;
1515use rmcp:: model:: { ClientInfo , ClientCapabilities , Implementation } ;
1616
1717// Global client instance (simplified approach - one client per process)
18- lazy_static:: lazy_static! {
19- static ref GLOBAL_CLIENT : Mutex <Option <McpClient >> = Mutex :: new( None ) ;
20- }
18+ static GLOBAL_CLIENT : OnceLock < Mutex < Option < McpClient > > > = OnceLock :: new ( ) ;
2119
2220/// Initialize the MCP library
2321/// Returns 0 on success, non-zero on error
@@ -345,8 +343,8 @@ pub extern "C" fn mcp_connect(
345343 * new_client. server_url . lock ( ) . unwrap ( ) = Some ( url) ;
346344
347345 // Store the client globally
348- let mut global_client = GLOBAL_CLIENT . lock ( ) . unwrap ( ) ;
349- * global_client = Some ( new_client) ;
346+ let global_client = GLOBAL_CLIENT . get_or_init ( || Mutex :: new ( None ) ) ;
347+ * global_client. lock ( ) . unwrap ( ) = Some ( new_client) ;
350348 }
351349
352350 match CString :: new ( result) {
@@ -360,8 +358,9 @@ pub extern "C" fn mcp_connect(
360358#[ no_mangle]
361359pub extern "C" fn mcp_list_tools ( _client_ptr : * mut McpClient ) -> * mut c_char {
362360 // Get global client
363- let global_client_guard = GLOBAL_CLIENT . lock ( ) . unwrap ( ) ;
364- let client = match global_client_guard. as_ref ( ) {
361+ let global_client_guard = GLOBAL_CLIENT . get ( )
362+ . and_then ( |c| Some ( c. lock ( ) . unwrap ( ) ) ) ;
363+ let client = match global_client_guard. as_ref ( ) . and_then ( |g| g. as_ref ( ) ) {
365364 Some ( c) => c,
366365 None => {
367366 let error = r#"{"error": "Not connected. Call mcp_connect() first"}"# ;
@@ -453,8 +452,9 @@ pub extern "C" fn mcp_call_tool(
453452 } ;
454453
455454 // Get global client
456- let global_client_guard = GLOBAL_CLIENT . lock ( ) . unwrap ( ) ;
457- let client = match global_client_guard. as_ref ( ) {
455+ let global_client_guard = GLOBAL_CLIENT . get ( )
456+ . and_then ( |c| Some ( c. lock ( ) . unwrap ( ) ) ) ;
457+ let client = match global_client_guard. as_ref ( ) . and_then ( |g| g. as_ref ( ) ) {
458458 Some ( c) => c,
459459 None => {
460460 let error = r#"{"error": "Not connected. Call mcp_connect() first"}"# ;
0 commit comments