hexser 0.4.7

Zero-boilerplate hexagonal architecture with graph-based introspection
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
//! MCP server adapter using stdio transport.
//!
//! Implements the McpServer port using standard input/output for JSON-RPC
//! communication. Reads line-delimited JSON requests from stdin and writes
//! JSON-RPC responses to stdout. Integrates with ProjectRegistry for
//! multi-project architecture data serving.
//!
//! Revision History
//! - 2025-10-10T20:16:00Z @AI: Add Default impl and fix clippy warnings (needless borrows in cargo args).
//! - 2025-10-10T19:48:00Z @AI: Implement hexser/refresh method for triggering recompilation and clearing inventory cache.
//! - 2025-10-10T18:37:00Z @AI: Replace single graph with ProjectRegistry for multi-project support.
//! - 2025-10-08T23:35:00Z @AI: Initial MCP stdio adapter implementation.

/// MCP server implementation using stdio transport.
///
/// Processes MCP requests via JSON-RPC over standard input/output.
/// Uses ProjectRegistry to provide architecture context for multiple projects.
/// Each line on stdin should be a complete JSON-RPC request.
pub struct McpStdioServer {
  /// Registry managing multiple project configurations
  registry: crate::domain::mcp::ProjectRegistry,
}

impl McpStdioServer {
  /// Creates a new MCP stdio server with current HexGraph as single project.
  ///
  /// Provides backward compatibility by wrapping current graph in registry.
  ///
  /// # Returns
  ///
  /// New McpStdioServer instance with single "hexser" project
  pub fn new() -> Self {
    McpStdioServer {
      registry: crate::domain::mcp::ProjectRegistry::from_current_graph(),
    }
  }

  /// Creates a new MCP stdio server with a specific project registry.
  ///
  /// # Arguments
  ///
  /// * `registry` - ProjectRegistry containing projects to serve
  ///
  /// # Returns
  ///
  /// New McpStdioServer instance
  pub fn with_registry(registry: crate::domain::mcp::ProjectRegistry) -> Self {
    McpStdioServer { registry }
  }

  /// Creates a new MCP stdio server with a specific graph (backward compatibility).
  ///
  /// # Arguments
  ///
  /// * `graph` - Arc-wrapped HexGraph to use
  ///
  /// # Returns
  ///
  /// New McpStdioServer instance
  #[deprecated(since = "0.4.7", note = "Use with_registry instead")]
  pub fn with_graph(graph: std::sync::Arc<crate::graph::hex_graph::HexGraph>) -> Self {
    let mut registry = crate::domain::mcp::ProjectRegistry::new();
    let config = crate::domain::mcp::ProjectConfig::new(
      std::string::String::from("hexser"),
      std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
      graph,
    );
    registry.register(config);
    McpStdioServer { registry }
  }

  /// Parses project name from URI.
  ///
  /// Supports both legacy flat URIs (hexser://context) and new project-scoped
  /// URIs (hexser://project_name/context).
  ///
  /// # Arguments
  ///
  /// * `uri` - Resource URI to parse
  ///
  /// # Returns
  ///
  /// Tuple of (project_name, resource_type) or None if invalid
  fn parse_uri(uri: &str) -> std::option::Option<(std::string::String, std::string::String)> {
    if !uri.starts_with("hexser://") {
      return std::option::Option::None;
    }

    let path = &uri[9..]; // Remove "hexser://" prefix

    if path.is_empty() {
      return std::option::Option::None;
    }

    if path.contains('/') {
      // New format: hexser://project/resource
      let parts: std::vec::Vec<&str> = path.splitn(2, '/').collect();
      if parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() {
        return std::option::Option::Some((
          std::string::String::from(parts[0]),
          std::string::String::from(parts[1]),
        ));
      }
    } else {
      // Legacy format: hexser://resource (assumes "hexser" project)
      return std::option::Option::Some((
        std::string::String::from("hexser"),
        std::string::String::from(path),
      ));
    }

    std::option::Option::None
  }

  /// Runs the MCP server loop, reading from stdin and writing to stdout.
  ///
  /// Reads line-delimited JSON-RPC requests from stdin, processes each
  /// request, and writes responses to stdout. Exits on EOF or IO error.
  ///
  /// # Returns
  ///
  /// Result indicating success or IO error
  pub fn run(&self) -> crate::HexResult<()> {
    let stdin = std::io::stdin();
    let mut stdout = std::io::stdout();

    for line_result in stdin.lines() {
      let line = match line_result {
        std::result::Result::Ok(l) => l,
        std::result::Result::Err(e) => {
          return std::result::Result::Err(crate::Hexserror::adapter(
            "E_MCP_STDIN",
            &format!("Failed to read from stdin: {}", e),
          ));
        }
      };

      if line.trim().is_empty() {
        continue;
      }

      let request: crate::domain::mcp::JsonRpcRequest = match serde_json::from_str(&line) {
        std::result::Result::Ok(req) => req,
        std::result::Result::Err(e) => {
          let error_response = crate::domain::mcp::JsonRpcResponse::error(
            serde_json::Value::Null,
            crate::domain::mcp::JsonRpcError::parse_error(format!("Invalid JSON: {}", e)),
          );
          self.write_response(&mut stdout, &error_response)?;
          continue;
        }
      };

      let response = <Self as crate::ports::mcp_server::McpServer>::handle_request(self, request);
      self.write_response(&mut stdout, &response)?;
    }

    std::result::Result::Ok(())
  }

  fn write_response(
    &self,
    stdout: &mut std::io::Stdout,
    response: &crate::domain::mcp::JsonRpcResponse,
  ) -> crate::HexResult<()> {
    let json = match serde_json::to_string(response) {
      std::result::Result::Ok(j) => j,
      std::result::Result::Err(e) => {
        return std::result::Result::Err(crate::Hexserror::adapter(
          "E_MCP_SERIALIZE",
          &format!("Failed to serialize response: {}", e),
        ));
      }
    };

    use std::io::Write;
    if let std::result::Result::Err(e) = writeln!(stdout, "{}", json) {
      return std::result::Result::Err(crate::Hexserror::adapter(
        "E_MCP_STDOUT",
        &format!("Failed to write to stdout: {}", e),
      ));
    }

    if let std::result::Result::Err(e) = stdout.flush() {
      return std::result::Result::Err(crate::Hexserror::adapter(
        "E_MCP_FLUSH",
        &format!("Failed to flush stdout: {}", e),
      ));
    }

    std::result::Result::Ok(())
  }
}

impl std::default::Default for McpStdioServer {
  fn default() -> Self {
    Self::new()
  }
}

impl crate::ports::mcp_server::McpServer for McpStdioServer {
  fn initialize(
    &self,
    _request: crate::domain::mcp::InitializeRequest,
  ) -> crate::HexResult<crate::domain::mcp::InitializeResult> {
    std::result::Result::Ok(crate::domain::mcp::InitializeResult::hexser_default())
  }

  fn list_resources(&self) -> crate::HexResult<crate::domain::mcp::ResourceList> {
    let mut resources = std::vec::Vec::new();

    for (project_name, _config) in self.registry.iter() {
      // Add context resource for this project
      resources.push(crate::domain::mcp::Resource {
        uri: std::format!("hexser://{}/context", project_name),
        name: std::format!("{} Architecture Context", project_name),
        description: std::option::Option::Some(std::format!(
          "Machine-readable architecture context for {} project",
          project_name
        )),
        mime_type: std::option::Option::Some(std::string::String::from("application/json")),
      });

      // Add pack resource for this project
      resources.push(crate::domain::mcp::Resource {
        uri: std::format!("hexser://{}/pack", project_name),
        name: std::format!("{} Agent Pack", project_name),
        description: std::option::Option::Some(std::format!(
          "Comprehensive agent pack (architecture + guidelines + docs) for {} project",
          project_name
        )),
        mime_type: std::option::Option::Some(std::string::String::from("application/json")),
      });
    }

    std::result::Result::Ok(crate::domain::mcp::ResourceList { resources })
  }

  fn read_resource(&self, uri: &str) -> crate::HexResult<crate::domain::mcp::ResourceContent> {
    let (project_name, resource_type) = Self::parse_uri(uri).ok_or_else(|| {
      crate::Hexserror::adapter("E_MCP_INVALID_URI", &format!("Invalid URI format: {}", uri))
    })?;

    let project = self.registry.get(&project_name).ok_or_else(|| {
      crate::Hexserror::adapter(
        "E_MCP_PROJECT_NOT_FOUND",
        &format!("Project not found: {}", project_name),
      )
    })?;

    match resource_type.as_str() {
      "context" => {
        let builder = crate::ai::ContextBuilder::new(std::sync::Arc::as_ref(&project.graph));
        let context = builder.build()?;
        let json = match context.to_json() {
          std::result::Result::Ok(j) => j,
          std::result::Result::Err(e) => {
            return std::result::Result::Err(crate::Hexserror::adapter(
              "E_MCP_CONTEXT_SERIALIZE",
              &e,
            ));
          }
        };
        std::result::Result::Ok(crate::domain::mcp::ResourceContent::text(
          std::string::String::from(uri),
          json,
          std::option::Option::Some(std::string::String::from("application/json")),
        ))
      }
      "pack" => {
        let pack =
          crate::ai::AgentPack::from_graph_with_defaults(std::sync::Arc::as_ref(&project.graph))?;
        let json = match pack.to_json() {
          std::result::Result::Ok(j) => j,
          std::result::Result::Err(e) => {
            return std::result::Result::Err(crate::Hexserror::adapter("E_MCP_PACK_SERIALIZE", &e));
          }
        };
        std::result::Result::Ok(crate::domain::mcp::ResourceContent::text(
          std::string::String::from(uri),
          json,
          std::option::Option::Some(std::string::String::from("application/json")),
        ))
      }
      _ => std::result::Result::Err(crate::Hexserror::adapter(
        "E_MCP_RESOURCE_NOT_FOUND",
        &format!("Unknown resource type: {}", resource_type),
      )),
    }
  }

  fn refresh_project(
    &mut self,
    request: crate::domain::mcp::RefreshRequest,
  ) -> crate::HexResult<crate::domain::mcp::RefreshResult> {
    let project = self.registry.get(&request.project).ok_or_else(|| {
      crate::Hexserror::adapter(
        "E_MCP_PROJECT_NOT_FOUND",
        &format!("Project not found: {}", request.project),
      )
    })?;

    let output = std::process::Command::new("cargo")
      .args(["build", "-p", &request.project, "--features", "macros"])
      .current_dir(&project.root_path)
      .output()
      .map_err(|e| {
        crate::Hexserror::adapter(
          "E_MCP_COMPILE",
          &format!("Failed to execute cargo build: {}", e),
        )
      })?;

    if !output.status.success() {
      let error_msg = std::string::String::from_utf8_lossy(&output.stderr).to_string();
      return std::result::Result::Ok(crate::domain::mcp::RefreshResult::compilation_error(
        error_msg,
      ));
    }

    std::result::Result::Ok(crate::domain::mcp::RefreshResult::restart_required())
  }

  fn handle_request(
    &self,
    request: crate::domain::mcp::JsonRpcRequest,
  ) -> crate::domain::mcp::JsonRpcResponse {
    let id = request.id.clone();

    match request.method.as_str() {
      "initialize" => {
        let init_request: crate::domain::mcp::InitializeRequest = match request.params {
          Some(p) => match serde_json::from_value(p) {
            std::result::Result::Ok(r) => r,
            std::result::Result::Err(e) => {
              return crate::domain::mcp::JsonRpcResponse::error(
                id,
                crate::domain::mcp::JsonRpcError::invalid_request(format!(
                  "Invalid initialize params: {}",
                  e
                )),
              );
            }
          },
          None => {
            return crate::domain::mcp::JsonRpcResponse::error(
              id,
              crate::domain::mcp::JsonRpcError::invalid_request(String::from(
                "Missing initialize params",
              )),
            );
          }
        };

        match self.initialize(init_request) {
          std::result::Result::Ok(result) => {
            let result_value = match serde_json::to_value(result) {
              std::result::Result::Ok(v) => v,
              std::result::Result::Err(e) => {
                return crate::domain::mcp::JsonRpcResponse::error(
                  id,
                  crate::domain::mcp::JsonRpcError::internal_error(format!(
                    "Serialization error: {}",
                    e
                  )),
                );
              }
            };
            crate::domain::mcp::JsonRpcResponse::success(id, result_value)
          }
          std::result::Result::Err(e) => crate::domain::mcp::JsonRpcResponse::error(
            id,
            crate::domain::mcp::JsonRpcError::internal_error(format!("{}", e)),
          ),
        }
      }
      "resources/list" => match self.list_resources() {
        std::result::Result::Ok(list) => {
          let list_value = match serde_json::to_value(list) {
            std::result::Result::Ok(v) => v,
            std::result::Result::Err(e) => {
              return crate::domain::mcp::JsonRpcResponse::error(
                id,
                crate::domain::mcp::JsonRpcError::internal_error(format!(
                  "Serialization error: {}",
                  e
                )),
              );
            }
          };
          crate::domain::mcp::JsonRpcResponse::success(id, list_value)
        }
        std::result::Result::Err(e) => crate::domain::mcp::JsonRpcResponse::error(
          id,
          crate::domain::mcp::JsonRpcError::internal_error(format!("{}", e)),
        ),
      },
      "resources/read" => {
        let uri: String = match request.params {
          Some(p) => match p.get("uri") {
            Some(u) => match u.as_str() {
              Some(s) => String::from(s),
              None => {
                return crate::domain::mcp::JsonRpcResponse::error(
                  id,
                  crate::domain::mcp::JsonRpcError::invalid_request(String::from(
                    "URI must be a string",
                  )),
                );
              }
            },
            None => {
              return crate::domain::mcp::JsonRpcResponse::error(
                id,
                crate::domain::mcp::JsonRpcError::invalid_request(String::from(
                  "Missing uri parameter",
                )),
              );
            }
          },
          None => {
            return crate::domain::mcp::JsonRpcResponse::error(
              id,
              crate::domain::mcp::JsonRpcError::invalid_request(String::from("Missing params")),
            );
          }
        };

        match self.read_resource(&uri) {
          std::result::Result::Ok(content) => {
            let content_value = match serde_json::to_value(content) {
              std::result::Result::Ok(v) => v,
              std::result::Result::Err(e) => {
                return crate::domain::mcp::JsonRpcResponse::error(
                  id,
                  crate::domain::mcp::JsonRpcError::internal_error(format!(
                    "Serialization error: {}",
                    e
                  )),
                );
              }
            };
            crate::domain::mcp::JsonRpcResponse::success(id, content_value)
          }
          std::result::Result::Err(e) => crate::domain::mcp::JsonRpcResponse::error(
            id,
            crate::domain::mcp::JsonRpcError::internal_error(format!("{}", e)),
          ),
        }
      }
      "hexser/refresh" => {
        let refresh_request: crate::domain::mcp::RefreshRequest = match request.params {
          Some(p) => match serde_json::from_value(p) {
            std::result::Result::Ok(r) => r,
            std::result::Result::Err(e) => {
              return crate::domain::mcp::JsonRpcResponse::error(
                id,
                crate::domain::mcp::JsonRpcError::invalid_request(format!(
                  "Invalid refresh params: {}",
                  e
                )),
              );
            }
          },
          None => {
            return crate::domain::mcp::JsonRpcResponse::error(
              id,
              crate::domain::mcp::JsonRpcError::invalid_request(String::from(
                "Missing refresh params",
              )),
            );
          }
        };

        let project = match self.registry.get(&refresh_request.project) {
          Some(p) => p,
          None => {
            let error_result = crate::domain::mcp::RefreshResult::compilation_error(format!(
              "Project not found: {}",
              refresh_request.project
            ));
            let result_value = match serde_json::to_value(error_result) {
              std::result::Result::Ok(v) => v,
              std::result::Result::Err(e) => {
                return crate::domain::mcp::JsonRpcResponse::error(
                  id,
                  crate::domain::mcp::JsonRpcError::internal_error(format!(
                    "Serialization error: {}",
                    e
                  )),
                );
              }
            };
            return crate::domain::mcp::JsonRpcResponse::success(id, result_value);
          }
        };

        let output = match std::process::Command::new("cargo")
          .args([
            "build",
            "-p",
            &refresh_request.project,
            "--features",
            "macros",
          ])
          .current_dir(&project.root_path)
          .output()
        {
          std::result::Result::Ok(o) => o,
          std::result::Result::Err(e) => {
            let error_result = crate::domain::mcp::RefreshResult::compilation_error(format!(
              "Failed to execute cargo build: {}",
              e
            ));
            let result_value = match serde_json::to_value(error_result) {
              std::result::Result::Ok(v) => v,
              std::result::Result::Err(e) => {
                return crate::domain::mcp::JsonRpcResponse::error(
                  id,
                  crate::domain::mcp::JsonRpcError::internal_error(format!(
                    "Serialization error: {}",
                    e
                  )),
                );
              }
            };
            return crate::domain::mcp::JsonRpcResponse::success(id, result_value);
          }
        };

        let result = if !output.status.success() {
          let error_msg = std::string::String::from_utf8_lossy(&output.stderr).to_string();
          crate::domain::mcp::RefreshResult::compilation_error(error_msg)
        } else {
          crate::domain::mcp::RefreshResult::restart_required()
        };

        let result_value = match serde_json::to_value(result) {
          std::result::Result::Ok(v) => v,
          std::result::Result::Err(e) => {
            return crate::domain::mcp::JsonRpcResponse::error(
              id,
              crate::domain::mcp::JsonRpcError::internal_error(format!(
                "Serialization error: {}",
                e
              )),
            );
          }
        };
        crate::domain::mcp::JsonRpcResponse::success(id, result_value)
      }
      _ => crate::domain::mcp::JsonRpcResponse::error(
        id,
        crate::domain::mcp::JsonRpcError::method_not_found(request.method),
      ),
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::ports::mcp_server::McpServer;

  #[test]
  fn test_mcp_server_initialization() {
    let server = McpStdioServer::new();
    let request = crate::domain::mcp::InitializeRequest {
      protocol_version: String::from("2024-11-05"),
      capabilities: None,
      client_info: None,
    };

    let result = server.initialize(request);
    std::assert!(result.is_ok());
  }

  #[test]
  fn test_list_resources() {
    // Test: Validates resource listing returns project-scoped URIs
    // Justification: Core functionality for resource discovery
    let server = McpStdioServer::new();
    let list = server.list_resources().unwrap();

    std::assert_eq!(list.resources.len(), 2);
    std::assert_eq!(list.resources[0].uri, "hexser://hexser/context");
    std::assert_eq!(list.resources[1].uri, "hexser://hexser/pack");
  }

  #[test]
  fn test_parse_uri_legacy_format() {
    // Test: Validates backward compatibility with legacy URI format
    // Justification: Ensures existing integrations continue to work
    let result = McpStdioServer::parse_uri("hexser://context");
    std::assert!(result.is_some());
    let (project, resource) = result.unwrap();
    std::assert_eq!(project, "hexser");
    std::assert_eq!(resource, "context");
  }

  #[test]
  fn test_parse_uri_project_scoped_format() {
    // Test: Validates new project-scoped URI format
    // Justification: Core functionality for multi-project support
    let result = McpStdioServer::parse_uri("hexser://myproject/pack");
    std::assert!(result.is_some());
    let (project, resource) = result.unwrap();
    std::assert_eq!(project, "myproject");
    std::assert_eq!(resource, "pack");
  }

  #[test]
  fn test_parse_uri_invalid() {
    // Test: Validates invalid URIs are rejected
    // Justification: Error handling verification
    std::assert!(McpStdioServer::parse_uri("invalid://uri").is_none());
    std::assert!(McpStdioServer::parse_uri("hexser://").is_none());
  }

  #[test]
  fn test_multi_project_registry() {
    // Test: Validates multiple projects can be registered and served
    // Justification: Core multi-project functionality
    let mut registry = crate::domain::mcp::ProjectRegistry::new();
    let graph1 = crate::graph::builder::GraphBuilder::new().build();
    let graph2 = crate::graph::builder::GraphBuilder::new().build();

    registry.register(crate::domain::mcp::ProjectConfig::new(
      std::string::String::from("project1"),
      std::path::PathBuf::from("/path1"),
      std::sync::Arc::new(graph1),
    ));
    registry.register(crate::domain::mcp::ProjectConfig::new(
      std::string::String::from("project2"),
      std::path::PathBuf::from("/path2"),
      std::sync::Arc::new(graph2),
    ));

    let server = McpStdioServer::with_registry(registry);
    let list = server.list_resources().unwrap();

    std::assert_eq!(list.resources.len(), 4);
    std::assert!(
      list
        .resources
        .iter()
        .any(|r| r.uri == "hexser://project1/context")
    );
    std::assert!(
      list
        .resources
        .iter()
        .any(|r| r.uri == "hexser://project1/pack")
    );
    std::assert!(
      list
        .resources
        .iter()
        .any(|r| r.uri == "hexser://project2/context")
    );
    std::assert!(
      list
        .resources
        .iter()
        .any(|r| r.uri == "hexser://project2/pack")
    );
  }

  #[test]
  fn test_read_resource_legacy_uri() {
    // Test: Validates backward compatibility for reading resources
    // Justification: Ensures existing code continues to work
    let server = McpStdioServer::new();
    let result = server.read_resource("hexser://context");
    std::assert!(result.is_ok());
  }

  #[test]
  fn test_read_resource_project_not_found() {
    // Test: Validates error when project doesn't exist
    // Justification: Error handling verification
    let server = McpStdioServer::new();
    let result = server.read_resource("hexser://nonexistent/context");
    std::assert!(result.is_err());
  }

  #[test]
  fn test_read_resource_invalid_resource_type() {
    // Test: Validates error for unknown resource types
    // Justification: Error handling verification
    let server = McpStdioServer::new();
    let result = server.read_resource("hexser://hexser/unknown");
    std::assert!(result.is_err());
  }

  #[test]
  fn test_handle_initialize_request() {
    let server = McpStdioServer::new();
    let request = crate::domain::mcp::JsonRpcRequest::new(
      serde_json::Value::Number(serde_json::Number::from(1)),
      String::from("initialize"),
      Some(serde_json::json!({"protocolVersion": "2024-11-05"})),
    );

    let response = server.handle_request(request);
    std::assert!(response.result.is_some());
    std::assert!(response.error.is_none());
  }

  #[test]
  fn test_handle_unknown_method() {
    let server = McpStdioServer::new();
    let request = crate::domain::mcp::JsonRpcRequest::new(
      serde_json::Value::Number(serde_json::Number::from(1)),
      String::from("unknown/method"),
      None,
    );

    let response = server.handle_request(request);
    std::assert!(response.result.is_none());
    std::assert!(response.error.is_some());
    std::assert_eq!(response.error.unwrap().code, -32601);
  }

  #[test]
  fn test_handle_refresh_project_not_found() {
    // Test: Validates refresh returns error for nonexistent project
    // Justification: Error handling verification for refresh endpoint
    let server = McpStdioServer::new();
    let request = crate::domain::mcp::JsonRpcRequest::new(
      serde_json::Value::Number(serde_json::Number::from(1)),
      String::from("hexser/refresh"),
      Some(serde_json::json!({"project": "nonexistent"})),
    );

    let response = server.handle_request(request);
    std::assert!(response.result.is_some());
    std::assert!(response.error.is_none());

    let result: crate::domain::mcp::RefreshResult =
      serde_json::from_value(response.result.unwrap()).unwrap();
    std::assert_eq!(result.status, "error");
    std::assert!(!result.compiled);
  }

  #[test]
  fn test_handle_refresh_missing_params() {
    // Test: Validates refresh returns error when params missing
    // Justification: Validates parameter validation
    let server = McpStdioServer::new();
    let request = crate::domain::mcp::JsonRpcRequest::new(
      serde_json::Value::Number(serde_json::Number::from(1)),
      String::from("hexser/refresh"),
      None,
    );

    let response = server.handle_request(request);
    std::assert!(response.result.is_none());
    std::assert!(response.error.is_some());
    std::assert_eq!(response.error.unwrap().code, -32600);
  }
}