### Custom MCP Server Binary Configuration Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Example of how to specify a custom binary name for the MCP server within the 'args' of the Cargo command. ```json "args": ["run", "--features", "mcp", "--bin", "my-custom-mcp-server"] ``` -------------------------------- ### Start Hexser Web Server Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Starts a full HTTP REST API server on port 3000 using the RealWorld API example. This involves navigating to the example directory and executing the web_server binary with cargo. ```bash cd hexser/examples/realworld_api cargo run --bin web_server ``` ```bash cargo run --example realworld_api --bin web_server ``` -------------------------------- ### Bash: Running the Hexser Adapter Example Source: https://github.com/squillo/hexser/blob/main/hexser/tutorials/03-implementing-adapters/README.md This command demonstrates how to execute the runnable example provided in the hexser tutorial for implementing adapters. It assumes you are in the repository root and uses Cargo to build and run the specific example. ```bash # From repository root cargo run --example tutorial_03_adapters ``` -------------------------------- ### MCP Server Initialization Response Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md An example JSON response from the MCP server after receiving an 'initialize' command. This confirms the server is running and reports its protocol version, server information, and supported capabilities. The structure indicates a successful handshake. ```json {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","serverInfo":{"name":"hexser","version":"0.4.5"},"capabilities":{"resources":{}}}} ``` -------------------------------- ### Hexser Dependency Configuration Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Example of how to specify the Hexser dependency in a Cargo.toml file, including necessary features like 'mcp' and 'macros'. ```toml hexser = { version = "0.4.5", features = ["mcp", "macros"] } ``` -------------------------------- ### Logging into Crates.io Source: https://github.com/squillo/hexser/blob/main/PUBLISHING.md Authenticates your local Cargo installation with your crates.io account using an API token. This is a one-time setup step required before publishing. ```bash cargo login ``` -------------------------------- ### Run Hexser Example to Build Graph Source: https://github.com/squillo/hexser/blob/main/hexser/tutorials/05-graph-analysis/README.md Executes a Hexser example from the repository root to build and visualize the architecture graph. This is a quick way to see the graph output. ```bash # From the repository root cargo run --example tutorial_03_adapters ``` ```bash # Alternative example exercising the Application layer cargo run --example tutorial_04_application ``` -------------------------------- ### Simplify Cargo Arguments for Single Crate Projects Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Provides a simplified `args` configuration for Junie's MCP server setup when your project is a single crate and not part of a workspace. This removes the need to specify the package with `-p`. ```json "args": [ "run", "--features", "mcp", "--bin", "hex-mcp-server" ] ``` -------------------------------- ### Example API Usage: List Articles Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Demonstrates how to retrieve a list of articles using a GET request to the /api/articles endpoint. ```bash curl http://localhost:3000/api/articles ``` -------------------------------- ### Bash Command for Running Hexser Examples Source: https://github.com/squillo/hexser/blob/main/hexser/docs/ARCHITECTURE.md A bash command to run example applications provided within the Hexser project. This is useful for verifying example code and demonstrating real-world usage patterns. ```bash # Test examples cargo run --example simple_todo ``` -------------------------------- ### Example API Usage: Get Article by Slug Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Shows how to fetch a specific article using its slug via a GET request to /api/articles/{slug}. ```bash curl http://localhost:3000/api/articles/how-to-train-your-dragon ``` -------------------------------- ### Running Hexser Examples with Cargo Source: https://github.com/squillo/hexser/blob/main/hexser/README.md Provides the command to run examples included with the hex crate using Cargo. This is useful for users who want to see the hexagonal architecture patterns in action. ```bash cargo run --example simple_todo ``` -------------------------------- ### Bash Script for Hexser Project Setup and Testing Source: https://github.com/squillo/hexser/blob/main/hexser/docs/ARCHITECTURE.md Provides bash commands for setting up, building, and testing the Hexser project. It includes cloning the repository, building with all features, and running all tests to ensure project integrity. ```bash git clone https://github.com/squillo/hexser cd hexser cargo build --all-features cargo test --all-features ``` -------------------------------- ### Example JSON-RPC Initialize Request Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/mcp-tools.md An example of a JSON-RPC 2.0 request for initializing an MCP server connection. Includes protocol version, capabilities, and client information. ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "example-client", "version": "1.0.0" } } } ``` -------------------------------- ### Run RealWorld API Demonstration with Cargo Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md This command executes the RealWorld API example in demonstration mode, showcasing hexagonal architecture patterns, CQRS, and various workflows. It provides detailed logging of operations. ```bash cd hexser/examples/realworld_api cargo run --bin realworld_api ``` -------------------------------- ### Run Hexser Tests Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Executes all tests for the hexser project, covering domain logic, application handlers, and adapter implementations. This command should be run from the example's directory. ```bash cd hexser/examples/realworld_api cargo test ``` -------------------------------- ### Add Hexser Dependency to Cargo.toml Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/getting-started.md This snippet shows how to add the hexser crate as a dependency in your Cargo.toml file, including enabling the 'macros' feature. This is necessary to use the derive macros provided by hexser. ```toml [dependencies] hexser = { version = "0.1.0", features = ["macros"] } ``` -------------------------------- ### MCP Server Configuration - Multiple Projects Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md JSON configuration for the MCP server to manage multiple Hexser projects. It specifies commands, arguments, and working directories for each project. ```json { "mcpServers": { "project-a": { "command": "cargo", "args": ["run", "-p", "project-a", "--features", "mcp", "--bin", "hex-mcp-server"], "cwd": "/path/to/project-a" }, "project-b": { "command": "cargo", "args": ["run", "-p", "project-b", "--features", "mcp", "--bin", "hex-mcp-server"], "cwd": "/path/to/project-b" } } } ``` -------------------------------- ### Rust Hexagonal Component Definition with Hexser Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/getting-started.md This Rust code demonstrates the creation of a hexagonal architecture component using hexser. It defines a User entity, a UserRepository port (trait), and an InMemoryUserRepository adapter, utilizing hexser's derive macros for entity, domain, port, and adapter functionalities. ```rust use hexser::prelude::*; #[derive(Entity, HexDomain)] struct User { id: String, email: String, } // A port is a trait describing what the domain needs #[derive(HexPort)] trait UserRepository: Repository { fn find_by_email(&self, email: &str) -> HexResult>; } // An adapter implements one or more ports #[derive(HexAdapter)] struct InMemoryUserRepository { users: Vec, } impl Repository for InMemoryUserRepository { fn find_by_id(&self, id: &String) -> HexResult> { Ok(self.users.iter().find(|u| &u.id == id).cloned()) } } impl UserRepository for InMemoryUserRepository { fn find_by_email(&self, email: &str) -> HexResult> { Ok(self.users.iter().find(|u| u.email == email).cloned()) } } ``` -------------------------------- ### Configuring Sparse Protocol for Faster Indexing Source: https://github.com/squillo/hexser/blob/main/PUBLISHING.md Sets an environment variable to use the sparse protocol for interacting with crates.io, which can potentially speed up indexing times. ```bash export CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse ``` -------------------------------- ### Rust Doc Test Example Source: https://github.com/squillo/hexser/blob/main/hexser/docs/ARCHITECTURE.md Illustrates how to write documentation tests in Rust. Doc comments with code blocks enclosed in triple backticks (```rust) are compiled and run as tests. This ensures that examples in documentation are always up-to-date. ```rust /// Example usage /// /// ```rust /// use hexser::HexEntity; /// struct User { id: String } /// impl HexEntity for User { /// type Id = String; /// } /// ``` ``` -------------------------------- ### Example API Usage: Register User Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Demonstrates how to register a new user using the REST API. This involves a POST request to the /api/users endpoint with a JSON payload containing user credentials. ```bash curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{ "user": { "email": "jake@example.com", "username": "jake", "password": "password123" } }' ``` -------------------------------- ### Cargo Build Command for MCP Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Command to build a Rust project with the 'mcp' feature enabled, specifically for the hex-mcp-server binary. This is used for troubleshooting MCP server startup issues. ```bash cargo build --features mcp --bin hex-mcp-server ``` -------------------------------- ### Example API Usage: Login Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Shows how to log in a user via the REST API. This is a POST request to the /api/users/login endpoint, requiring user email and password in the JSON body. ```bash curl -X POST http://localhost:3000/api/users/login \ -H "Content-Type: application/json" \ -d '{ "user": { "email": "jake@example.com", "password": "password123" } }' ``` -------------------------------- ### Example JSON-RPC List Resources Request Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/mcp-tools.md An example of a JSON-RPC 2.0 request to list available resources exposed by the MCP server. This typically includes context and agent pack information. ```json { "jsonrpc": "2.0", "id": 2, "method": "resources/list", "params": {} } ``` -------------------------------- ### Rust: Error Display and Debugging with Hexser Source: https://github.com/squillo/hexser/blob/main/hexser/src/error/ERROR_GUIDE.md This example demonstrates how to handle and display errors generated by the hexser library. It covers printing the full error message, iterating through the error chain using `source()`, and matching on specific Hexserror variants for custom error handling. ```rust use hexser::error::Hexserror; use std::error::Error; fn handle_user_creation(req: CreateUserRequest) { match service.register_user(req).await { Ok(user) => { println!("User created successfully: {}", user.id); } Err(err) => { // Display the full error eprintln!("{}", err); // Print error chain let mut source = err.source(); while let Some(cause) = source { eprintln!("Caused by: {}", cause); source = cause.source(); } // Match on specific error types for custom handling match &err { Hexserror::Validation(_) => { // Return 400 Bad Request } Hexserror::NotFound(_) => { // Return 404 Not Found } Hexserror::Conflict(_) => { // Return 409 Conflict } _ => { // Return 500 Internal Server Error } } } } } ``` -------------------------------- ### Example JSON-RPC Requests Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/mcp-tools.md Examples of common JSON-RPC requests used to interact with the Hexser MCP server. ```APIDOC ## Example JSON-RPC Requests ### Initialize Request ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "example-client", "version": "1.0.0" } } } ``` ### List Resources Request ```json { "jsonrpc": "2.0", "id": 2, "method": "resources/list", "params": {} } ``` ### Read Resource Request ```json { "jsonrpc": "2.0", "id": 3, "method": "resources/read", "params": { "uri": "hexser://context" } } ``` ``` -------------------------------- ### JSON: Example AIContext with MethodInfo structure Source: https://github.com/squillo/hexser/blob/main/hexser/README.md An example JSON structure representing component information for AI assistants, including a detailed `methods` field. This field lists public methods with their signatures, documentation, parameters, return types, and visibility. ```json { "type_name": "UserRepository", "layer": "Port", "role": "Repository", "module_path": "ports::user_repository", "purpose": "Manages user persistence", "methods": [ { "name": "find_by_id", "signature": "fn find_by_id(&self, id: &str) -> HexResult>", "documentation": "Finds a user by their ID", "parameters": [ { "name": "id", "param_type": "&str", "description": "User identifier" } ], "return_type": "HexResult>", "is_public": true, "is_async": false } ], "dependencies": [] } ``` -------------------------------- ### Running Workspace Tests and Checks Source: https://github.com/squillo/hexser/blob/main/PUBLISHING.md Executes all tests across the entire Cargo workspace with all features enabled, and performs a build check. These are recommended pre-publishing steps to ensure code quality and stability. ```bash cargo test --workspace --all-features cargo check --workspace ``` -------------------------------- ### Example API Usage: Create Article Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Illustrates how to create a new article, including authentication. This POST request to /api/articles requires a JWT token in the Authorization header and article details in the JSON body. ```bash curl -X POST http://localhost:3000/api/articles \ -H "Content-Type: application/json" \ -H "Authorization: Token YOUR_JWT_TOKEN" \ -d '{ "article": { "title": "How to train your dragon", "description": "Ever wonder how?", "body": "Very carefully.", "tagList": ["dragons", "training"] } }' ``` -------------------------------- ### Example JSON-RPC Read Resource Request Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/mcp-tools.md An example of a JSON-RPC 2.0 request to read the content of a specific resource, such as architecture context or agent pack data, using its URI. ```json { "jsonrpc": "2.0", "id": 3, "method": "resources/read", "params": { "uri": "hexser://context" } } ``` -------------------------------- ### Cargo Build Command for Macros Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Command to rebuild a Rust project with the 'macros' feature enabled. This is often required for Hexser's compile-time registration to take effect. ```bash cargo build --features macros ``` -------------------------------- ### Repository Pattern: Domain-Owned Filters Example (Rust) Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Demonstrates the Repository Pattern with domain-owned filters in Rust. It shows how to construct an `ArticleFilter` and use the `QueryRepository::find` method with sorting and pagination options. ```rust let filter = crate::ports::article_repository::ArticleFilter::And(vec![ ArticleFilter::ByTag(std::string::String::from("rust")), ArticleFilter::ByAuthor(author_id), ]); let articles = hexser::ports::repository::QueryRepository::find( &*repo, &filter, hexser::ports::repository::FindOptions { sort: std::option::Option::Some(vec![ hexser::ports::repository::Sort { key: ArticleSortKey::CreatedAt, direction: hexser::ports::repository::Direction::Desc, } ]), limit: std::option::Option::Some(20), offset: std::option::Option::Some(0), } )?; ``` -------------------------------- ### Publishing Crates with Cargo Source: https://github.com/squillo/hexser/blob/main/PUBLISHING.md Commands for publishing individual crates within a Cargo workspace. It includes dry-run validation before the actual publish command. Publishing must be done in dependency order: macros, main crate, then examples/patterns. ```bash cargo publish -p hexser_macros --dry-run cargo publish -p hexser_macros cargo publish -p hexser --dry-run cargo publish -p hexser cargo publish -p hexser_potions --dry-run cargo publish -p hexser_potions ``` -------------------------------- ### Rust Entity Definition Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Defines a Customer entity with Hexser derive macros for domain and cloning. This entity is used to represent data within the Hexser architecture. ```rust #[derive(HexEntity, HexDomain, Clone, Debug)] pub struct Customer { pub id: String, pub name: String, } ``` -------------------------------- ### Creating and Pushing a Signed Git Tag Source: https://github.com/squillo/hexser/blob/main/PUBLISHING.md Creates a signed Git tag for a release and pushes it to the remote repository. This is a standard practice for marking releases and ensuring code integrity. ```bash git tag -s v0.4.7 -m "hexser 0.4.7 release" git push origin v0.4.7 ``` -------------------------------- ### Cargo Check Command for MCP Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Command to check a Rust project with the 'mcp' feature enabled. Used for diagnosing compilation errors related to the MCP server. ```bash cargo check --features mcp ``` -------------------------------- ### Inspecting Packaged Crate Contents Source: https://github.com/squillo/hexser/blob/main/PUBLISHING.md Lists the files that would be included in a crate package. This command helps in verifying the contents of the crate before publishing, ensuring no unintended files are included. ```bash cargo package -p hexser_macros --list cargo package -p hexser --list cargo package -p hexser_potions --list ``` -------------------------------- ### Build Hex MCP Server Binary Source: https://github.com/squillo/hexser/blob/main/hexser/README.md Builds and runs the `hex-mcp-server` binary, which starts an MCP (Model Context Protocol) server over stdio. Requires the `mcp` feature to be enabled. ```bash carp run --bin hex-mcp-server --features mcp ``` -------------------------------- ### Configure Claude Desktop MCP Server Source: https://github.com/squillo/hexser/blob/main/hexser/README.md Example JSON configuration for Claude Desktop to connect to the Hexser MCP server. This specifies the command to run, arguments, and the working directory. ```json { "mcpServers": { "hexser": { "command": "cargo", "args": ["run", "-p", "hexser", "--features", "mcp", "--bin", "hex-mcp-server"], "cwd": "/path/to/your/hexser/project" } } } ``` -------------------------------- ### Regenerate Architecture Diagram with Bash Script Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md This bash script navigates to the example directory and regenerates the architecture diagram and AI pack. It utilizes `cargo run --bin generate_architecture_diagram` to perform the regeneration. ```bash cd hexser/examples/realworld_api ./regenerate_diagram.sh ``` -------------------------------- ### Rust: Query and Print HexGraph Architecture Summary Source: https://github.com/squillo/hexser/blob/main/hexser/tutorials/05-graph-analysis/README.md Demonstrates how to access the current HexGraph at runtime in Rust, pretty-print the entire graph, and count components by layer. This function can be added to any example for runtime analysis. ```rust fn print_arch_summary() { let graph = hexser::HexGraph::current(); // Pretty print the entire graph graph.pretty_print(); // Count components by layer let domain_count = graph.nodes_by_layer(hexser::Layer::Domain).len(); let ports_count = graph.nodes_by_layer(hexser::Layer::Port).len(); let adapters_count = graph.nodes_by_layer(hexser::Layer::Adapter).len(); let app_count = graph.nodes_by_layer(hexser::Layer::Application).len(); println!("\nArchitecture summary:"); println!(" Domain: {}", domain_count); println!(" Ports: {}", ports_count); println!(" Adapters: {}", adapters_count); println!(" Application: {}", app_count); } ``` -------------------------------- ### Rust: Provide Actionable Guidance in Errors Source: https://github.com/squillo/hexser/blob/main/hexser/src/error/ERROR_GUIDE.md Illustrates how to add actionable guidance, such as next steps and concrete suggestions, to Hexserror instances. This practice makes error messages more helpful to developers and users by indicating how to resolve the issue. ```Rust Hexserror::validation_field("Password too short", "password") .with_next_step("Use a password with at least 8 characters") .with_suggestion("Try: MyP@ssw0rd2024") Hexserror::validation("Invalid password") // No actionable guidance ``` -------------------------------- ### Implement QueryRepository for InMemoryUserRepository (Rust) Source: https://github.com/squillo/hexser/blob/main/hexser/MIGRATION_GUIDE.md Implements the `QueryRepository` trait for `InMemoryUserRepository`. This involves defining the `Filter` and `SortKey` types and implementing methods like `find_one` and `find` to handle queries based on filters and sorting options. ```rust impl QueryRepository for InMemoryUserRepository { type Filter = UserFilter; type SortKey = UserSortKey; fn find_one(&self, f: &Self::Filter) -> HexResult> { /* match filter */ } fn find(&self, f: &Self::Filter, opts: FindOptions) -> HexResult> { /* filter + sort + page */ } } ``` -------------------------------- ### Run MCP Server (Hexser) Source: https://github.com/squillo/hexser/blob/main/hexser/README.md Command to start the Model Context Protocol (MCP) server for the Hexser project. This server exposes project architecture to AI assistants via JSON-RPC over stdio. Requires the 'mcp' feature. ```shell cargo run -p hexser --features mcp --bin hex-mcp-server ``` -------------------------------- ### Rust Standard Library Error Source Access Source: https://github.com/squillo/hexser/blob/main/hexser/src/error/ERROR_GUIDE.md Demonstrates how to access the underlying source error chain using the standard `std::error::Error::source()` method. This function recursively prints all errors in the chain, starting from the most specific to the root cause. ```rust use std::error::Error; fn print_error_chain(err: &dyn Error) { eprintln!("Error: {}", err); let mut source = err.source(); while let Some(err) = source { eprintln!("Caused by: {}", err); source = err.source(); } } ``` -------------------------------- ### Run Hexser MCP Server from Terminal Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Commands to run the hexser MCP server using Cargo. This allows for manual testing before connecting an AI agent. The `--features mcp` flag is essential to enable the MCP functionality. The `--bin hex-mcp-server` specifies the binary to run. ```bash cd /path/to/your/hexser/project cargo run --features mcp --bin hex-mcp-server ``` ```bash cargo run -p hexser --features mcp --bin hex-mcp-server ``` -------------------------------- ### Hexser Error Types and Layer-Specific Errors Source: https://github.com/squillo/hexser/blob/main/hexser/src/error/ERROR_GUIDE.md Illustrates the definition of the main `Hexserror` enum and its variants for different architectural layers (Domain, Port, Adapter, Validation, NotFound, Conflict). It includes examples of constructing specific layer errors with contextual details. ```rust pub enum Hexserror { Domain(DomainError), Port(PortError), Adapter(AdapterError), Validation(ValidationError), NotFound(NotFoundError), Conflict(ConflictError), } use hexser::error::{Hexserror, codes}; let err = Hexserror::domain( codes::domain::INVARIANT_VIOLATION, "Account balance cannot be negative" ) .with_next_step("Ensure sufficient funds before withdrawal") .with_suggestion("Check account.balance >= amount"); use hexser::error::port_error; let err = port_error::communication_failure("Database connection lost"); let err = port_error::port_timeout("UserRepository"); let err = port_error::port_not_found("PaymentGateway"); use hexser::error::adapter_error; let err = adapter_error::connection_failed("PostgreSQL", "Connection refused"); let err = adapter_error::api_failure("Payment API returned 503"); let err = adapter_error::mapping_failure("Cannot map DTO to entity"); use hexser::error::{Hexserror, codes}; let err = Hexserror::validation("Required field missing") .with_field("username"); let err = Hexserror::validation_field("Must be at least 8 characters", "password") .with_suggestion("Use a longer password"); use hexser::error::Hexserror; let err = Hexserror::not_found("Order", "order-123"); let err = Hexserror::not_found("User", "user@example.com"); use hexser::error::Hexserror; let err = Hexserror::conflict("Email already registered") .with_existing_id("user-456") .with_next_step("Use a different email or recover existing account"); ``` -------------------------------- ### Rust: Test Error Scenarios with Assertions Source: https://github.com/squillo/hexser/blob/main/hexser/src/error/ERROR_GUIDE.md Provides an example of how to write unit tests for error cases in Rust using the Hexserror framework. This test verifies that an error is returned, checks the specific error type, and asserts that the error message contains expected content. ```Rust #[test] fn test_order_empty_invariant() { let order = Order::new(); let result = order.submit(); assert!(result.is_err()); let err = result.unwrap_err(); assert!(matches!(err, Hexserror::Domain(_))); assert!(err.to_string().contains("E_HEX_001")); } ``` -------------------------------- ### Send Initialize Command to MCP Server Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md A sample JSON-RPC 2.0 request to initialize the MCP server. This is used for manual testing to verify communication. The server expects a JSON payload and responds with a similar structure indicating its capabilities. ```json {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}} ``` -------------------------------- ### Configure Junie MCP Servers JSON Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md This JSON configuration defines how Junie connects to an MCP server, specifically for the 'hexser' project. It specifies the command to run, arguments including project and feature flags, and the current working directory. Ensure the `cwd` path is absolute and matches your project's root directory. ```json { "mcpServers": { "hexser": { "command": "cargo", "args": [ "run", "-p", "hexser", "--features", "mcp", "--bin", "hex-mcp-server" ], "cwd": "/absolute/path/to/your/hexser/project" } } } ``` -------------------------------- ### IntelliJ Plugin Configuration for Hexser MCP Server Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Details the settings required when configuring Junie's MCP server through the IntelliJ plugin UI. This includes specifying the server name, the command (`cargo`), arguments, and the working directory for the hexser project. ```text - Name: hexser - Command: cargo - Arguments: run -p hexser --features mcp --bin hex-mcp-server - Working Directory: /absolute/path/to/your/project ``` -------------------------------- ### Rich Error Handling Example (Rust) Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Illustrates Hexser's rich error handling mechanism in Rust. This example shows how to create a validation error with specific fields and suggest the next step for the user. ```rust if user.password_hash != password_hash { return std::result::Result::Err( hexser::Hexserror::validation("Invalid password") .with_field("password") .with_next_step("Check your password and try again") ); } ``` -------------------------------- ### Build Project with MCP Feature Enabled Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Command to rebuild the Rust project with the MCP feature enabled. This is necessary after modifying the Cargo.toml file to include the 'mcp' feature. It ensures that all necessary components for the MCP server are compiled. ```bash cargo build --features mcp ``` -------------------------------- ### Rust Hexser RichError with More Info Link Source: https://github.com/squillo/hexser/blob/main/hexser/src/error/ERROR_GUIDE.md Allows linking errors to external documentation for detailed remediation steps. The `with_more_info` method adds a URL to the error, guiding users to further explanations or solutions. ```rust use hexser::error::{Hexserror, RichError}; let err = Hexserror::domain("E_HEX_002", "Invariant violation") .with_more_info("https://docs.example.com/errors/E_HEX_002"); ``` -------------------------------- ### hex_mcp_server Binary Usage Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/mcp-tools.md Instructions on how to run the pre-built Hexser MCP server binary and an overview of the communication protocol flow. ```APIDOC ## The hex_mcp_server Binary Hexser includes a pre-built MCP server binary that you can run to expose your architecture data. ### Usage ```bash # Run the MCP server cargo run --bin hex_mcp_server --features ai,mcp # Or if installed: hex_mcp_server ``` The server communicates over stdio using line-delimited JSON-RPC 2.0 messages. AI agents connect to this server and send requests via stdin, receiving responses on stdout. ### Protocol Flow 1. **Client connects** to the server process 2. **Initialize**: Client sends `initialize` method with protocol version 3. **Server responds** with capabilities and server info 4. **Client requests** resources via `list_resources` or `read_resource` 5. **Server responds** with architecture data 6. **Connection closes** when client disconnects ``` -------------------------------- ### Hexser Error Handling Cookbook Examples in Rust Source: https://github.com/squillo/hexser/blob/main/hexser/README.md Provides various examples of using hexser for different error types in Rust, including validation, not found, port, and adapter errors. It showcases how to chain errors with `with_source` and add context like `next_steps` and `suggestions`. ```rust // Validation errors (field-aware) return Err(hexser::error::hex_error::Hexserror::validation_field( "Title cannot be empty", "title", )); // Not Found errors (resource + id) return Err(hexser::error::hex_error::Hexserror::not_found("User", "123") .with_next_step("Verify the ID and try again")); // Port errors (communication issues) let port_err = hexser::hex_port_error!( hexser::error::codes::port::PORT_TIMEOUT, "User service timed out" ).with_suggestion("Increase timeout or retry later"); // Adapter errors (infra failures) with source error fn fetch_from_api(url: &str) -> HexResult { let resp = std::fs::read_to_string(url) .map_err(|ioe| hexser::hex_adapter_error!( hexser::error::codes::adapter::IO_FAILURE, // or API_FAILURE in real HTTP "Failed to fetch resource" ).with_source(ioe))?; Ok(resp) } ``` -------------------------------- ### JSON: Example MCP Refresh Request Source: https://github.com/squillo/hexser/blob/main/TASK_PLAN.md This is an example JSON payload for an MCP server's refresh method. It follows the JSON-RPC 2.0 specification and includes the method name and parameters required to refresh a specific project. This format is used for inter-process communication with the MCP server. ```json { "jsonrpc": "2.0", "id": 1, "method": "hexser/refresh", "params": { "project": "myproject" } } ``` -------------------------------- ### Get Article by Slug API Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Retrieves a single article identified by its slug. ```APIDOC ## GET /api/articles/:slug ### Description Retrieves a specific article using its unique slug. ### Method GET ### Endpoint /api/articles/:slug ### Parameters #### Path Parameters - **slug** (string) - Required - The unique slug of the article to retrieve. ### Response #### Success Response (200) - **article** (object) - The requested article object. #### Response Example (Response structure for getting an article by slug not provided in source text) ``` -------------------------------- ### Verify Hexser Dependency with MCP Feature in Cargo.toml Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md This snippet shows how to check and add the 'mcp' feature to the hexser dependency in your Cargo.toml file. Enabling this feature is crucial for the MCP server functionality. Ensure the version matches your project's requirements. ```toml [dependencies] hexser = { version = "0.4.5", features = ["mcp", "macros"] } ``` ```toml [workspace.dependencies] hexser = { version = "0.4.5", path = "hexser", features = ["mcp", "macros"] } ``` -------------------------------- ### Diagnose Hexser MCP Server Configuration (Bash) Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md This bash command sequence helps diagnose if the Hexser MCP server is configured correctly. It first builds the project with the 'mcp' feature and then runs the MCP server, sending a sample JSONRPC request to list resources. Successful execution results in JSON output. ```bash cd /path/to/your/project cargo build --features mcp cargo run --features mcp --bin hex-mcp-server <<< '{"jsonrpc":"2.0","id":1,"method":"resources/list","params":{}}' ``` -------------------------------- ### Hexagonal Architecture: Application Layer (Rust) Source: https://github.com/squillo/hexser/blob/main/hexser/examples/realworld_api/README.md Shows the Application Layer of the Hexagonal Architecture in Rust, implementing the CQRS pattern. This example demonstrates a `RegisterUserHandler` implementing `DirectiveHandler` to process directives. ```rust // application/user/register.rs impl hexser::DirectiveHandler for RegisterUserHandler { fn handle(&self, directive: RegisterUserDirective) -> hexser::HexResult<()> { hexser::Directive::validate(&directive)?; // Business logic here } } ``` -------------------------------- ### Running the hex_mcp_server Binary Source: https://github.com/squillo/hexser/blob/main/hexser/docs/src/mcp-tools.md Provides commands to run the Hexser MCP server binary, enabling the exposure of architecture data. Requires enabling 'ai' and 'mcp' features. ```bash # Run the MCP server cargo run --bin hex_mcp_server --features ai,mcp # Or if installed: hex_mcp_server ``` -------------------------------- ### Adjust Cargo Arguments for Project Name Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Shows how to modify the `args` array in the Junie MCP server configuration when your Rust project is not named 'hexser'. Specifically, it highlights changing the `-p` flag to match your project's actual name. ```json "args": [ "run", "-p", "your-project-name", "--features", "mcp", "--bin", "hex-mcp-server" ] ``` -------------------------------- ### Update Hexser Project Path in Configuration Source: https://github.com/squillo/hexser/blob/main/hexser/docs/MCP_BEGINNER_WALKTHROUGH.md Illustrates how to update the `cwd` (current working directory) field within the Junie MCP server configuration for different operating systems. It's crucial to replace the placeholder with the actual absolute path to your hexser project. ```json "cwd": "/Users/yourname/projects/my-hexser-app" ``` ```json "cwd": "C:\\Users\\yourname\\projects\\my-hexser-app" ``` -------------------------------- ### JSON: AI Tool Configuration for MCP Server Source: https://github.com/squillo/hexser/blob/main/TASK_PLAN.md This JSON configuration snippet shows how to integrate the Hexser MCP server with AI tools. It specifies a command to execute, which first compiles the project (`cargo build -q`) and then starts the MCP server. This ensures that the AI tool queries an up-to-date architecture graph. The `cwd` parameter specifies the project's working directory. ```json { "mcpServers": { "hexser": { "command": "sh", "args": ["-c", "cargo build -q && cargo run --bin hex-mcp-server"], "cwd": "/path/to/project" } } } ``` -------------------------------- ### Bash Command for Testing Hexser Potions Crate Source: https://github.com/squillo/hexser/blob/main/hexser/docs/ARCHITECTURE.md This bash command executes tests specifically for the `hexser_potions` crate, which contains copy-paste-friendly examples with tests for common flows like authentication and CRUD operations. ```bash # Test potions cargo test -p hexser_potions ``` -------------------------------- ### Rust: In-memory Repository with QueryRepository Implementation Source: https://github.com/squillo/hexser/blob/main/hexser/tutorials/03-implementing-adapters/README.md This snippet shows a Rust implementation of an in-memory repository for 'Todo' entities. It implements both the standard 'Repository' for writes and the 'QueryRepository' for filtered reads, demonstrating how to translate domain-owned filters into concrete data retrieval logic. It uses fully qualified paths for clarity. ```rust // Domain-owned types #[derive(Clone)] struct Todo { id: String, title: String, done: bool } impl hexser::domain::Entity for Todo { type Id = String; } #[derive(Clone)] enum TodoFilter { All, ById(String) } #[derive(Clone, Copy)] enum TodoSortKey { Id } // Adapter implements write via Repository and read via QueryRepository struct InMemoryTodoRepository { todos: std::vec::Vec } impl hexser::ports::Repository for InMemoryTodoRepository { fn save(&mut self, t: Todo) -> hexser::HexResult<()> { self.todos.push(t); Ok(()) } } impl hexser::ports::repository::QueryRepository for InMemoryTodoRepository { type Filter = TodoFilter; type SortKey = TodoSortKey; fn find_one(&self, f: &TodoFilter) -> hexser::HexResult> { let found = match f { TodoFilter::All => self.todos.first().cloned(), TodoFilter::ById(id) => self.todos.iter().find(|t| &t.id == id).cloned(), }; Ok(found) } fn find(&self, f: &TodoFilter, _o: hexser::ports::repository::FindOptions) -> hexser::HexResult> { let v = match f { TodoFilter::All => self.todos.clone(), TodoFilter::ById(id) => self.todos.iter().filter(|t| &t.id == id).cloned().collect(), }; Ok(v) } } // Read all with defaults let v = >::find( &repo, &TodoFilter::All, hexser::ports::repository::FindOptions::default(), )?; ``` -------------------------------- ### Example Hexser Refresh Compilation Error Response (JSON-RPC) Source: https://github.com/squillo/hexser/blob/main/hexser/README.md This JSON-RPC response indicates a compilation error during a hexser/refresh request. It provides details about the compilation failure, allowing for debugging. ```json { "jsonrpc": "2.0", "id": 1, "result": { "status": "error", "compiled": false, "components_added": 0, "components_removed": 0, "error": "error[E0425]: cannot find value `foo` in this scope..." } } ```