nika 0.20.0

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! rmcp Adapter Layer
//!
//! This module wraps Anthropic's official rmcp SDK to provide Nika's MCP client interface.
//! It handles the translation between Nika's API and rmcp's Service/Transport abstractions.
//!
//! ## Architecture
//!
//! ```text
//! McpClient (Nika API)
//!//!     ├── Mock Mode ──► Direct mock responses (testing)
//!//!     └── Real Mode ──► RmcpClientAdapter
//!//!                           └── rmcp::Service<ClientHandler>
//!//!                                   └── TokioChildProcess transport
//! ```
//!
//! ## Internal Usage
//!
//! This adapter is internal to the MCP module and should be accessed via `McpClient`.
//!
//! ```rust,ignore
//! // Users should use McpClient, not RmcpClientAdapter directly
//! use nika::mcp::{McpClient, McpConfig};
//!
//! let config = McpConfig::new("novanet", "cargo")
//!     .with_args(["run", "--manifest-path", "path/to/Cargo.toml"]);
//!
//! let client = McpClient::new(config)?;
//! client.connect().await?;
//! ```

use std::process::Stdio;

use parking_lot::Mutex;
use rmcp::model::{CallToolRequestParams, ListToolsResult};
use rmcp::service::{RoleClient, RunningService};
use rmcp::transport::TokioChildProcess;
use rmcp::ServiceExt;
use serde_json::Value;
use tokio::process::Command;
use tokio::sync::Mutex as AsyncMutex;
use tokio::time::timeout;

use crate::error::{NikaError, Result};
use crate::mcp::retry::{retry_mcp_call, McpRetryConfig};
use crate::mcp::types::{
    ContentBlock, McpConfig, McpErrorCode, ResourceContent, ToolCallResult, ToolDefinition,
};
use crate::util::{CONNECT_TIMEOUT, MCP_CALL_TIMEOUT};

/// Extract JSON-RPC error code from error message if present.
///
/// Attempts to find standard JSON-RPC error codes (-32xxx) in error strings.
fn extract_error_code(error: &str) -> Option<McpErrorCode> {
    // Look for patterns like "code: -32602" or "(-32602)" or "error -32602"
    let patterns = [r"code:\s*(-?\d+)", r"\((-\d+)\)", r"error\s+(-\d+)"];

    for pattern in patterns {
        if let Ok(re) = regex::Regex::new(pattern) {
            if let Some(caps) = re.captures(error) {
                if let Some(m) = caps.get(1) {
                    if let Ok(code) = m.as_str().parse::<i32>() {
                        // Only return JSON-RPC error codes
                        if (-32799..=-32000).contains(&code) || (-32700..=-32600).contains(&code) {
                            return Some(McpErrorCode::from_code(code));
                        }
                    }
                }
            }
        }
    }
    None
}

/// Running rmcp service type alias
/// RunningService<Role, Handler> where Handler implements Service<Role>
type RmcpService = RunningService<RoleClient, ()>;

/// rmcp Client Adapter (internal)
///
/// Wraps rmcp's Service to provide Nika's MCP client interface.
/// Handles connection lifecycle, tool calls, and resource reads.
/// Users should access MCP via `McpClient`, not this type directly.
pub(crate) struct RmcpClientAdapter {
    /// Server name (from config)
    name: String,

    /// Server configuration
    config: McpConfig,

    /// Running rmcp service (None when disconnected)
    service: AsyncMutex<Option<RmcpService>>,

    /// Protocol version reported by server
    server_version: Mutex<Option<String>>,

    /// Cached tool definitions (populated after list_tools() call)
    /// Used by get_cached_tools() for synchronous access in rig integration
    cached_tools: Mutex<Vec<ToolDefinition>>,
}

impl std::fmt::Debug for RmcpClientAdapter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RmcpClientAdapter")
            .field("name", &self.name)
            .field("config", &self.config)
            .field("connected", &self.is_connected_sync())
            .finish()
    }
}

impl RmcpClientAdapter {
    /// Create a new rmcp client adapter from configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - MCP server configuration
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = McpConfig::new("novanet", "cargo")
    ///     .with_args(["run", "--manifest-path", "path/to/Cargo.toml"]);
    /// let adapter = RmcpClientAdapter::new(config);
    /// ```
    pub fn new(config: McpConfig) -> Self {
        Self {
            name: config.name.clone(),
            config,
            service: AsyncMutex::new(None),
            server_version: Mutex::new(None),
            cached_tools: Mutex::new(Vec::new()),
        }
    }

    /// Get the server name.
    #[allow(dead_code)] // Used in tests
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Check if connected synchronously (non-blocking).
    ///
    /// Uses try_lock to avoid blocking. Returns false if:
    /// - The lock is held by another task
    /// - No service connection exists
    ///
    /// For accurate state, prefer `is_connected()` async method.
    pub fn is_connected_sync(&self) -> bool {
        // Try to check without blocking - return false if lock is held
        self.service
            .try_lock()
            .map(|guard| guard.is_some())
            .unwrap_or(false)
    }

    /// Check if the client is connected to the server.
    pub async fn is_connected(&self) -> bool {
        self.service.lock().await.is_some()
    }

    /// Connect to the MCP server.
    ///
    /// Spawns the server process and establishes MCP communication.
    /// The rmcp SDK handles the initialize/initialized handshake.
    ///
    /// # Errors
    ///
    /// Returns `NikaError::McpStartError` if the server fails to start.
    pub async fn connect(&self) -> Result<()> {
        let mut guard = self.service.lock().await;

        if guard.is_some() {
            return Ok(()); // Already connected
        }

        // Build command from config
        let mut cmd = Command::new(&self.config.command);
        cmd.args(&self.config.args);

        // Suppress stderr to avoid polluting TUI output
        // MCP communication happens over stdin/stdout, stderr is only for logging
        cmd.stderr(Stdio::null());

        // Suppress logging in child process to avoid TUI pollution
        // This must be set BEFORE adding config env vars to allow override if needed
        cmd.env("RUST_LOG", "off");

        // Add environment variables from workflow config
        for (key, value) in &self.config.env {
            cmd.env(key, value);
        }

        // Create transport
        let transport = TokioChildProcess::new(cmd).map_err(|e| NikaError::McpStartError {
            name: self.name.clone(),
            reason: format!("Failed to create transport: {}", e),
        })?;

        // Connect to server using rmcp's serve pattern
        // The () implements ClientHandler with default behavior
        // Wrap with timeout to prevent hanging on unresponsive MCP servers
        let service = timeout(CONNECT_TIMEOUT, ().serve(transport))
            .await
            .map_err(|_| NikaError::McpTimeout {
                name: self.name.clone(),
                operation: "connect".to_string(),
                timeout_secs: CONNECT_TIMEOUT.as_secs(),
            })?
            .map_err(|e| NikaError::McpStartError {
                name: self.name.clone(),
                reason: format!("Failed to connect: {}", e),
            })?;

        // Store server info
        if let Some(info) = service.peer_info() {
            *self.server_version.lock() = Some(info.protocol_version.to_string());
        }

        *guard = Some(service);
        Ok(())
    }

    /// Disconnect from the MCP server.
    ///
    /// Gracefully closes the connection.
    pub async fn disconnect(&self) -> Result<()> {
        let mut guard = self.service.lock().await;

        if let Some(service) = guard.take() {
            // Graceful shutdown
            let _ = service.cancel().await;
        }

        *self.server_version.lock() = None;
        Ok(())
    }

    /// Reconnect to the MCP server.
    ///
    /// Disconnects if connected, then establishes a new connection.
    pub async fn reconnect(&self) -> Result<()> {
        tracing::info!(
            mcp_server = %self.name,
            "Attempting MCP server reconnection"
        );

        self.disconnect().await?;
        self.connect().await
    }

    /// Call an MCP tool with the given parameters.
    ///
    /// # Arguments
    ///
    /// * `name` - Tool name (e.g., "novanet_generate")
    /// * `params` - Tool parameters as JSON value
    ///
    /// # Errors
    ///
    /// Returns `NikaError::McpNotConnected` if not connected.
    /// Returns `NikaError::McpToolError` if the tool call fails.
    pub async fn call_tool(&self, name: &str, params: Value) -> Result<ToolCallResult> {
        // FIX: Clone the Peer and release the lock immediately to prevent lock contention
        // during the timeout period (60s). Without this, concurrent call_tool requests
        // would block waiting for the mutex while one request times out.
        let peer = {
            let guard = self.service.lock().await;
            let service = guard.as_ref().ok_or_else(|| NikaError::McpNotConnected {
                name: self.name.clone(),
            })?;
            // Clone the Peer (Peer implements Clone via derive)
            // RunningService derefs to Peer, and Peer is Clone
            use std::ops::Deref;
            service.deref().clone()
        }; // Lock is released here

        // Convert params to object format expected by rmcp
        let arguments = params.as_object().cloned();

        let request = CallToolRequestParams {
            meta: None,
            name: name.to_string().into(),
            arguments,
            task: None,
        };

        let result = timeout(MCP_CALL_TIMEOUT, peer.call_tool(request))
            .await
            .map_err(|_| NikaError::McpTimeout {
                name: self.name.clone(),
                operation: "call_tool".to_string(),
                timeout_secs: MCP_CALL_TIMEOUT.as_secs(),
            })?
            .map_err(|e| {
                let error_str = e.to_string();
                NikaError::McpToolError {
                    tool: name.to_string(),
                    reason: error_str.clone(),
                    error_code: extract_error_code(&error_str),
                }
            })?;

        // Convert rmcp result to Nika's ToolCallResult
        let content: Vec<ContentBlock> = result
            .content
            .iter()
            .filter_map(|c| {
                // Extract text content
                c.as_text().map(|t| ContentBlock::text(t.text.clone()))
            })
            .collect();

        Ok(ToolCallResult {
            content,
            is_error: result.is_error.unwrap_or(false),
        })
    }

    /// Call a tool on the MCP server with automatic retry on transient failures.
    ///
    /// Uses exponential backoff with jitter for retries. Only retryable errors
    /// (timeouts, connection issues) trigger retries. Validation errors and
    /// resource-not-found errors fail immediately.
    ///
    /// # Arguments
    ///
    /// * `name` - Tool name (e.g., "novanet_generate")
    /// * `params` - Tool parameters as JSON value
    /// * `retry_config` - Optional retry configuration (uses defaults if None)
    ///
    /// # Errors
    ///
    /// Returns `NikaError::McpNotConnected` if not connected.
    /// Returns `NikaError::McpToolError` if the tool call fails after all retries.
    #[allow(dead_code)] // Available for future use in invoke: verb retry logic
    pub async fn call_tool_with_retry(
        &self,
        name: &str,
        params: Value,
        retry_config: Option<McpRetryConfig>,
    ) -> Result<ToolCallResult> {
        let config = retry_config.unwrap_or_default();
        let name_owned = name.to_string();
        let server_name = self.name.clone();

        tracing::debug!(
            mcp_server = %server_name,
            tool = %name_owned,
            max_retries = config.max_retries,
            "Calling MCP tool with retry"
        );

        retry_mcp_call(config, || {
            let params = params.clone();
            let name = name_owned.clone();
            async move { self.call_tool(&name, params).await }
        })
        .await
    }

    /// Read a resource from the MCP server.
    ///
    /// # Arguments
    ///
    /// * `uri` - Resource URI (e.g., "neo4j://entity/qr-code")
    ///
    /// # Errors
    ///
    /// Returns `NikaError::McpNotConnected` if not connected.
    /// Returns `NikaError::McpResourceNotFound` if the resource doesn't exist.
    pub async fn read_resource(&self, uri: &str) -> Result<ResourceContent> {
        // FIX: Clone the Peer and release the lock immediately to prevent lock contention
        let peer = {
            let guard = self.service.lock().await;
            let service = guard.as_ref().ok_or_else(|| NikaError::McpNotConnected {
                name: self.name.clone(),
            })?;
            use std::ops::Deref;
            service.deref().clone()
        }; // Lock is released here

        let request = rmcp::model::ReadResourceRequestParams {
            meta: None,
            uri: uri.into(),
        };

        let result = timeout(MCP_CALL_TIMEOUT, peer.read_resource(request))
            .await
            .map_err(|_| NikaError::McpTimeout {
                name: self.name.clone(),
                operation: "read_resource".to_string(),
                timeout_secs: MCP_CALL_TIMEOUT.as_secs(),
            })?
            .map_err(|e| {
                // Check for not found error
                let error_str = e.to_string().to_lowercase();
                if error_str.contains("not found") {
                    NikaError::McpResourceNotFound {
                        uri: uri.to_string(),
                    }
                } else {
                    let error_str = e.to_string();
                    NikaError::McpToolError {
                        tool: "resources/read".to_string(),
                        reason: error_str.clone(),
                        error_code: extract_error_code(&error_str),
                    }
                }
            })?;

        // Convert first resource content
        let resource = result
            .contents
            .first()
            .ok_or_else(|| NikaError::McpResourceNotFound {
                uri: uri.to_string(),
            })?;

        // Build ResourceContent from rmcp response
        // Serialize the resource content as JSON for simplicity
        let text = serde_json::to_string(resource).map_err(|e| NikaError::McpToolError {
            tool: "resources/read".to_string(),
            reason: format!("Failed to serialize resource: {}", e),
            error_code: None, // Serialization errors are internal
        })?;

        let content = ResourceContent::new(uri)
            .with_text(&text)
            .with_mime_type("application/json");

        Ok(content)
    }

    /// List all available tools from the MCP server.
    ///
    /// # Errors
    ///
    /// Returns `NikaError::McpNotConnected` if not connected.
    pub async fn list_tools(&self) -> Result<Vec<ToolDefinition>> {
        // FIX: Clone the Peer and release the lock immediately to prevent lock contention
        let peer = {
            let guard = self.service.lock().await;
            let service = guard.as_ref().ok_or_else(|| NikaError::McpNotConnected {
                name: self.name.clone(),
            })?;
            use std::ops::Deref;
            service.deref().clone()
        }; // Lock is released here

        let result: ListToolsResult =
            timeout(MCP_CALL_TIMEOUT, peer.list_tools(Default::default()))
                .await
                .map_err(|_| NikaError::McpTimeout {
                    name: self.name.clone(),
                    operation: "list_tools".to_string(),
                    timeout_secs: MCP_CALL_TIMEOUT.as_secs(),
                })?
                .map_err(|e| {
                    let error_str = e.to_string();
                    NikaError::McpToolError {
                        tool: "tools/list".to_string(),
                        reason: error_str.clone(),
                        error_code: extract_error_code(&error_str),
                    }
                })?;

        // Convert rmcp tools to Nika's ToolDefinition
        let tools: Vec<ToolDefinition> = result
            .tools
            .into_iter()
            .map(|t| {
                let mut tool = ToolDefinition::new(t.name.as_ref());
                if let Some(desc) = &t.description {
                    tool = tool.with_description(desc.as_ref());
                }
                // Convert Arc<Map> to Value and ensure "type": "object" for Claude API
                // Claude requires the root schema to have a "type" field
                let mut schema_map: serde_json::Map<String, serde_json::Value> =
                    (*t.input_schema).clone();
                // Ensure "type": "object" is present (required by Claude API)
                if !schema_map.contains_key("type") {
                    schema_map.insert("type".to_string(), serde_json::json!("object"));
                }
                tool = tool.with_input_schema(serde_json::Value::Object(schema_map));
                tool
            })
            .collect();

        // Cache tools for synchronous access via get_cached_tools()
        *self.cached_tools.lock() = tools.clone();

        Ok(tools)
    }

    /// Get cached tool definitions (synchronous access).
    ///
    /// Returns tools from the last `list_tools()` call, or empty vec if never called.
    /// This is used by rig integration which requires sync access to tool definitions.
    pub fn get_cached_tools(&self) -> Vec<ToolDefinition> {
        self.cached_tools.lock().clone()
    }
}

impl Drop for RmcpClientAdapter {
    fn drop(&mut self) {
        // Best-effort cleanup - rmcp handles process termination
        // The service will be dropped and cleaned up automatically
        tracing::debug!(
            mcp_server = %self.name,
            "RmcpClientAdapter dropped"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ═══════════════════════════════════════════════════════════════════════════
    // RmcpAdapter Construction Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_adapter_new() {
        let config = McpConfig::new("test-server", "echo");
        let adapter = RmcpClientAdapter::new(config);
        assert_eq!(adapter.name(), "test-server");
    }

    #[test]
    fn test_adapter_new_with_args_and_env() {
        let config = McpConfig::new("novanet", "cargo")
            .with_arg("run")
            .with_env("NEO4J_URI", "bolt://localhost:7687");

        let adapter = RmcpClientAdapter::new(config);
        assert_eq!(adapter.name(), "novanet");
    }

    #[test]
    fn test_adapter_debug_not_connected() {
        let config = McpConfig::new("test-server", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let debug_str = format!("{:?}", adapter);
        assert!(debug_str.contains("RmcpClientAdapter"));
        assert!(debug_str.contains("test-server"));
        assert!(debug_str.contains("connected"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Connection State Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_adapter_not_connected_by_default() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);
        assert!(!adapter.is_connected().await);
    }

    #[test]
    fn test_adapter_not_connected_sync() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);
        assert!(!adapter.is_connected_sync());
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Disconnect Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_disconnect_when_not_connected_is_ok() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let result = adapter.disconnect().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_disconnect_clears_server_version() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        // Manually set server version to test clearing
        *adapter.server_version.lock() = Some("1.0".to_string());
        assert_eq!(
            adapter.server_version.lock().as_ref().map(|s| s.as_str()),
            Some("1.0")
        );

        adapter.disconnect().await.ok();
        assert_eq!(adapter.server_version.lock().as_ref(), None);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Tool Call Error Tests (when not connected)
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_call_tool_when_not_connected_returns_error() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let result = adapter.call_tool("test_tool", serde_json::json!({})).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            NikaError::McpNotConnected { name } => assert_eq!(name, "test"),
            e => panic!("Expected McpNotConnected, got: {:?}", e),
        }
    }

    #[tokio::test]
    async fn test_call_tool_with_object_params() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let params = serde_json::json!({
            "entity": "qr-code",
            "locale": "fr-FR"
        });

        let result = adapter.call_tool("novanet_generate", params).await;

        // Should fail with McpNotConnected, not with param conversion error
        assert!(result.is_err());
        match result.unwrap_err() {
            NikaError::McpNotConnected { name } => assert_eq!(name, "test"),
            e => panic!("Expected McpNotConnected, got: {:?}", e),
        }
    }

    #[tokio::test]
    async fn test_call_tool_with_non_object_params() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        // Pass a string instead of object
        let params = serde_json::json!("not-an-object");

        let result = adapter.call_tool("test_tool", params).await;

        // Should still error with McpNotConnected (params are converted to None)
        assert!(result.is_err());
        match result.unwrap_err() {
            NikaError::McpNotConnected { name } => assert_eq!(name, "test"),
            e => panic!("Expected McpNotConnected, got: {:?}", e),
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Resource Read Error Tests (when not connected)
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_read_resource_when_not_connected_returns_error() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let result = adapter.read_resource("neo4j://entity/test").await;

        assert!(result.is_err());
        match result.unwrap_err() {
            NikaError::McpNotConnected { name } => assert_eq!(name, "test"),
            e => panic!("Expected McpNotConnected, got: {:?}", e),
        }
    }

    #[tokio::test]
    async fn test_read_resource_with_various_uris() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let uris = vec![
            "neo4j://entity/qr-code",
            "neo4j://page/landing",
            "neo4j://block/hero",
            "file:///path/to/file",
        ];

        for uri in uris {
            let result = adapter.read_resource(uri).await;
            assert!(result.is_err());
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // List Tools Error Tests (when not connected)
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_list_tools_when_not_connected_returns_error() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let result = adapter.list_tools().await;

        assert!(result.is_err());
        match result.unwrap_err() {
            NikaError::McpNotConnected { name } => assert_eq!(name, "test"),
            e => panic!("Expected McpNotConnected, got: {:?}", e),
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Cached Tools Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_get_cached_tools_returns_empty_initially() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let cached = adapter.get_cached_tools();
        assert!(cached.is_empty());
    }

    #[test]
    fn test_get_cached_tools_with_populated_cache() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        // Manually populate cache
        let tools = vec![
            ToolDefinition::new("novanet_generate"),
            ToolDefinition::new("novanet_traverse"),
        ];
        *adapter.cached_tools.lock() = tools.clone();

        let cached = adapter.get_cached_tools();
        assert_eq!(cached.len(), 2);
        assert_eq!(cached[0].name, "novanet_generate");
        assert_eq!(cached[1].name, "novanet_traverse");
    }

    #[test]
    fn test_cached_tools_independence() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        let tool1 = ToolDefinition::new("tool1");
        *adapter.cached_tools.lock() = vec![tool1];

        let cached1 = adapter.get_cached_tools();
        assert_eq!(cached1.len(), 1);

        // Modify cache again
        let tool2 = ToolDefinition::new("tool2");
        *adapter.cached_tools.lock() = vec![tool2];

        let cached2 = adapter.get_cached_tools();
        assert_eq!(cached2.len(), 1);
        assert_eq!(cached2[0].name, "tool2");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Drop Implementation Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_adapter_drop_does_not_panic() {
        let config = McpConfig::new("test", "echo");
        let adapter = RmcpClientAdapter::new(config);

        // This should not panic
        drop(adapter);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Error Code Extraction Tests (v0.5.3)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_extract_error_code_with_code_pattern() {
        let error = "JSON-RPC error code: -32602 - Invalid params";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::InvalidParams));
    }

    #[test]
    fn test_extract_error_code_with_parentheses_pattern() {
        let error = "Method not found (-32601)";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::MethodNotFound));
    }

    #[test]
    fn test_extract_error_code_with_error_word_pattern() {
        let error = "error -32700 in parser";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::ParseError));
    }

    #[test]
    fn test_extract_error_code_parse_error() {
        let error = "Parse error code: -32700";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::ParseError));
    }

    #[test]
    fn test_extract_error_code_invalid_request() {
        let error = "Invalid request (-32600)";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::InvalidRequest));
    }

    #[test]
    fn test_extract_error_code_internal_error() {
        let error = "code: -32603";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::InternalError));
    }

    #[test]
    fn test_extract_error_code_server_error() {
        let error = "Server error (-32050): Internal failure";
        let code = extract_error_code(error);
        assert!(matches!(code, Some(McpErrorCode::ServerError(-32050))));
    }

    #[test]
    fn test_extract_error_code_various_server_errors() {
        let test_cases = vec![
            ("error -32000", Some(McpErrorCode::ServerError(-32000))),
            ("code: -32050", Some(McpErrorCode::ServerError(-32050))),
            ("(-32099)", Some(McpErrorCode::ServerError(-32099))),
        ];

        for (error, expected) in test_cases {
            let code = extract_error_code(error);
            assert_eq!(code, expected, "Failed for error: {}", error);
        }
    }

    #[test]
    fn test_extract_error_code_no_code_present() {
        let error = "Connection refused";
        let code = extract_error_code(error);
        assert_eq!(code, None);
    }

    #[test]
    fn test_extract_error_code_non_jsonrpc_code() {
        let error = "HTTP error code: 404";
        let code = extract_error_code(error);
        assert_eq!(code, None); // 404 is not a JSON-RPC code
    }

    #[test]
    fn test_extract_error_code_negative_but_outside_range() {
        let error = "error code: -100";
        let code = extract_error_code(error);
        // -100 is outside JSON-RPC ranges, should be None
        assert_eq!(code, None);
    }

    #[test]
    fn test_extract_error_code_positive_numbers_ignored() {
        let error = "code: 500 or code: 400";
        let code = extract_error_code(error);
        // Positive codes are not JSON-RPC error codes
        assert_eq!(code, None);
    }

    #[test]
    fn test_extract_error_code_multiple_codes_uses_first() {
        let error = "code: -32602 and also code: -32601";
        let code = extract_error_code(error);
        // Should extract the first matching code
        assert_eq!(code, Some(McpErrorCode::InvalidParams));
    }

    #[test]
    fn test_extract_error_code_empty_string() {
        let error = "";
        let code = extract_error_code(error);
        assert_eq!(code, None);
    }

    #[test]
    fn test_extract_error_code_with_text_around_code() {
        let error = "Request failed: code: -32602 - invalid parameters supplied";
        let code = extract_error_code(error);
        assert_eq!(code, Some(McpErrorCode::InvalidParams));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Integration Tests (Configuration & Conversion)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_adapter_preserves_config_command() {
        let config = McpConfig::new("myserver", "python").with_args(["script.py", "--flag"]);

        let adapter = RmcpClientAdapter::new(config);
        assert_eq!(adapter.name(), "myserver");
    }

    #[test]
    fn test_adapter_with_complex_config() {
        let config = McpConfig::new("complex-server", "node")
            .with_arg("--require")
            .with_arg("dotenv/config")
            .with_arg("index.js")
            .with_env("LOG_LEVEL", "debug")
            .with_env("PORT", "3000");

        let adapter = RmcpClientAdapter::new(config);
        assert_eq!(adapter.name(), "complex-server");
    }

    #[test]
    fn test_adapter_name_accessor() {
        let config = McpConfig::new("my-test-server", "echo");
        let adapter = RmcpClientAdapter::new(config);

        assert_eq!(adapter.name(), "my-test-server");
    }
}