### Start ArchGuard Backend with Gradle Source: https://github.com/archguard/archguard/blob/master/examples/observability/README.md This command starts the ArchGuard backend service using Gradle. It assumes you are in the project's root directory and have Gradle installed. ```bash cd ../.. ./gradlew :server:bootRun ``` -------------------------------- ### MCP Server Configuration Example Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-issue.md Example configuration for integrating the ArchGuard MCP server with an AI assistant like Claude Desktop. ```APIDOC ## Example Usage ### Claude Desktop Configuration ```json { "mcpServers": { "archguard": { "command": "java", "args": ["-jar", "/path/to/archguard-mcp-server.jar"] } } } ``` ### User Interaction Example ``` User: "Review the API design in my Spring Boot project" Claude: [Uses lint_webapi tool via MCP] Claude: "I found 15 API design issues: 1. POST /api/user/delete - HTTP method should not be in URL 2. GET /api/GetUsers - URL should use lowercase ..." ``` ``` -------------------------------- ### Start Observability Stack with Docker Compose Source: https://github.com/archguard/archguard/blob/master/examples/observability/README.md This command initiates the observability stack, including Jaeger, Prometheus, and Grafana, using Docker Compose. Ensure Docker is installed and running. ```bash cd examples/observability docker-compose up -d ``` -------------------------------- ### Manage Systems: Get All Systems Source: https://context7.com/archguard/archguard/llms.txt Retrieves a list of all systems managed within ArchGuard. ```bash curl -X GET http://localhost:8080/api/system-info ``` -------------------------------- ### Run Sample Application with Gradle Source: https://github.com/archguard/archguard/blob/master/examples/observability/README.md This command executes the sample application that sends telemetry data. It requires Gradle to be installed and the user to be in the 'examples/observability' directory. ```bash cd examples/observability ./gradlew run ``` -------------------------------- ### Manage Systems: Get System Details Source: https://context7.com/archguard/archguard/llms.txt Retrieves detailed information for a specific system identified by its ID. ```bash curl -X GET http://localhost:8080/api/system-info/1 ``` -------------------------------- ### Run ArchGuard MCP Server in HTTP Mode Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md These bash commands demonstrate how to start the ArchGuard MCP Server in HTTP mode. The first command starts the server with default settings (localhost:8080), while the second allows specifying a custom port. ```bash # Start with HTTP transport (binds to localhost:8080 by default) MCP_MODE=http java -jar archguard-mcp-server.jar # Or with custom port MCP_MODE=http MCP_PORT=9000 java -jar archguard-mcp-server.jar ``` -------------------------------- ### Configure MCP Server Usage Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Configuration examples for integrating the server with Claude Desktop and running it via Docker. Also provides a sample curl command for direct HTTP interaction. ```json { "mcpServers": { "archguard": { "command": "java", "args": ["-jar", "/path/to/archguard-mcp-server.jar"], "env": { "MCP_MODE": "stdio" } } } } ``` ```bash docker run -d -p 127.0.0.1:8080:8080 -v /path/to/project:/workspace -e MCP_MODE=http archguard/mcp-server:latest ``` ```bash curl -X POST http://localhost:8080/mcp -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "lint_code", "arguments": {"path": "/workspace/my-project", "language": "java"}}, "id": 1}' ``` -------------------------------- ### Define Architecture DSL Source: https://github.com/archguard/archguard/blob/master/architecture-as-code/repl-api/README.md Example of using the ArchDoc DSL to define layered architecture components and their dependencies. ```kotlin @file:DependsOn("org.archguard.scanner:doc-executor:2.0.0-alpha.2") import org.archguard.dsl.* var layer = layered { prefixId("org.archguard") component("controller") dependentOn component("service") 组件("service") 依赖于 组件("repository") } ``` -------------------------------- ### ArchGuard CLI Usage Examples Source: https://github.com/archguard/archguard/blob/master/scanner_cli/README.md Demonstrates the practical application of the ArchGuard CLI for different scanning types. It shows how to configure parameters like type, system ID, server URL, workspace, path, output format, language, features, repository ID, and branch for GIT, SCA, and SOURCE_CODE analysis. ```bash [SCANNER] org.archguard.scanner.ctl.Runner |type: GIT |systemId: 6 |serverUrl: http://localhost:8080 |workspace: /tmp/archguard14370627952499838085 |path: /tmp/archguard14370627952499838085 |output: [http] |analyzerSpec: [] |slotSpec: [] |language: Java |features: [] |repoId: https://gitee.com/thoughtworks/coca |branch: master |startedAt: 0 |since: null |until: null |depth: 7 |rules: [] ``` ```bash [SCANNER] org.archguard.scanner.ctl.Runner |type: SCA |systemId: 6 |serverUrl: http://localhost:8080 |workspace: /tmp/archguard14370627952499838085 |path: /tmp/archguard14370627952499838085 |output: [http] |analyzerSpec: [] |slotSpec: [] |language: java |features: [] |repoId: null |branch: master |startedAt: 0 |since: null |until: null |depth: 7 |rules: [] ``` ```bash [SCANNER] org.archguard.scanner.ctl.Runner |type: SOURCE_CODE |systemId: 6 |serverUrl: http://localhost:8080 |workspace: /tmp/archguard14370627952499838085 |path: /tmp/archguard14370627952499838085 |output: [http] |analyzerSpec: [] |slotSpec: [] |language: Java |features: [apicalls, datamap] |repoId: null |branch: master |startedAt: 0 |since: null |until: null |depth: 7 |rules: [webapi, test, sql] ``` -------------------------------- ### Example JSON Request to Get Rules Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This JSON payload illustrates how to use the `get_rules` tool to retrieve linting rules for a specific category, such as 'webapi'. ```json { "method": "tools/call", "params": { "name": "get_rules", "arguments": { "category": "webapi" } } } ``` -------------------------------- ### Coupling Metrics API: Get All Modules Coupling Metrics Source: https://context7.com/archguard/archguard/llms.txt Retrieves coupling metrics for all modules within a specified system. ```bash curl -X GET http://localhost:8080/api/systems/1/metric/coupling/all-module ``` -------------------------------- ### Push Scan Results to Server via CLI Source: https://github.com/archguard/archguard/blob/master/scanner_cli/README.md Example of how to use the ArchGuard CLI to scan a project and push the results to the ArchGuard API server. It specifies the language, features, output format, path, and server URL. ```bash java -jar scanner_cli.jar --language=Kotlin --features=apicalls --output=http --output=json --path=. --server-url=http://localhost:8080 ``` -------------------------------- ### Container Service API: Get Services for Multiple Systems Source: https://context7.com/archguard/archguard/llms.txt Retrieves service information for multiple systems by providing a list of system IDs. ```bash curl -X GET "http://localhost:8080/api/container-service/systems?system=1&system=2&system=3" ``` -------------------------------- ### Class Dependency Analysis: Get Complete Code Tree Source: https://context7.com/archguard/archguard/llms.txt Retrieves the complete code structure tree for a given system. ```bash curl -X GET http://localhost:8080/api/systems/1/classes/code-tree ``` -------------------------------- ### Example JSON Request to Lint SQL Statements Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This JSON payload demonstrates how to call the `lint_sql` tool via the MCP Server. It includes the SQL statement to be analyzed as an argument. ```json { "method": "tools/call", "params": { "name": "lint_sql", "arguments": { "sql": "CREATE TABLE users (id INT, name VARCHAR);" } } } ``` -------------------------------- ### ArchGuard MCP Server - Get Rules Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This section shows how to retrieve a list of available linting rules, optionally filtered by category. ```APIDOC ## POST /tools/call (Get Rules) ### Description Retrieves a list of available architectural linting rules, optionally filtered by category. ### Method POST ### Endpoint /tools/call ### Parameters #### Request Body - **method** (string) - Required - Must be "tools/call". - **params** (object) - Required - Parameters for the tool call. - **name** (string) - Required - Must be "get_rules". - **arguments** (object) - Optional - Arguments for filtering rules. - **category** (string) - Optional - The category of rules to retrieve (e.g., "code", "webapi", "sql", "test", "layer", "comment", "protobuf"). If omitted, all rules are returned. ### Request Example ```json { "method": "tools/call", "params": { "name": "get_rules", "arguments": { "category": "webapi" } } } ``` ### Response #### Success Response (200) - **result** (array) - A list of rule objects, each containing details like id, message, severity, and ruleUrl. #### Response Example ```json { "result": [ { "id": "WEBAPI-001", "message": "API endpoint should use plural nouns for collections.", "severity": "warning", "ruleUrl": "archguard://rules/webapi" } ] } ``` ``` -------------------------------- ### Fix Issues Prompt Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-proposal.md A pre-defined prompt template for reviewing linting issues and generating suggested fixes with code examples. ```APIDOC ### Prompt Template: fix-issues This prompt is used to review linting issues and suggest fixes. **Template:** ``` Review the linting issues in {file}: {issues} Suggest fixes for each issue with code examples. ``` **Parameters:** - **file** (string) - The file containing the linting issues. - **issues** (string) - A detailed description of the linting issues found. ``` -------------------------------- ### Initialize Language Service with languages.json Source: https://github.com/archguard/archguard/blob/master/analyser_estimate/src/test/resources/kotlin/LanguageService.kt.txt Initializes the LanguageService by loading language definitions from `languages.json`. It parses the JSON file to populate internal maps for extension-to-language mapping, filename-to-language mapping, and shebang lookups. This setup is crucial for subsequent language detection tasks. ```Kotlin package org.archguard.scanner.analyser.count import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import java.io.File import kotlin.experimental.or class LanguageService { private val extensionCache: HashMap = hashMapOf() private val SHE_BANG: String = "#!" private var extToLanguages: MutableMap> = mutableMapOf() private var filenameToLanguage: MutableMap = mutableMapOf() private var languageFeatures: MutableMap = mutableMapOf() private var shebangLookup: MutableMap> = mutableMapOf() init { val fileContent = this.javaClass.classLoader.getResource("languages.json")!!.readText() val languageMap: HashMap = Json.decodeFromString(fileContent) languageMap.forEach { (name, lang) -> lang.name = name lang.extensions.forEach { extToLanguages.getOrPut(it) { listOf() } extToLanguages[it] = extToLanguages[it]?.plus(name)!! } lang.fileNames?.forEach { filenameToLanguage[it] = name } if (lang.sheBangs != null) { shebangLookup[name] = lang.sheBangs } processLanguageFeatures(name, lang) } } data class LanguageGuess( val name: String, val count: Int, ) // ... other methods ... } ``` -------------------------------- ### Container Service API: Get Services Map for a System Source: https://context7.com/archguard/archguard/llms.txt Retrieves the service map for a specific system, detailing services, their resources, and inter-service demands. ```bash curl -X GET http://localhost:8080/api/container-service/1 ``` -------------------------------- ### Coupling Metrics API: Get Module Coupling Metrics Source: https://context7.com/archguard/archguard/llms.txt Calculates and retrieves coupling metrics for a specific module within a system. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/metric/coupling/module?moduleName=core" ``` -------------------------------- ### Coupling Metrics API: Get All Classes Coupling in a Package Source: https://context7.com/archguard/archguard/llms.txt Retrieves coupling metrics for all classes within a specified package and module of a system. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/metric/coupling/package-class-list?packageName=com.example.service&moduleName=core" ``` -------------------------------- ### Send Telemetry Manually with Kotlin Script Source: https://github.com/archguard/archguard/blob/master/examples/observability/README.md This command runs a Kotlin script to manually send telemetry data. It requires the Kotlin compiler (kotlinc) to be installed and the script to be in the 'sample-app' directory. ```bash cd sample-app kotlinc -script send-telemetry.main.kts ``` -------------------------------- ### Scan with Arrow Output Format Source: https://github.com/archguard/archguard/blob/master/scanner_cli/README.md An example of running the ArchGuard scanner with the output format set to 'arrow'. This command also includes JVM arguments for opening unnamed modules, which may be necessary for certain Java versions or environments. ```bash java --add-opens=java.base/java.nio=ALL-UNNAMED -jar plugins/scanner-v2.jar --type=source_code --path=. --output=json --language=kotlin --output=arrow ``` -------------------------------- ### Example JSON Request to Lint Web API Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This JSON payload shows how to invoke the `lint_webapi` tool. It requires the project path and a list of API definitions, including resource URLs and methods. ```json { "method": "tools/call", "params": { "name": "lint_webapi", "arguments": { "path": "/path/to/project", "apis": [ { "name": "UserService", "resources": [ { "url": "/api/GetUsers", "method": "GET" } ] } ] } } } ``` -------------------------------- ### Manage Systems: Create New System Source: https://context7.com/archguard/archguard/llms.txt Creates a new system in ArchGuard. Requires system name, repository URL, repository type, programming language, and a scanned status. ```bash curl -X POST \ -H "Content-Type: application/json" \ -d '{ "systemName": "my-microservice", "repo": "https://github.com/org/repo", "repoType": "GIT", "language": "Java", "scanned": false }' \ http://localhost:8080/api/system-info ``` -------------------------------- ### Configure and Run MCP Server Source: https://context7.com/archguard/archguard/llms.txt Build and execute the ArchGuard MCP server in either stdio or HTTP mode to enable AI assistant integration. ```bash ./gradlew :mcp-server:shadowJar java -jar mcp-server/build/libs/archguard-mcp-server.jar MCP_MODE=http MCP_PORT=8080 java -jar archguard-mcp-server.jar ``` -------------------------------- ### Build and Containerize MCP Server Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Commands and configuration for building the fat JAR and creating a Docker image for the MCP server. Includes environment variable configuration for stdio and HTTP modes. ```bash ./gradlew :mcp-server:jar ``` ```dockerfile FROM openjdk:17-slim WORKDIR /app COPY mcp-server/build/libs/mcp-server-all.jar /app/archguard-mcp-server.jar ENV MCP_MODE=stdio ENV MCP_PORT=8080 EXPOSE 8080 CMD ["java", "-jar", "/app/archguard-mcp-server.jar"] ``` ```bash docker build -t archguard/mcp-server:latest . ``` -------------------------------- ### ArchGuard Scanner CLI Help and Options Source: https://github.com/archguard/archguard/blob/master/scanner_cli/README.md Displays the help message and lists all available options for the ArchGuard Scanner CLI. This includes options for specifying analysis type, system ID, server URL, workspace, output format, language, rules, features, and Git repository details. ```bash java -jar scanner_cli-2.2.0-all.jar --help ``` -------------------------------- ### Query Database with KtORM Source: https://github.com/archguard/archguard/blob/master/architecture-as-code/repl-api/README.md Demonstrates using the KtORM library to perform SQL-like queries, including aliasing, grouping, and having clauses. ```kotlin val t = Employees.aliased("t") database .from(t) .select(t.departmentId, avg(t.salary)) .groupBy(t.departmentId) .having { avg(t.salary) greater 100.0 } .forEach { row -> println("${row.getInt(1)}:${row.getDouble(2)}") } ``` -------------------------------- ### Configure MCP Main Server Application Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md The main entry point for the MCP server, supporting execution in either stdio or HTTP modes. It configures the protocol handler and manages server lifecycle events. ```kotlin fun main(args: Array) { val mode = System.getenv("MCP_MODE") ?: "stdio" val port = System.getenv("MCP_PORT")?.toIntOrNull() ?: 8080 when (mode) { "stdio" -> runStdioServer() "http" -> runHttpServer(port) else -> { logger.error { "Unknown mode: $mode" } } } } fun runHttpServer(port: Int) { embeddedServer(Netty, port = port, host = "127.0.0.1") { install(ContentNegotiation) { json() } routing { post("/mcp") { val request = call.receiveText() val response = handler.handleRequest(request) call.respondText(response, ContentType.Application.Json) } } }.start(wait = true) } ``` -------------------------------- ### Clean Up Docker Resources Source: https://github.com/archguard/archguard/blob/master/examples/observability/README.md This command stops and removes all containers and volumes created by the Docker Compose setup, ensuring a clean state. ```bash docker-compose down -v ``` -------------------------------- ### Lint All Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-proposal.md Runs all applicable linters on a project. ```APIDOC ## POST lint_all ### Description Runs all applicable linters on a project. ### Method POST ### Endpoint lint_all ### Parameters #### Request Body *Requires specific input parameters for project analysis. Refer to tool documentation for details.* ### Request Example None provided. ### Response #### Success Response (200) *Returns aggregated analysis results from all linters.* #### Response Example None provided. ``` -------------------------------- ### Coupling Metrics API: Get Package Coupling Metrics Source: https://context7.com/archguard/archguard/llms.txt Calculates and retrieves coupling metrics for a specific package within a module of a system. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/metric/coupling/package?packageName=com.example.service&moduleName=core" ``` -------------------------------- ### Test MCP Server Integration with Ktor Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Demonstrates how to test MCP protocol handlers using Ktor's test framework. It sets up a mock application module and verifies JSON-RPC responses for initialization and resource listing. ```kotlin class McpServerIntegrationTest { private fun Application.testModule() { install(ContentNegotiation) { json() } val handler = McpProtocolHandler(ResourceProvider(), ToolRegistry(), PromptRegistry()) routing { post("/mcp") { val request = call.receiveText() val response = handler.handleRequest(request) call.respondText(response, ContentType.Application.Json) } } } @Test fun testInitializeRequest() = testApplication { application { testModule() } val response = client.post("/mcp") { contentType(ContentType.Application.Json) setBody("{\"jsonrpc\": \"2.0\", \"method\": \"initialize\", \"id\": 1}") } assertEquals(HttpStatusCode.OK, response.status) } } ``` -------------------------------- ### Deploy ArchGuard with Docker Source: https://context7.com/archguard/archguard/llms.txt Build and run the ArchGuard backend and MCP server containers, or use Docker Compose for multi-service orchestration. ```bash docker build -t archguard/archguard-backend:latest . docker run -p 8080:8080 archguard/archguard-backend:latest docker run -i archguard/mcp-server:latest ``` -------------------------------- ### Class Dependency Analysis: Get Class Dependencies Source: https://context7.com/archguard/archguard/llms.txt Retrieves class dependencies for a given system and class, with an option to specify the module and depth of the search. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/classes/UserService/dependencies?module=core&deep=3" ``` -------------------------------- ### Configure MCP Server Module Build Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Defines the build configuration for the 'mcp-server' module in Kotlin. It sets up necessary plugins, the main application class, and lists project and external dependencies for the server, including Ktor for the HTTP server and Kotlinx for serialization. ```kotlin // mcp-server/build.gradle.kts plugins { id("org.jetbrains.kotlin.jvm") id("org.jetbrains.kotlin.plugin.serialization") application } application { mainClass.set("org.archguard.mcp.MainKt") } dependencies { // ArchGuard dependencies implementation(project(":rule-core")) implementation(project(":rule-linter:rule-code")) implementation(project(":rule-linter:rule-webapi")) implementation(project(":rule-linter:rule-sql")) implementation(project(":rule-linter:rule-test")) implementation(project(":rule-linter:rule-layer")) implementation(project(":scanner_core")) // Ktor for HTTP server implementation("io.ktor:ktor-server-core:2.3.7") implementation("io.ktor:ktor-server-netty:2.3.7") implementation("io.ktor:ktor-server-content-negotiation:2.3.7") implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7") // Kotlin coroutines implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3") // JSON serialization (already in rule-core) implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2") // Logging implementation("io.github.microutils:kotlin-logging:3.0.5") implementation("ch.qos.logback:logback-classic:1.4.11") // Testing testImplementation("io.ktor:ktor-server-tests:2.3.7") testImplementation("org.jetbrains.kotlin:kotlin-test") testImplementation("io.mockk:mockk:1.13.8") } tasks { jar { manifest { attributes["Main-Class"] = "org.archguard.mcp.MainKt" } // Create fat JAR from(configurations.runtimeClasspath.get().files.map { if (it.isDirectory) it else zipTree(it) }) duplicatesStrategy = DuplicatesStrategy.EXCLUDE } } ``` -------------------------------- ### Configure Claude Desktop for ArchGuard MCP Server Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This JSON configuration snippet shows how to integrate the ArchGuard MCP Server with Claude Desktop. It specifies the command to run the server and its arguments, enabling communication via stdio mode. ```json { "mcpServers": { "archguard": { "command": "java", "args": [ "-jar", "/path/to/archguard-mcp-server.jar" ] } } } ``` -------------------------------- ### Circular Dependency Detection API: Get Package Circular Dependencies Source: https://context7.com/archguard/archguard/llms.txt Detects and retrieves circular dependencies at the package level for a given system. Supports pagination. ```bash curl -X POST \ -H "Content-Type: application/json" \ -d '{"currentPageNumber": 1, "numberPerPage": 20}' \ http://localhost:8080/api/systems/1/circular-dependency/package ``` -------------------------------- ### Implement ResourceProvider for MCP Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Creates a central ResourceProvider that delegates resource requests to specific resource handlers like RulesResource. This acts as the main entry point for MCP resource operations. ```kotlin class ResourceProvider { private val rulesResource = RulesResource() suspend fun listResources(): Map> { return mapOf("resources" to rulesResource.listResources()) } suspend fun readResource(uri: String): ResourceContent { return when { uri.startsWith("archguard://rules") -> rulesResource.readResource(uri) else -> throw IllegalArgumentException("Unknown resource URI: $uri") } } } ``` -------------------------------- ### Circular Dependency Detection API: Get Module Circular Dependencies Source: https://context7.com/archguard/archguard/llms.txt Detects and retrieves circular dependencies at the module level for a given system. Supports pagination. ```bash curl -X POST \ -H "Content-Type: application/json" \ -d '{"currentPageNumber": 1, "numberPerPage": 20}' \ http://localhost:8080/api/systems/1/circular-dependency/module ``` -------------------------------- ### ArchGuard MCP Server - Lint SQL Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This section demonstrates how to use the `lint_sql` tool to validate SQL statements and database design. ```APIDOC ## POST /tools/call (Lint SQL) ### Description Validates SQL statements and database design against architectural rules. ### Method POST ### Endpoint /tools/call ### Parameters #### Request Body - **method** (string) - Required - Must be "tools/call". - **params** (object) - Required - Parameters for the tool call. - **name** (string) - Required - Must be "lint_sql". - **arguments** (object) - Required - Arguments for SQL linting. - **sql** (string) - Required - The SQL statement(s) to validate. ### Request Example ```json { "method": "tools/call", "params": { "name": "lint_sql", "arguments": { "sql": "CREATE TABLE users (id INT, name VARCHAR);" } } } ``` ### Response #### Success Response (200) - **result** (array) - A list of linting issues found in the SQL code. #### Response Example ```json { "result": [ { "id": "SQL-001", "message": "Table name should be plural.", "severity": "warning", "ruleUrl": "archguard://rules/sql" } ] } ``` ``` -------------------------------- ### Run ArchGuard MCP Server Tests Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This command executes the tests for the ArchGuard MCP Server module using Gradle. It helps ensure the functionality and stability of the server. ```bash ./gradlew :mcp-server:test ``` -------------------------------- ### Coupling Metrics API: Get Class Coupling Metrics Source: https://context7.com/archguard/archguard/llms.txt Calculates and retrieves coupling metrics (fan-in, fan-out, coupling, instability) for a specific class within a module of a system. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/metric/coupling/class?className=UserService&moduleName=core" ``` -------------------------------- ### Class Dependency Analysis: Get Method Callee Details Source: https://context7.com/archguard/archguard/llms.txt Retrieves the callees for methods within a specific class in a system. Supports filtering by module, depth, and inclusion of parent methods. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/classes/OrderService/methods_callees?module=service&deep=3&needParents=true&needIncludeImpl=true" ``` -------------------------------- ### Add MCP Module to Gradle Settings Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md This snippet shows how to include the new 'mcp-server' module in the project's settings.gradle.kts file, making it recognized by the Gradle build system. ```kotlin // settings.gradle.kts include("mcp-server") ``` -------------------------------- ### Custom Slot Configuration for Specific Rules (Test Smell) Source: https://github.com/archguard/archguard/blob/master/scanner_cli/README.md Shows how to configure a custom slot for specific analysis rules, such as 'test smell' or 'webapi' rules. This involves providing a detailed JSON specification for the slot, including its identifier, host, version, JAR file, and class name. ```bash java -jar scanner_cli.jar --language=Kotlin --features=apicalls --output=json --path=server --slot-spec='{"identifier": "rule", "host": "https://github.com/archguard/archguard/releases/download/v2.0.0-alpha.17", "version": "2.0.0-alpha.17", "jar": "rule-webapi-2.0.0-alpha.17-all.jar", "className": "org.archguard.linter.rule.webapi.WebApiRuleSlot", "slotType": "rule"}' ``` -------------------------------- ### Get File Extension with Caching Source: https://github.com/archguard/archguard/blob/master/analyser_estimate/src/test/resources/kotlin/LanguageService.kt.txt This function retrieves the file extension for a given filename, with caching to improve performance. It handles cases with no extension, trailing dots, and multiple extensions by intelligently parsing the filename. ```Kotlin fun getExtension(name: String): String { val lowercase = name.lowercase() var extension = extensionCache[lowercase] if (extension != null) { return extension } val ext = File(name).extension if (ext == "" || name.last() == '.') { extension = name } else { // Handling multiple dots or multiple extensions only needs to delete the last extension // and then call filepath.Ext. // If there are multiple extensions, it is the value of subExt, // otherwise subExt is an empty string. val subExt = File(name.removeSuffix(".$ext")).extension extension = "$subExt.$ext".removePrefix(".") } extensionCache[name] = extension return extension } ``` -------------------------------- ### Available Rule Sets Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-proposal.md Retrieves all available rule sets and their configurations, including details about each rule's category, ID, name, description, and severity. ```APIDOC ## GET archguard://rules ### Description Returns all available rule sets and their configurations. ### Method GET ### Endpoint archguard://rules ### Parameters None ### Request Example None ### Response #### Success Response (200) - **contents** (array) - List of rule categories, each containing a list of rules. - **category** (string) - The category of the rules (e.g., "code", "webapi"). - **rules** (array) - List of rules within the category. - **id** (string) - Unique identifier for the rule. - **name** (string) - Human-readable name of the rule. - **description** (string) - Detailed explanation of the rule. - **severity** (string) - The severity level of the rule (e.g., "WARN", "ERROR"). #### Response Example ```json { "uri": "archguard://rules", "name": "Available Linting Rules", "description": "Complete list of architectural rules", "mimeType": "application/json", "contents": [ { "category": "code", "rules": [ { "id": "service-should-use-domain-model", "name": "Service Should Use Domain Model", "description": "Service layer should use domain objects, not data layer objects", "severity": "WARN" } ] }, { "category": "webapi", "rules": [ { "id": "no-http-method-in-url", "name": "No HTTP Method in URL", "description": "HTTP method should not be part of the URL path", "severity": "ERROR" } ] } ] } ``` ``` -------------------------------- ### Class Dependency Analysis: Get Class Method Invocations Source: https://context7.com/archguard/archguard/llms.txt Retrieves method invocation details (callers and callees) for a specific class within a system. Allows specifying module, depth, and inclusion of implementation details. ```bash curl -X GET \ "http://localhost:8080/api/systems/1/classes/UserService/invokes?module=core&deep=3&callerDeep=2&calleeDeep=4&needIncludeImpl=true" ``` -------------------------------- ### Build ArchGuard MCP Server Docker Image Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md These bash commands are used to build the Docker image for the ArchGuard MCP Server. The first command builds the image with the tag 'archguard/mcp-server:latest'. ```bash # Build docker build -t archguard/mcp-server:latest . # Run (stdio mode) docker run -i archguard/mcp-server:latest # Run (HTTP mode) docker run -p 127.0.0.1:8080:8080 -e MCP_MODE=http archguard/mcp-server:latest ``` -------------------------------- ### System Management API Source: https://context7.com/archguard/archguard/llms.txt Endpoints for creating, retrieving, and deleting systems within the ArchGuard platform. ```APIDOC ## GET /api/system-info ### Description Retrieves a list of all systems managed by ArchGuard. ### Method GET ### Endpoint /api/system-info ## POST /api/system-info ### Description Registers a new system for analysis. ### Method POST ### Request Body - **systemName** (String) - Required - Name of the system. - **repo** (String) - Required - Repository URL. - **repoType** (String) - Required - Type of repository (e.g., GIT). - **language** (String) - Required - Primary language. ### Response #### Success Response (200) - **id** (Long) - The generated system ID. ``` -------------------------------- ### Build ArchGuard MCP Server JAR Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This command builds the fat JAR for the ArchGuard MCP Server using Gradle. The resulting JAR file contains all necessary dependencies and can be used for deployment. ```bash ./gradlew :mcp-server:shadowJar ``` -------------------------------- ### Manage Tools with ToolRegistry Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Provides a central registry for registering and executing available tools. It maps tool names to their implementations and handles the dispatching of execution requests. ```kotlin class ToolRegistry { private val tools = mutableMapOf() init { register(LintCodeTool()) } private fun register(tool: Tool) { tools[tool.definition().name] = tool } fun listTools(): Map> { return mapOf("tools" to tools.values.map { it.definition() }) } suspend fun executeTool(name: String, arguments: JsonObject?): ToolResult { val tool = tools[name] ?: throw IllegalArgumentException("Tool not found: $name") return tool.execute(arguments) } } ``` -------------------------------- ### Implement Prompt Registry for MCP Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md Defines the PromptRegistry class to manage and retrieve prompt definitions. It uses Kotlin serialization to structure prompt metadata and arguments for LLM interactions. ```kotlin package org.archguard.mcp.prompts import kotlinx.serialization.Serializable @Serializable data class PromptDefinition( val name: String, val description: String, val arguments: List = emptyList() ) @Serializable data class PromptArgument( val name: String, val description: String, val required: Boolean = false ) class PromptRegistry { private val prompts = mutableMapOf() init { registerDefaultPrompts() } private fun registerDefaultPrompts() { prompts["analyze-architecture"] = PromptDefinition( name = "analyze-architecture", description = "Analyze the architecture of a codebase", arguments = listOf( PromptArgument("path", "Path to the codebase", required = true), PromptArgument("aspects", "Focus areas (code quality, API design, etc.)", required = false) ) ) } fun getPrompt(name: String): PromptDefinition { return prompts[name] ?: throw IllegalArgumentException("Prompt not found: $name") } } ``` -------------------------------- ### Scanner CLI: Software Composition Analysis (SCA) (Bash) Source: https://context7.com/archguard/archguard/llms.txt Performs Software Composition Analysis (SCA) to identify project dependencies for security and compliance. Supports various package managers including Maven, Gradle, NPM, and Go. Requires project path, system ID, and server URL. ```bash java -jar scanner_cli-2.3.0-all.jar \ --type=SCA \ --language=java \ --system-id=1 \ --server-url=http://localhost:8080 \ --path=/path/to/project \ --output=http ``` -------------------------------- ### Query Data with Apache Spark Streaming Source: https://github.com/archguard/archguard/blob/master/architecture-as-code/repl-api/README.md Shows how to perform aggregations on a streaming dataset and output the results to the console or an in-memory table. ```java Dataset aggDF = df.groupBy("device").count(); aggDF .writeStream() .outputMode("complete") .format("console") .start(); aggDF .writeStream() .queryName("aggregates") .outputMode("complete") .format("memory") .start(); spark.sql("select * from aggregates").show(); ``` -------------------------------- ### Configure ArchGuard MCP Server for Claude Desktop Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-issue.md This JSON configuration snippet defines the MCP server settings for integration with the Claude Desktop application. It specifies the command and arguments required to execute the ArchGuard MCP server JAR file. ```json { "mcpServers": { "archguard": { "command": "java", "args": ["-jar", "/path/to/archguard-mcp-server.jar"] } } } ``` -------------------------------- ### MCP Protocol Resources and Tools Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-issue.md Details the available resources and tools exposed by the MCP server for interacting with the linter. ```APIDOC ## MCP Protocol Details ### Resources - `archguard://rules` - List all available linting rules. - `archguard://rules/{category}` - List rules for a specific category. ### Tools - `lint_code` - Analyze code quality issues. - `lint_webapi` - Check REST API design. - `lint_sql` - Validate SQL and database design. - `lint_test` - Analyze test code quality. - `lint_layer` - Check layer architecture. - `lint_all` - Run all applicable linters. ### Prompts - `analyze-architecture` - Template for full architectural analysis. - `fix-issues` - Template for reviewing and fixing linting issues. ``` -------------------------------- ### Implement LintCodeTool for Code Analysis Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-implementation-guide.md A concrete implementation of the Tool interface that performs code quality analysis. It defines the input schema for project paths and languages, and executes linting logic using ArchGuard's internal rule engine. ```kotlin class LintCodeTool : Tool { override fun definition() = ToolDefinition( name = "lint_code", description = "Analyze code quality issues using ArchGuard rules", inputSchema = buildJsonObject { put("type", "object") put("properties", buildJsonObject { put("path", buildJsonObject { put("type", "string") put("description", "Path to the project directory") }) put("language", buildJsonObject { put("type", "string") put("description", "Programming language (java, kotlin, etc.)") }) put("rules", buildJsonObject { put("type", "array") put("description", "List of rule IDs to apply, or ['all']") }) }) put("required", buildJsonArray { add("path") }) } ) override suspend fun execute(arguments: JsonObject?): ToolResult { val path = arguments?.get("path")?.jsonPrimitive?.content ?: throw IllegalArgumentException("Missing required parameter: path") val language = arguments["language"]?.jsonPrimitive?.content ?: "java" val rules = arguments["rules"]?.jsonArray?.map { it.jsonPrimitive.content } ?: listOf("all") val issues = performLinting(path, language, rules) val resultText = formatIssues(issues) return ToolResult(content = listOf(ToolContent(text = resultText))) } } ``` -------------------------------- ### Manage Dashboard Metrics and Reports Source: https://context7.com/archguard/archguard/llms.txt Retrieve system overview metrics or trigger the generation of new analysis reports via the dashboard API. ```bash curl -X GET http://localhost:8080/api/systems/1/dashboard curl -X POST http://localhost:8080/api/systems/1/dashboard ``` -------------------------------- ### Scanner CLI: Architecture Analysis (Bash, Curl) Source: https://context7.com/archguard/archguard/llms.txt Generates architecture analysis reports, including tech stack detection and layered architecture identification. Supports structure caching and uploading reports to the ArchGuard server via a POST request. ```bash java -jar scanner_cli-2.3.0-all.jar \ --type=ARCHITECTURE \ --language=kotlin \ --with-structure-cache \ --output=json \ --path=/path/to/project ``` ```bash curl -X POST \ -H "Content-Type: application/json" \ -d @0_architecture.json \ http://localhost:8080/api/scanner/1/reporting/architecture ``` -------------------------------- ### Scanner CLI: Basic Source Code Analysis (Java, Kotlin) Source: https://context7.com/archguard/archguard/llms.txt Performs source code analysis using the ArchGuard Scanner CLI, detecting API calls and data maps. Supports pushing results to a server or saving locally as JSON, CSV, or console output. Requires specifying the project path, server URL, and system ID. ```bash java -jar scanner_cli-2.3.0-all.jar \ --type=SOURCE_CODE \ --language=Java \ --features=apicalls \ --features=datamap \ --path=/path/to/project \ --server-url=http://localhost:8080 \ --system-id=1 \ --output=http ``` ```bash java -jar scanner_cli-2.3.0-all.jar \ --language=Kotlin \ --features=apicalls \ --output=http \ --output=json \ --path=. \ --server-url=http://localhost:8080 ``` -------------------------------- ### Define MCP Server Dependencies Source: https://github.com/archguard/archguard/blob/master/doc/mcp/mcp-server-proposal.md Lists the required Kotlin dependencies for the MCP server module, including rule-core libraries and Ktor for network communication. ```kotlin dependencies { implementation(project(":rule-core")) implementation(project(":rule-linter:rule-code")) implementation(project(":rule-linter:rule-webapi")) implementation(project(":rule-linter:rule-sql")) implementation(project(":rule-linter:rule-test")) implementation(project(":rule-linter:rule-layer")) implementation("io.ktor:ktor-server-core:2.3.7") implementation("io.ktor:ktor-server-netty:2.3.7") implementation("io.ktor:ktor-server-content-negotiation:2.3.7") implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7") } ``` -------------------------------- ### ArchGuard MCP Server - Lint Web API Source: https://github.com/archguard/archguard/blob/master/mcp-server/README.md This section demonstrates how to use the `lint_webapi` tool to check REST API design. ```APIDOC ## POST /tools/call (Lint Web API) ### Description Analyzes REST API design for adherence to architectural standards. ### Method POST ### Endpoint /tools/call ### Parameters #### Request Body - **method** (string) - Required - Must be "tools/call". - **params** (object) - Required - Parameters for the tool call. - **name** (string) - Required - Must be "lint_webapi". - **arguments** (object) - Required - Arguments for the web API linting. - **path** (string) - Required - The path to the project or API definitions. - **apis** (array) - Required - A list of API definitions to analyze. - **name** (string) - Required - The name of the API. - **resources** (array) - Required - A list of API resources. - **url** (string) - Required - The API endpoint URL. - **method** (string) - Required - The HTTP method (e.g., "GET", "POST"). ### Request Example ```json { "method": "tools/call", "params": { "name": "lint_webapi", "arguments": { "path": "/path/to/project", "apis": [ { "name": "UserService", "resources": [ { "url": "/api/users", "method": "GET" } ] } ] } } } ``` ### Response #### Success Response (200) - **result** (array) - A list of linting issues found in the API design. #### Response Example ```json { "result": [ { "id": "WEBAPI-001", "message": "API endpoint should use plural nouns for collections.", "severity": "warning", "ruleUrl": "archguard://rules/webapi" } ] } ``` ``` -------------------------------- ### Process Data with Apache Spark Source: https://github.com/archguard/archguard/blob/master/architecture-as-code/repl-api/README.md Demonstrates reading a JSON file and performing basic filtering and selection operations using the Spark Java API. ```java Dataset df = spark.read().json("logs.json"); df.where("age > 21") .select("name.first").show(); ```