agentleFS
streamshubstreamshub/streamshub-mcp/AGENTS.md

streamshub-mcp

AGENTS.md4 starsChanged 2 months agoApache-2.0View on GitHub

Multi-module Quarkus mono-repo providing MCP (Model Context Protocol) servers for Kubernetes-based streaming platforms. Java 21, Quarkus 3.x, Strimzi API 1.0.x, Fabric8 Kubernetes client. CRITICAL: When implementing new features or modifying existing functionality, you MUST update the relevant documentation: Documentation updates are mandatory and must be completed before the task is considered done. Checkstyle runs during compile phase. Fix all violations before committing.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

64 rules. About 0 are common, 22 are distinctive, and 42 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈22

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 42

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    CRITICAL: When implementing new features or modifying existing functionality, you MUST update the relevant documentation:

    line 14
  2. Very specific:

    Add entries under the ## [Unreleased] section using Keep a Changelog categories: Added, Changed, Deprecated, Removed, Fixed, Security

    line 34
  3. Distinctive:

    Tools: call domain services and return typed responses.

    line 214
  4. Very specific:

    Every tool method is annotated with @WithSpan("tool.<tool_name>") where the span name matches the @Tool(name = ...) value.

    line 280
  5. Very specific:

    All tools declare @Tool.Annotations nested inside @Tool(...

    line 294
  6. Very specific:

    All tool methods use native @ToolGuardrails to attach a guardrail palette:

    line 301
  7. Very specific:

    Every tool method is annotated with @MetaField annotations from io.quarkiverse.mcp.server.MetaField to provide structured metadata in the …

    line 335
  8. Very specific:

    Use snake_case: list_kafka_clusters, get_kafka_topic, get_kafka_bootstrap_servers

    line 357
  9. Very specific:

    Use StrimziToolsPrompts constants for shared parameter descriptions (NS_DESC, CLUSTER_DESC, etc.)

    line 360
  10. Distinctive:

    No filler phrases ("Perfect for...", "Essential for...", "Use this to...")

    line 365
  11. Very specific:

    Use string concatenation for multi-line: "First part." + " Second part."

    line 367
  12. Distinctive:

    Phase 1 — Initial data gathering: Always runs. Gathers cluster status, node pools, pods.

    line 449
  13. Distinctive:

    If namespace is ambiguous and Elicitation is supported, asks the user to choose.

    line 450
  14. Distinctive:

    Phase 2 — Deep investigation: If Sampling is supported, sends Phase 1 results to LLM and asks which areas need deeper investigation.

    line 451
  15. Very specific:

    Pod filtering: When collecting cluster logs, the service identifies problematic pods (not Running, not ready, or restart count > …

    line 453
  16. Distinctive:

    If problematic pods exist, logs are collected only from those pods.

    line 455
  17. Distinctive:

    Phase 3 — Analysis: If Sampling is supported, sends all gathered data to LLM for root cause analysis.

    line 461
  18. Distinctive:

    Use between discrete workflow steps (after gathering data, before next phase)

    line 496
  19. Distinctive:

    Use poll-based for synchronous code paths (gathering data, parsing responses, building reports)

    line 505
  20. Distinctive:

    Use push-based for async operations (Sampling, Elicitation, long-running external API calls)

    line 506
  21. Very specific:

    All cancellation-aware overloads accept an optional AtomicBoolean cancelled parameter.

    line 540
  22. Very specific:

    Create the report DTO in strimzi-mcp/src/.../strimzi/dto/

    line 564
  23. Very specific:

    Create the diagnostic service in strimzi-mcp/src/.../strimzi/service/ extending BaseDiagnosticService (common/) — provides objectMapper, …

    line 565
  24. Very specific:

    Add the @Tool method to DiagnosticTools

    line 569
  25. Very specific:

    Add the tool name to McpDiscoveryTest.testToolDiscovery() expected list

    line 570
  26. Very specific:

    Create a service test in strimzi-mcp/src/test/.../strimzi/service/

    line 571
  27. Distinctive:

    Use specific resource names in log messages and client notifications:

    line 576
  28. Very specific:

    Use StrimziToolsPrompts.systemMessage() for consistent persona across all prompts

    line 629
  29. Very specific:

    Use CompletionService (strimzi) for domain-specific completions

    line 684
  30. Very specific:

    Use CompletionHelper (common) for generic Kubernetes completions (namespaces, etc.)

    line 685
  31. Distinctive:

    Every tool accepts an optional namespace.

    line 740
  32. Very specific:

    Use InputUtils.normalizeInput() for all user-supplied strings (namespace, cluster name, etc.).

    line 742
  33. Distinctive:

    Never return error objects.

    line 760
  34. Very specific:

    Use @JsonProperty with snake_case names on every field

    line 781
  35. Very specific:

    Use @JsonInclude(JsonInclude.Include.NON_NULL) to omit null fields

    line 782
  36. Distinctive:

    All URI patterns are defined once here — never hardcode URI strings elsewhere.

    line 811
  37. Very specific:

    Before adding a new constant, check if it already exists in ResourceLabels, ProcessRoles, KafkaListenerType, or other Strimzi API classes.

    line 814
  38. Distinctive:

    Import order: third-party, javax, java, static (alphabetical within groups, blank line between)

    line 824
  39. Distinctive:

    All public types, methods, and fields require Javadoc

    line 825
  40. Very specific:

    Use final on method parameters

    line 831
  41. Very specific:

    Use if/else over multi-line ternary operators.

    line 832
  42. Very specific:

    Use InputUtils.normalizeInput() for all user-supplied input

    line 834
  43. Very specific:

    Prefer List.of() for empty immutable lists

    line 835
  44. Very specific:

    Use LOG.infof() / LOG.debugf() (JBoss logging with format strings)

    line 836
  45. Distinctive:

    Every file must end with a newline (trailing newline).

    line 838
  46. Distinctive:

    Keep descriptions concise, start with a verb or noun (not "This method...")

    line 846
  47. Very specific:

    Use {@code ...} for inline code references

    line 847
  48. Very specific:

    Create or update the DTO record in strimzi-mcp/src/.../strimzi/dto/

    line 852
  49. Very specific:

    Add the service method to the appropriate domain service in strimzi-mcp/src/.../strimzi/service/

    line 853
  50. Very specific:

    Add the @Tool method to the corresponding tools class in strimzi-mcp/src/.../strimzi/tool/

    line 854
  51. Very specific:

    Add @MetaField(name = ToolMetaFields.COMPOSITE, value = "true", type = MetaField.Type.BOOLEAN) for composite tools

    line 856
  52. Very specific:

    Add expected metadata to McpDiscoveryTest.testToolMetadata() maps

    line 858
  53. Very specific:

    Run ./mvnw compile to verify checkstyle + compilation

    line 859
  54. Very specific:

    Run ./mvnw test to verify tests pass

    line 860
  55. Very specific:

    Create a new directory at the repo root (e.g., new-module/)

    line 864
  56. Very specific:

    Add pom.xml with parent reference to streamshub-mcp

    line 865
  57. Very specific:

    Add module to parent pom.xml <modules> list

    line 867
  58. Very specific:

    Add META-INF/beans.xml to src/main/resources/ for CDI bean discovery

    line 868
  59. Very specific:

    Every test calls MCP tools via McpAssured.McpStreamableTestClient and validates the JSON responses.

    line 880
  60. Very specific:

    Never write a tool call assertion that only checks !isError().

    line 884
  61. Distinctive:

    Check that the response contains the correct resource name and namespace — not just that fields exist:

    line 921
  62. Distinctive:

    When the test deploys a known number of resources, verify the response count:

    line 934
  63. Distinctive:

    Every tool call must log its response for debugging CI failures.

    line 943
  64. Very specific:

    Don't use .toString().contains("value") to check array contents.

    line 969

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

Project: StreamsHub MCP (Multi-Module)

Multi-module Quarkus mono-repo providing MCP (Model Context Protocol) servers for Kubernetes-based streaming platforms. Java 21, Quarkus 3.x, Strimzi API 1.0.x, Fabric8 Kubernetes client.

Documentation Structure

  • User docs: docs/ -- Installation, configuration, usage, and troubleshooting for end users. Each MCP server has its own subdirectory (e.g., docs/strimzi-mcp/).
  • Developer docs: This file (AGENTS.md) -- Architecture, patterns, and conventions for developers
  • Coding agent skills: .agents/skills/ -- Reusable skill files for coding agents (code review, test coverage, tool creation guides, system test guide). Referenced by Claude Code, Bob, Cursor, GitHub Copilot, and Windsurf.

Documentation Update Requirements

CRITICAL: When implementing new features or modifying existing functionality, you MUST update the relevant documentation:

  1. User documentation (docs/) -- Update when:
    • Adding new MCP tools, prompts, or resource templates
    • Changing tool parameters or behavior
    • Modifying configuration options
    • Adding new features visible to end users
  2. This file (AGENTS.md) -- Update when:
    • Changing architecture or design patterns
    • Adding new modules or services
    • Changing coding standards
    • Introducing new architectural layers
    • Modifying development workflows
  3. Changelog (CHANGELOG.md) -- Update when:
    • Adding, changing, or removing tools, prompts, or resource templates
    • Fixing bugs
    • Changing configuration options or defaults
    • Making any user-visible change
    • Add entries under the ## [Unreleased] section using Keep a Changelog categories: Added, Changed, Deprecated, Removed, Fixed, Security
  4. Developer documentation (dev/docs/) -- Update when:
    • Changing build, test, or CI workflows (TESTING.md)
    • Changing release process or scripts (RELEASING.md)
    • Modifying development environment setup or tooling
  5. MCP tool test plan (dev/test-plans/strimzi-mcp-tool-test-plan.md) -- Update when:
    • Adding, modifying, or removing MCP tools (add/update test cases for the tool)
    • Changing tool parameters or behavior (update expected parameters and results)
    • Modifying dev environment resources (dev/) such as Kafka clusters, topics, users, connectors, or other Strimzi resources (update expected values in test cases and the dev deployment reference section)
    • Adding new optional dev components (add a new test phase or test cases)

Documentation updates are mandatory and must be completed before the task is considered done.

Modules

  • common (streamshub-mcp-common) - Generic Kubernetes helpers, DTOs, MCP framework utilities shared across modules
  • metrics-prometheus (streamshub-metrics-prometheus) - Prometheus/Thanos metrics provider (pluggable, replaceable JAR)
  • loki-log-provider (streamshub-loki-log-provider) - Loki log provider (pluggable, replaceable JAR)
  • elasticsearch-log-provider (streamshub-elasticsearch-log-provider) - Elasticsearch/OpenSearch log provider (pluggable, replaceable JAR)
  • strimzi-mcp (strimzi-mcp) - MCP Server for Strimzi: Kafka management tools and services

Build & Test

./mvnw compile                      # compile all modules + checkstyle
./mvnw test                         # unit tests (no live cluster needed)
./mvnw verify -Pcoverage            # tests with JaCoCo coverage (reports in target/site/jacoco/)
./mvnw quarkus:dev -pl strimzi-mcp  # dev mode on http://localhost:8080/mcp

Checkstyle runs during compile phase. Fix all violations before committing.

Architecture

Common module (common/)

io.streamshub.mcp.common.
├── auth/           → AbstractAuthFilter (base JAX-RS client request filter for outgoing API auth),
│                     AuthConfig (auth mode + token/credential config),
│                     AuthHelper (reads SA token and builds Authorization headers)
├── config/         → KubernetesConstants (labels, conditions, phases, health status),
│                     ToolMetaFields (type/resource/composite meta field name constants)
├── dto/            → PodSummaryResponse, PodLogsResult, LogCollectionParams (generic pod DTOs),
│                     ConditionInfo (serialisable Kubernetes condition record),
│                     ReplicasInfo (desired/ready/available replica counts),
│                     ResourceEventsResult (event list with metadata),
│                     ResourceInfo (generic name/namespace/status summary),
│                     PaginatedResponse (generic paginated list wrapper)
│   └── metrics/    → MetricSample, PodTarget, MetricsQueryParams, AggregatedTimeSeries,
│                     AggregationLevel (PARTITION→TOPIC→BROKER→CLUSTER hierarchy),
│                     MetricTimeSeries (labeled metric series with sample list),
│                     TimeSeriesSummary (min/max/avg/latest summary over a series)
├── guardrail/      → ArgumentSanitizationGuardrail, AbstractRateLimitGuardrail,
│                     GeneralRateLimitGuardrail, LogRateLimitGuardrail, MetricsRateLimitGuardrail,
│                     LogRedactionGuardrail, ResponseSizeLimitGuardrail, GuardedResponses,
│                     JsonNodeSanitizer (recursive text-node transformer for redaction)
├── observability/  → McpTrafficLogger (MCP protocol traffic listener for DEBUG logging),
│                     MeasuredTool (@InterceptorBinding), ToolMetricsInterceptor (records tool-call
│                     metrics around every outcome, incl. thrown McpException), ToolCallMetricsRecorder
│                     (Micrometer recorder), ToolCallOutcome (success/protocol_error/tool_error/rate_limited)
├── readiness/      → KubernetesConnectionReadinessCheck (health check for kube API)
├── service/        → KubernetesResourceService, PodsService, DeploymentService, CompletionHelper,
│   │                 CompletionCache (TTL-based cache for completion results),
│   │                 DiagnosticHelper (shared MCP framework utilities for diagnostic tools),
│   │                 BaseDiagnosticService (abstract base for all diagnostic services;
│   │                   injects ObjectMapper + token/log config; provides performSampling/Analysis/Triage),
│   │                 KubernetesEventsService (query Kubernetes events by resource name and kind),
│   │                 KubernetesQueryException (typed exception for Kubernetes API failures)
│   ├── log/        → LogCollectionService, LogCollectorProvider, KubernetesLogProvider,
│   │                 LogFilterUtils (shared keyword/regex log line filtering),
│   │                 LogQueryException (typed exception for log collection failures)
│   └── metrics/    → MetricsProvider (interface), PodScrapingMetricsProvider, MetricsQueryService,
│                     MetricsQueryException (typed exception for metrics query failures)
└── util/           → InputUtils,
│                     NamespaceElicitationHelper (namespace disambiguation via MCP Elicitation),
│                     TimeRangeValidator (validates rangeMinutes vs absolute startTime/endTime),
│                     CertificateUtils (parse and inspect X.509 certificate metadata),
│                     ExceptionUtils (extract root-cause message without Java class names),
│                     PaginationUtils (offset/limit helpers for paginated list responses)
    └── metrics/    → PrometheusTextParser, MetricLabelFilter,
                      CommonLabelExtractor (extracts shared labels from a set of metric samples),
                      TimeSeriesCompressor (compresses constant-value runs in time series)

Prometheus metrics module (metrics-prometheus/)

io.streamshub.mcp.metrics.prometheus.
├── dto/       → PrometheusResponse
├── service/   → PrometheusClient, PrometheusAuthFilter, PrometheusMetricsProvider
└── util/      → PromQLSanitizer

Loki log provider module (loki-log-provider/)

io.streamshub.mcp.loki.
├── config/    → LokiConfig (label mapping, auth mode)
├── service/   → LokiClient, LokiAuthFilter
├── util/      → LogQLSanitizer
└── LokiLogProvider (implements LogCollectorProvider)

Elasticsearch log provider module (elasticsearch-log-provider/)

io.streamshub.mcp.elasticsearch.
├── config/    → ElasticsearchConfig (field mapping, auth mode, index pattern)
├── service/   → ElasticsearchClient, ElasticsearchAuthFilter
├── util/      → ElasticsearchQuerySanitizer
├── ElasticsearchResponse (response record with nested Hit record)
└── ElasticsearchLogProvider (implements LogCollectorProvider)

MCP Server for Strimzi module (strimzi-mcp/)

io.streamshub.mcp.strimzi.
├── tool/              → MCP tool definitions (thin wrappers, no logic)
│   ├── kafka/         → KafkaTools, KafkaConfigurationTools
│   ├── kafkatopic/    → KafkaTopicTools
│   ├── kafkauser/     → KafkaUserTools
│   ├── kafkanodepool/ → KafkaNodePoolTools
│   ├── kafkarebalance/ → KafkaRebalanceTools
│   ├── kafkabridge/   → KafkaBridgeTools
│   ├── kafkaconnect/  → KafkaConnectTools, KafkaConnectorTools
│   ├── kafkamirrormaker2/ → KafkaMirrorMaker2Tools
│   ├── draincleaner/  → DrainCleanerTools
│   ├── operator/      → StrimziOperatorTools, StrimziEventsTools
│   ├── diagnostic/    → DiagnosticTools (composite diagnostic tools)
│   └── metrics/       → MetricsTools
├── service/           → Business logic, organized by domain sub-packages
│   ├── kafka/         → KafkaService, KafkaCertificateService, KafkaConfigService,
│   │                    KafkaConfigComparisonService, KafkaClusterOverviewService,
│   │                    KafkaFleetOverviewService, BootstrapMatcher,
│   │                    KafkaClusterDiagnosticService, KafkaConnectivityDiagnosticService,
│   │                    KafkaMetricsDiagnosticService, UpgradeReadinessDiagnosticService
│   ├── kafkatopic/    → KafkaTopicService, KafkaTopicDiagnosticService
│   ├── kafkauser/     → KafkaUserService
│   ├── kafkanodepool/ → KafkaNodePoolService
│   ├── kafkarebalance/ → KafkaRebalanceService
│   ├── draincleaner/  → DrainCleanerService
│   ├── operator/      → StrimziOperatorService, StrimziEventsService,
│   │                    OperatorMetricsDiagnosticService
│   ├── kafkabridge/   → KafkaBridgeService
│   ├── kafkaconnect/  → KafkaConnectService, KafkaConnectorService,
│   │                    KafkaConnectDiagnosticService, KafkaConnectorDiagnosticService
│   ├── kafkamirrormaker2/ → KafkaMirrorMaker2Service,
│   │                    KafkaMirrorMaker2DiagnosticService
│   ├── metrics/       → KafkaMetricsService, KafkaExporterMetricsService,
│   │                    KafkaBridgeMetricsService, KafkaConnectMetricsService,
│   │                    StrimziOperatorMetricsService, CruiseControlMetricsService
│   └── (root)         → CompletionService
├── dto/               → Strimzi response records and diagnostic reports
│   ├── kafkabridge/   → KafkaBridgeResponse, etc.
│   ├── kafkaconnect/  → KafkaConnectResponse, KafkaConnectorResponse, etc.
│   ├── kafkamirrormaker2/ → KafkaMirrorMaker2Response, KafkaMirrorMaker2DiagnosticReport, etc.
│   └── metrics/       → KafkaMetricsResponse, KafkaExporterMetricsResponse,
│                        KafkaBridgeMetricsResponse, KafkaConnectMetricsResponse,
│                        StrimziOperatorMetricsResponse, CruiseControlMetricsResponse
├── prompt/            → MCP prompt templates (DiagnoseClusterIssuePrompt, TroubleshootConnectivityPrompt,
│                        TroubleshootTopicPrompt, TroubleshootConnectPrompt, TroubleshootConnectorPrompt,
│                        TroubleshootBridgePrompt, TroubleshootMirrorMakerPrompt,
│                        AnalyzeKafkaMetricsPrompt, AnalyzeStrimziOperatorMetricsPrompt,
│                        AnalyzeCapacityPrompt, CompareClusterConfigsPrompt, AuditSecurityPrompt,
│                        AssessUpgradeReadinessPrompt, PromptCompletions)
├── resource/          → ResourceSubscriptionManager (Kubernetes watches → MCP notifications)
├── resource/template/ → MCP resource templates and completions (6 templates)
├── config/            → StrimziConstants (labels, resource URIs), StrimziToolsPrompts
│   └── metrics/       → KafkaMetricCategories, KafkaExporterMetricCategories,
│                        KafkaBridgeMetricCategories, KafkaConnectMetricCategories,
│                        StrimziOperatorMetricCategories, CruiseControlMetricCategories (category constants + metric name mappings)
└── util/              → MetricNameResolver, MetricsBackend

Layer rules

  • Tools call domain services and return typed responses. No try/catch, no business logic.
  • Prompts return structured step-by-step instructions referencing tool names. No logic.
  • Resource templates fetch and serialize live Kubernetes state. Thin wrappers over services.
  • Completions delegate to CompletionService / CompletionHelper. No logic.
  • Domain services (strimzi) contain all business logic. Throw structured McpExceptions via the McpErrors factory (not-found, invalid-params, ambiguity) so clients receive machine-readable error.data; see Error handling. Use plain ToolCallException only for errors that should remain failed tool responses (rate-limit, cancellation).
  • Common services are generic Kubernetes helpers shared across modules.
  • DTOs are immutable record types. Use static factory methods (of(), empty()) not constructors directly.
  • Metrics providers implement MetricsProvider interface. Selected via @LookupIfProperty on mcp.metrics.provider. Domain services use MetricsQueryService (in common/) to query metrics — it handles provider lookup, query param construction, and delegation. Do not inject Instance<MetricsProvider> directly in domain services.
  • Metrics aggregation uses AggregatedTimeSeries.fromSamples(samples, level) to group and average metric samples by AggregationLevel (PARTITION → TOPIC → BROKER → CLUSTER). MetricLabelFilter.labelsForAggregation() strips labels at each level. Each *MetricCategories class defines finestLevel() per category so the requested level is clamped to what the category supports. Results include summary statistics (min, max, avg, latest) and time-series compression for constant-value runs.
  • Diagnostic services orchestrate multi-step workflows by calling existing domain services. They use DiagnosticHelper (common/) for MCP framework interactions and NamespaceElicitationHelper (common/) for namespace disambiguation. Individual step failures do not abort the workflow.
  • Metric category constants are defined as public static final String fields in each *MetricCategories class (e.g., KafkaMetricCategories.REPLICATION). Use these constants instead of string literals when referencing metric categories in services, diagnostic tools, or prompts.

MCP Tool Pattern

@Singleton
@MeasuredTool
@WrapBusinessError(value = Exception.class, unless = {ToolCallException.class, McpException.class})
public class XxxTools {

    @Inject
    XxxService xxxService;

    XxxTools() {  // package-private no-arg constructor for CDI
    }

    @WithSpan("tool.verb_noun")
    @Tool(
        name = "verb_noun",
        description = "Short description of what the tool does."
            + " Additional sentence if needed.",
        annotations = @Tool.Annotations(
            readOnlyHint = true,
            destructiveHint = false,
            idempotentHint = true,
            openWorldHint = false
        )
    )
    @ToolGuardrails(
        input  = { GeneralRateLimitGuardrail.class, ArgumentSanitizationGuardrail.class },
        output = { LogRedactionGuardrail.class, ResponseSizeLimitGuardrail.class }
    )
    public TypedResponse toolMethod(
        @ToolArg(description = "...") final String requiredParam,
        @ToolArg(description = "...", required = false) final String optionalParam
    ) {
        return xxxService.operation(optionalParam, requiredParam);
    }
}

OpenTelemetry tracing on tools

Every tool method is annotated with @WithSpan("tool.<tool_name>") where the span name matches the @Tool(name = ...) value. This creates a named parent span for each MCP tool call.

Virtual threads for blocking tool methods

Blocking tool methods — log-collection (get_*_logs) and composite diagnostic/assessment (diagnose_*, compare_*, assess_*) methods — are annotated with @RunOnVirtualThread. These methods perform sequential Kubernetes API calls, selective diagnostic logic, and pod log streaming, which would otherwise block and exhaust the standard Quarkus worker thread pool under concurrent MCP client load. Annotating them with @RunOnVirtualThread offloads execution to virtual threads. The @RunOnVirtualThread annotation sits above @WithSpan in the annotation stack.

Tool Annotations

All tools declare @Tool.Annotations nested inside @Tool(... annotations = @Tool.Annotations(...)) with readOnlyHint = true, destructiveHint = false, idempotentHint = true, openWorldHint = false since all tools are read-only Kubernetes queries. When adding new tools, always include these annotations — MCP clients like ChatGPT default tools to "write" mode without them.

Guardrails

All tool methods use native @ToolGuardrails to attach a guardrail palette:

  • ArgumentSanitizationGuardrail — strips control characters (below U+0020) from string arguments while preserving \n, \t, \r
  • Rate-limit guardrails — throttles calls per category (see below)
  • LogRedactionGuardrail — redacts sensitive patterns from responses (fail-closed: redaction failure returns generic error)
  • ResponseSizeLimitGuardrail — truncates oversized responses to fit mcp.guardrail.max-response-bytes

The guardrails run in the declared order. All 56 @Tool methods use this palette; only the rate-limit guardrail class varies per category.

Tool-call metrics are NOT a guardrail. They are recorded by the @MeasuredTool class-level CDI interceptor (ToolMetricsInterceptor → ToolCallMetricsRecorder), which wraps the whole invocation like @WithSpan tracing. This is deliberate: ToolOutputGuardrail cannot observe thrown McpException protocol errors (the framework skips output-guardrail processing for non-ToolCallException failures), so metrics live in an interceptor to record every outcome consistently. Every tool class carries @MeasuredTool at class level (the ToolGuardrailsEnforcementTest enforces this alongside the @ToolGuardrails palette).

Sitting inside @WrapBusinessError, this interceptor also normalizes error messages: it re-wraps any uncaught business/infrastructure exception as new ToolCallException(e.getMessage(), e). Without this, @WrapBusinessError would wrap via new ToolCallException(cause) — whose message is cause.toString() — and leak the fully-qualified exception class name into the tool response (see ConfigValidationST.assertNoStackTrace). McpException, ToolCallException, and InputRequiredException are propagated unwrapped.

Tool rate limiting

Rate category is chosen by which rate-limit guardrail class a tool lists in its @ToolGuardrails:

  • LogRateLimitGuardrail — for log-collection tools (get_*_logs); throttled by mcp.guardrail.rate-limit.log-rpm
  • MetricsRateLimitGuardrail — for metrics tools (get_*_metrics); throttled by mcp.guardrail.rate-limit.metrics-rpm
  • GeneralRateLimitGuardrail — for all other tools; throttled by mcp.guardrail.rate-limit.general-rpm

Each rate-limit guardrail uses a 60-second sliding window. When the limit is exceeded, the guardrail returns a failed tool response (isError: true) with retry guidance. Default limits are 0 (unlimited); production deployments should set finite limits.

Tool metadata

Every tool method is annotated with @MetaField annotations from io.quarkiverse.mcp.server.MetaField to provide structured metadata in the _meta object of tools/list responses.

Three metadata fields are defined:

  • type — the tool action type: list, get, overview, logs, events, metrics, diagnose, compare, assess, check
  • resource — the Strimzi/Kubernetes resource: kafka, kafkatopic, kafkauser, kafkanodepool, kafkarebalance, strimzi-operator, strimzi-event, drain-cleaner, kafkaconnect, kafkaconnector, kafkabridge, kafkamirrormaker2
  • composite (boolean, only when true) — tool aggregates multiple internal API calls

Type constants are in io.streamshub.mcp.common.config.ToolMetaFields (common module). Resource constants are in io.streamshub.mcp.strimzi.config.StrimziToolResources (strimzi module).

@MetaField(name = ToolMetaFields.TYPE, value = ToolMetaFields.Types.LIST)
@MetaField(name = ToolMetaFields.RESOURCE, value = StrimziToolResources.KAFKA)
@Tool(name = "list_kafka_clusters", description = "...")

Tool naming

  • Use snake_case: list_kafka_clusters, get_kafka_topic, get_kafka_bootstrap_servers
  • Pattern: verb_resource (list, get)
  • Namespace is always optional via @ToolArg(required = false)
  • Use StrimziToolsPrompts constants for shared parameter descriptions (NS_DESC, CLUSTER_DESC, etc.)

Tool descriptions

  • 1-2 sentences max
  • No filler phrases ("Perfect for...", "Essential for...", "Use this to...")
  • State what it returns, not what it's useful for
  • Use string concatenation for multi-line: "First part." + " Second part."

Tool ordering (tools/list)

tools/list returns tools in a deterministic order. quarkus-mcp-server sorts features by registration timestamp (FeatureInfo.compareTo → createdAt, then name), and the timestamp is fixed at registration, so the order is stable for the lifetime of a running instance and across restarts of the same build. This satisfies the MCP 2026-07-28 "deterministic order" recommendation. McpDiscoveryTest.testToolListingOrderIsDeterministic guards the guarantee. The order is registration/scan order, not alphabetical — the framework comparator is not configurable, so a build-independent alphabetical order is not available without an upstream change (tracked in #265).

The production tool page size is set to quarkus.mcp.server.tools.page-size=100 so the full tool list (56 tools) ships in a single tools/list page rather than the framework default of 50 (which would paginate into two pages).

Tools with progress and cancellation

Long-running tools (e.g., log collection across many pods) accept MCP framework parameters for client feedback. These are injected by the framework — not user-supplied:

@Tool(name = "get_kafka_cluster_logs", description = "...")
public KafkaClusterLogsResponse getKafkaClusterLogs(
    @ToolArg(description = "...") final String clusterName,
    @ToolArg(description = "...", required = false) final String namespace,
    final Progress progress,        // report completion percentage
    final Cancellation cancellation // check if client cancelled mid-operation
) {
    // Build options with callbacks
    LogCollectionParams options = LogCollectionParams.builder(...)
        .cancelCheck(cancellation::skipProcessingIfCancelled)
        .progressCallback(progress.token().isPresent()
            ? (podName, completed, total) -> progress.notificationBuilder()
                .setProgress(completed).setTotal(total)
                .setMessage(String.format("Collecting logs from pod %s (%d/%d)", podName, completed, total))
                .build().sendAndForget()
            : null)
        .build();
    return kafkaService.getClusterLogs(namespace, clusterName, options);
}

Composite Diagnostic Tool Pattern

Composite diagnostic tools orchestrate multi-step workflows in a single tool call. They complement prompt templates: prompts are client-driven (LLM calls tools one by one), composite tools are server-driven (server gathers all data internally).

@Singleton
@MeasuredTool
@WrapBusinessError(value = Exception.class, unless = {ToolCallException.class, McpException.class})
public class DiagnosticTools {

    @Inject
    KafkaClusterDiagnosticService clusterDiagnosticService;

    @Tool(
        name = "diagnose_kafka_cluster",
        description = "..."
    )
    @ToolGuardrails(
        input  = { GeneralRateLimitGuardrail.class, ArgumentSanitizationGuardrail.class },
        output = { LogRedactionGuardrail.class, ResponseSizeLimitGuardrail.class }
    )
    public KafkaClusterDiagnosticReport diagnoseKafkaCluster(
        @ToolArg(description = StrimziToolsPrompts.CLUSTER_DESC) final String clusterName,
        @ToolArg(description = StrimziToolsPrompts.NS_DESC, required = false) final String namespace,
        final Sampling sampling,       // LLM-guided selective investigation
        final Elicitation elicitation,  // namespace disambiguation
        final Progress progress,
        final Cancellation cancellation
    ) {
        return clusterDiagnosticService.diagnose(...);
    }
}

Diagnostic service structure (3-phase workflow)

  1. Phase 1 — Initial data gathering: Always runs. Gathers cluster status, node pools, pods. If namespace is ambiguous and Elicitation is supported, asks the user to choose.
  2. Phase 2 — Deep investigation: If Sampling is supported, sends Phase 1 results to LLM and asks which areas need deeper investigation. If not supported, investigates all areas.
    • Pod filtering: When collecting cluster logs, the service identifies problematic pods (not Running, not ready, or restart count > mcp.diagnostic.restart-threshold, default 3). If problematic pods exist, logs are collected only from those pods. If all pods are healthy, logs are collected from all pods.
    • Time window: The triage LLM recommends a time window for log/event collection — either relative (last N minutes) for active issues, or absolute (start/end ISO 8601) for past incidents. Defaults to 30 minutes. If no errors are found, the window auto-escalates once, then uses Elicitation to ask the user whether to expand further.
  3. Phase 3 — Analysis: If Sampling is supported, sends all gathered data to LLM for root cause analysis. If not supported, returns raw data without analysis.

Key behaviors

  • Graceful degradation: Works without Sampling/Elicitation support (gathers everything, returns raw data)
  • Step failure resilience: Individual step failures are recorded in stepsFailed, workflow continues
  • Progress tracking: Reports progress via DiagnosticHelper.sendProgress()
  • Cancellation: Supports both poll-based (checkCancellation() between steps) and push-based (registerCancellationCallback() for async operations)
  • No duplication: Calls existing domain services (KafkaService, StrimziOperatorService, etc.)
  • Configurable token limits: mcp.sampling.triage-max-tokens and mcp.sampling.analysis-max-tokens
  • OpenTelemetry tracing: Gather/triage/analysis methods are annotated with @WithSpan for distributed tracing. Methods are package-private (not private) so Quarkus ArC subclass-based interception can intercept self-invocations from diagnose(). Span names follow the pattern diagnose.{domain}.{step} (e.g., diagnose.cluster.status, diagnose.connectivity.triage).

DiagnosticHelper (common module)

Shared MCP framework utilities in common/src/.../service/DiagnosticHelper.java:

  • sendProgress(Progress, step, totalSteps, message) — progress update with descriptive message to MCP client
  • checkCancellation(Cancellation) — poll-based cancellation check; throws if client cancelled (use for synchronous code paths)
  • registerCancellationCallback(Cancellation, AtomicBoolean) — push-based cancellation callback; immediately sets flag when cancelled (use for async operations like Sampling/Elicitation)
  • checkAsyncCancellation(AtomicBoolean) — check flag set by callback and throw if cancelled (use after async operations)
  • putIfNotNull(Map, String, Object) — conditional map insertion
  • elicitSelection(Elicitation, message, propertyName, description, options) — generic single-select Elicitation
  • extractSamplingText(SamplingResponse) — safe text extraction from Sampling response
  • MAP_TYPE_REF — reusable TypeReference<Map<String, Object>> for JSON parsing

Cancellation Patterns

Diagnostic services support two cancellation mechanisms:

  1. Poll-based (checkCancellation()) — For synchronous operations
    • Checks if cancellation occurred since the last check
    • Throws immediately if cancelled
    • Use between discrete workflow steps (after gathering data, before next phase)
  2. Push-based (registerCancellationCallback()) — For async operations
    • Registers a callback that fires immediately when cancellation occurs
    • Sets an AtomicBoolean flag that can be checked at any point
    • Suitable for Sampling/Elicitation calls that may take seconds to minutes
    • Catches cancellation during the async call, not just at poll points

When to use each:

  • Use poll-based for synchronous code paths (gathering data, parsing responses, building reports)
  • Use push-based for async operations (Sampling, Elicitation, long-running external API calls)
  • Can mix both — poll-based for sync phases, push-based for async phases

Example usage:

// Register callback once at start of diagnose()
AtomicBoolean cancelled = new AtomicBoolean(false);
DiagnosticHelper.registerCancellationCallback(cancellation, cancelled);

// Check after async operations (sampling/elicitation)
InvestigationAreas areas = performTriage(sampling, ...);
DiagnosticHelper.checkAsyncCancellation(cancelled);  // throws if cancelled

// Continue with poll-based checks for sync phases
DiagnosticHelper.checkCancellation(cancellation);

See KafkaClusterDiagnosticService for complete reference implementation.

BaseDiagnosticService (common module)

Abstract base class in common/src/.../service/BaseDiagnosticService.java that all diagnostic services must extend:

  • Injects ObjectMapper (shared Jackson mapper)
  • Binds mcp.sampling.triage-max-tokens → triageMaxTokens
  • Binds mcp.sampling.analysis-max-tokens → analysisMaxTokens
  • Binds mcp.log.tail-lines → defaultTailLines
  • performSampling(sampling, systemPrompt, data, maxTokens) — sends a Sampling request and returns extracted text
  • performSampling(sampling, systemPrompt, data, maxTokens, cancelled) — overload with push-based cancellation support
  • performAnalysis(sampling, systemPrompt, fullData) — convenience wrapper using analysisMaxTokens
  • performAnalysis(sampling, systemPrompt, fullData, cancelled) — overload with push-based cancellation support
  • performTriage(sampling, systemPrompt, phase1Summary) — sends triage Sampling, parses JSON response to Map
  • performTriage(sampling, systemPrompt, phase1Summary, cancelled) — overload with push-based cancellation support

All cancellation-aware overloads accept an optional AtomicBoolean cancelled parameter. If non-null, the flag is checked before and after the async sendAndAwait() call, returning null if cancelled.

NamespaceElicitationHelper (common module)

Namespace disambiguation in common/src/.../common/util/NamespaceElicitationHelper.java:

  • isMultipleNamespacesError(McpException) — true when the error carries McpErrorData with category AMBIGUOUS
  • elicitNamespace(McpException, Elicitation, context) — reads candidate namespaces from the structured McpErrorData.candidates() and combines with DiagnosticHelper.elicitSelection

Diagnostic services that resolve ambiguity catch McpException (not ToolCallException) around the getCluster/lookup call, gate on isMultipleNamespacesError, and rethrow otherwise.

Diagnostic report DTOs

Compose existing DTOs into a single report. Follow the naming pattern Kafka*DiagnosticReport:

  • KafkaClusterDiagnosticReport — cluster, node pools, pods, operator, logs, events, metrics
  • KafkaConnectivityDiagnosticReport — cluster, bootstrap servers, certificates, pods, logs
  • KafkaMetricsDiagnosticReport — cluster, pods, replication/performance/resource/throughput metrics
  • OperatorMetricsDiagnosticReport — operator, reconciliation/resource/JVM metrics, logs
  • KafkaConnectorDiagnosticReport — connector, parent Connect cluster, pods, logs

Adding a new composite diagnostic tool

  1. Create the report DTO in strimzi-mcp/src/.../strimzi/dto/
  2. Create the diagnostic service in strimzi-mcp/src/.../strimzi/service/ extending BaseDiagnosticService (common/) — provides objectMapper, triageMaxTokens, analysisMaxTokens, defaultTailLines, and the performSampling(), performAnalysis(), performTriage() utility methods
  3. Add the @Tool method to DiagnosticTools
  4. Add the tool name to McpDiscoveryTest.testToolDiscovery() expected list
  5. Create a service test in strimzi-mcp/src/test/.../strimzi/service/
  6. Run ./mvnw compile && ./mvnw test

Logging in diagnostic services

Use specific resource names in log messages and client notifications:

  • "Checked Kafka cluster status" (not "Checked cluster status")
  • "Found 3 KafkaNodePools" (not "Found 3 node pools")
  • "Checked Strimzi operator 'name' status: HEALTHY" (not "Checked operator status")
  • "Collected Kafka cluster logs" (not "Collected cluster logs")
  • "Failed to gather Kafka related events" (not "Failed to gather events")

Stateless clients (MRTR)

Diagnostic and comparison tools support both stateful (SSE) and stateless (streamable HTTP, protocol 2026-07-28) MCP clients. Stateless clients receive LLM analysis via the Multi Round-Trip Request (MRTR) pattern: the service throws io.quarkiverse.mcp.server.InputRequiredException describing the sampling it needs, the client fulfills it with its own LLM, and retries carrying the result in inputResponses().

Key patterns:

  • Transport detection is centralized in DiagnosticHelper.analysisSamplingMrtr() (for analysis) and NamespaceElicitationHelper.elicitNamespaceMrtr() (for namespace disambiguation). Services call BaseDiagnosticService.performAnalysisMrtr(...) or elicitNamespaceMrtr(...) — they never branch on transport type themselves.
  • Triage is stateful-only (SSE). It is a token/scope optimization; stateless clients skip triage (guarded in BaseDiagnosticService.performTriage on isServerInitiatedRequestSupported()) and run analysis over all gathered data. Note Sampling.isSupported() reflects the client's capability and is true even for stateless clients, so the skip must key off isServerInitiatedRequestSupported(), not isSupported().
  • InputRequiredException MUST propagate uncaught AND unwrapped to the framework (it is converted to an input_required JSON-RPC result). Every catch between the service and the framework must pass it through: it is excluded from @WrapBusinessError(unless = ...) on DiagnosticTools and explicitly rethrown ahead of the generic catch (Exception) in DiagnosticHelper.sendSampling/analysisSamplingMrtr. Any new catch (Exception) on the diagnostic path must do the same — treat InputRequiredException exactly like McpException.
  • requestState carries the resolved namespace across round-trips because InputResponses does not accumulate. Pass the gathered resource's resolved namespace as the String requestState argument when calling performAnalysisMrtr. When the primary elicited resource has no namespace accessor (e.g. KafkaTopicResponse), thread the namespace that resolved the gather out to the caller (see KafkaTopicDiagnosticService.TopicStatusResult) rather than falling back to a nullable secondary resource.
  • Namespace disambiguation: The 9 single-namespace diagnostic tools use MRTR elicitation (elicitNamespaceMrtr) when the namespace is ambiguous. compare_kafka_clusters (two namespaces) uses the structured-error fallback (#229) instead — stateless clients re-call with explicit namespace1/namespace2.

Shared helpers:

  • DiagnosticHelper.analysisSamplingMrtr(Sampling, ObjectMapper, String systemPrompt, Map data, int maxTokens, String key, String requestState, AtomicBoolean cancelled) — forks to stateful/stateless paths; requestState is a String (not a map), and cancelled short-circuits the stateful call before/after sendAndAwait()
  • BaseDiagnosticService.performAnalysisMrtr(Sampling, String systemPrompt, Map fullData, String key, String requestState, AtomicBoolean cancelled) — convenience wrapper delegating to analysisSamplingMrtr
  • NamespaceElicitationHelper.elicitNamespaceMrtr(...) — namespace disambiguation via Elicitation (SSE) or MRTR (stateless). It self-guards on isFormModeSupported() and falls back to the structured error otherwise.
  • DiagnosticHelper.effectiveNamespace(...) — resolves namespace from tool arg or requestState

See KafkaClusterDiagnosticService and KafkaConfigComparisonService for reference implementations.

MCP Prompt Template Pattern

Prompt templates encode domain knowledge and guide LLMs through structured workflows. They tell the LLM exactly which tools to call and in what order.

@Singleton
public class XxxPrompt {

    @Prompt(name = "verb-noun", description = "What this workflow does.")
    PromptResponse execute(
        @PromptArg(description = "...") final String requiredParam,
        @PromptArg(description = "...", required = false) final String optionalParam
    ) {
        String instructions = "Step-by-step instructions referencing MCP tools...";
        return PromptResponse.withMessages(List.of(
            PromptMessage.withAssistantRole(StrimziToolsPrompts.systemMessage("domain area")),
            PromptMessage.withUserRole(instructions)
        ));
    }
}
  • Prompt names use kebab-case: diagnose-cluster-issue, troubleshoot-connectivity
  • Return PromptResponse.withMessages(List.of(...)) with two messages:
    1. An assistant-role persona via StrimziToolsPrompts.systemMessage("domain") — sets the SRE expert persona
    2. A user-role task with step-by-step instructions
  • Use StrimziToolsPrompts.systemMessage() for consistent persona across all prompts
  • Reference specific tool names in the instructions so the LLM knows what to call

MCP Resource Template Pattern

Resource templates expose live Kubernetes state as structured JSON that clients can attach to conversations for immediate context — without requiring tool calls.

@Singleton
public class XxxResource {

    @Inject
    XxxService xxxService;

    @ResourceTemplate(
        name = "resource-name",
        uriTemplate = StrimziConstants.ResourceUris.RESOURCE_PATTERN,
        description = "What this resource exposes.",
        mimeType = "application/json"
    )
    String getResource(final String namespace, final String name) {
        // Fetch and serialize resource data
    }
}
  • URI templates use StrimziConstants.ResourceUris.* constants — never hardcode URI strings
  • Return serialized JSON strings
  • Resource names use kebab-case: kafka-cluster-status, kafka-cluster-topology

MCP Completion Pattern

Completions provide IDE-like autocomplete for prompt and resource template parameters by querying Kubernetes in real-time.

@Singleton
public class XxxCompletions {

    @Inject
    CompletionService completionService;

    @CompletePrompt("prompt-name")
    CompletionResponse completePrompt(final CompleteContext context) {
        return completionService.completeByArgName(context);
    }

    @CompleteResourceTemplate("resource-name")
    CompletionResponse completeResource(final CompleteContext context) {
        return completionService.completeByArgName(context);
    }
}
  • Use CompletionService (strimzi) for domain-specific completions
  • Use CompletionHelper (common) for generic Kubernetes completions (namespaces, etc.)

Resource Subscription Pattern

ResourceSubscriptionManager establishes Kubernetes watches on startup and sends notifications/resources/updated to subscribed MCP clients when resource state changes.

  • Watches Kafka CRs, KafkaNodePool CRs, KafkaTopic CRs, KafkaUser CRs, and operator Deployments
  • De-duplicates by comparing serialized JSON against last known state
  • Started/stopped via @Observes StartupEvent / @Observes ShutdownEvent
  • Auto-reconnects with exponential backoff when watches close unexpectedly
  • Periodic reconciliation removes orphaned state for deleted resources
  • Can be disabled via mcp.resource-watches.enabled=false (used in tests)
  • Configuration:
    • mcp.watch.reconnect-initial-delay-ms (default: 1000) — initial reconnect delay
    • mcp.watch.reconnect-max-delay-ms (default: 60000) — maximum reconnect delay
    • mcp.watch.reconnect-max-attempts (default: 10) — maximum reconnect attempts before giving up
    • mcp.watch.reconcile-interval (default: 5m) — interval for orphaned state cleanup

Domain Service Pattern

@ApplicationScoped
public class XxxService {

    @Inject
    KubernetesResourceService k8sService;

    XxxService() {  // package-private no-arg constructor for CDI
    }

    public List<XxxResponse> listItems(final String namespace, final String clusterName) {
        String ns = InputUtils.normalizeInput(namespace);
        String name = InputUtils.normalizeInput(clusterName);

        if (name == null) {
            throw McpErrors.invalidParams("Cluster name is required");
        }

        List<Resource> resources;
        if (ns != null) {
            resources = k8sService.queryResourcesByLabel(Resource.class, ns, LABEL_KEY, name);
        } else {
            resources = k8sService.queryResourcesByLabelInAnyNamespace(Resource.class, LABEL_KEY, name);
        }

        return resources.stream()
            .map(this::createResponse)
            .toList();
    }
}

Namespace handling

Every tool accepts an optional namespace. The service method receives it first, normalizes it, then branches: if non-null query that namespace, if null query all namespaces (auto-discovery). Use InputUtils.normalizeInput() for all user-supplied strings (namespace, cluster name, etc.).

Error handling

Errors fall into two client-visible shapes:

  • Structured JSON-RPC errors (carry machine-readable error.data, i.e. McpErrorData) — build these with the McpErrors factory (common/.../util/McpErrors.java). They propagate unwrapped through @WrapBusinessError (which excludes McpException). Use for:
    • Missing/invalid params: throw McpErrors.invalidParams("Cluster name is required") → code -32602, category INVALID_PARAMS
    • Resource not found: throw McpErrors.notFound("Kafka cluster", name, namespace) → code -32002, category RESOURCE_NOT_FOUND (pass namespace = null for all-namespace searches; name = null when there is no single name)
    • Multiple matches: throw McpErrors.ambiguous("Kafka cluster", name, candidateNamespaces) → code -32602, category AMBIGUOUS (candidates carried in error.data.candidates)
  • Failed tool responses (isError: true, text only) — plain ToolCallException. Use for errors the LLM should reason over as tool output rather than protocol failures: rate-limit (from the rate-limit guardrails) and cancellation (DiagnosticHelper). @WrapBusinessError also wraps any uncaught infrastructure exception into this shape — notably KubernetesResourceService wraps Kubernetes failures (including RBAC/403) in KubernetesQueryException with a contextual message, which surfaces as a failed tool response and lets tools do graceful degradation.
  • Empty list results: return an empty list (not an error).
  • Never return error objects; always throw or return typed responses.

McpErrorData (JSON-RPC error.data, snake_case, nulls omitted): category, resource_kind, resource_name, namespace, candidates, remediation. Keep messages clean (no stack traces / FQCNs — enforced by AbstractST.assertNoStackTrace).

DTO Pattern

@JsonInclude(JsonInclude.Include.NON_NULL)
public record XxxResponse(
    @JsonProperty("name") String name,
    @JsonProperty("namespace") String namespace,
    @JsonProperty("status") String status
) {
    public static XxxResponse of(String name, String namespace, String status) {
        return new XxxResponse(name, namespace, status);
    }
}
  • Use @JsonProperty with snake_case names on every field
  • Use @JsonInclude(JsonInclude.Include.NON_NULL) to omit null fields
  • Provide static factory methods (of(), empty()) for construction
  • Record javadoc uses @param tags for each component

Constants

Constants are split across two modules:

  • KubernetesConstants (common) - standard Kubernetes labels, conditions, phases, container states, resource status, health status, and the generic UNKNOWN fallback value
  • StrimziConstants (strimzi-mcp) - Strimzi-specific label keys, kind values, component types, and operator discovery values

Use Strimzi API constants where available

  • Label keys: use ResourceLabels.STRIMZI_CLUSTER_LABEL, ResourceLabels.STRIMZI_KIND_LABEL, ResourceLabels.STRIMZI_COMPONENT_TYPE_LABEL from io.strimzi.api.ResourceLabels
  • Node pool roles: use ProcessRoles.BROKER.toValue() from io.strimzi.api.kafka.model.nodepool.ProcessRoles
  • Listener types: use KafkaListenerType.INTERNAL.toValue() etc. from io.strimzi.api.kafka.model.kafka.listener.KafkaListenerType

Custom constants (no API equivalent)

  • StrimziConstants.Labels.POOL_NAME - "strimzi.io/pool-name" (not in ResourceLabels)
  • StrimziConstants.KindValues.CLUSTER_OPERATOR - "cluster-operator" (label value, no API constant)
  • StrimziConstants.ComponentTypes.KAFKA - "kafka" (label value, no API constant)
  • StrimziConstants.Operator.APP_LABEL_VALUE - "strimzi" (label value, no API constant)
  • StrimziConstants.ResourceUris.* - MCP resource URI templates and builders (e.g., KAFKA_STATUS, kafkaStatus(namespace, name)). Used in @ResourceTemplate annotations and ResourceSubscriptionManager. All URI patterns are defined once here — never hardcode URI strings elsewhere.
  • KubernetesConstants.* - standard Kubernetes strings not provided by Fabric8 as constants

Before adding a new constant, check if it already exists in ResourceLabels, ProcessRoles, KafkaListenerType, or other Strimzi API classes.

Code Style

Enforced by checkstyle (runs at compile)

  • License header on every Java file (see .checkstyle/checkstyle.xml)
  • No star imports
  • No tabs
  • Import order: third-party, javax, java, static (alphabetical within groups, blank line between)
  • All public types, methods, and fields require Javadoc
  • Locale-sensitive methods must specify locale: .toLowerCase(Locale.ROOT) not .toLowerCase()
  • Max method length: 150 lines, max parameters: 13, max cyclomatic complexity: 19

Conventions

  • Use final on method parameters
  • Use if/else over multi-line ternary operators. Single-line ternaries for simple expressions are fine.
  • Package-private no-arg constructors on CDI beans (not private, not public)
  • Use InputUtils.normalizeInput() for all user-supplied input
  • Prefer List.of() for empty immutable lists
  • Use LOG.infof() / LOG.debugf() (JBoss logging with format strings)
  • No assert statements (checkstyle enforced)
  • Every file must end with a newline (trailing newline). Verify before committing.

Javadoc

  • Required on all public classes, methods, fields, and record components
  • Class-level: brief description of purpose
  • Method-level: describe what it does, @param for each parameter, @return for return value
  • Record-level: describe the record, @param for each component
  • Keep descriptions concise, start with a verb or noun (not "This method...")
  • Use {@code ...} for inline code references
  • Non-empty @param/@return/@throws descriptions (checkstyle enforced)

Adding a New Strimzi Tool

  1. Create or update the DTO record in strimzi-mcp/src/.../strimzi/dto/
  2. Add the service method to the appropriate domain service in strimzi-mcp/src/.../strimzi/service/
  3. Add the @Tool method to the corresponding tools class in strimzi-mcp/src/.../strimzi/tool/
    • Include @MetaField annotations for type (from ToolMetaFields) and resource (from StrimziToolResources)
    • Add @MetaField(name = ToolMetaFields.COMPOSITE, value = "true", type = MetaField.Type.BOOLEAN) for composite tools
  4. Add the tool name to McpDiscoveryTest.testToolDiscovery() expected list
  5. Add expected metadata to McpDiscoveryTest.testToolMetadata() maps
  6. Run ./mvnw compile to verify checkstyle + compilation
  7. Run ./mvnw test to verify tests pass

Adding a New Module

  1. Create a new directory at the repo root (e.g., new-module/)
  2. Add pom.xml with parent reference to streamshub-mcp
  3. Depend on streamshub-mcp-common for shared Kubernetes helpers
  4. Add module to parent pom.xml <modules> list
  5. Add META-INF/beans.xml to src/main/resources/ for CDI bean discovery

Testing

Unit tests use Quarkus test framework with Mockito for Kubernetes client mocking. System tests use kubetest4j against a real Kubernetes cluster and are skipped by default.

For detailed testing documentation including test locations, patterns, system test configuration, and the systemtest module structure, see dev/docs/TESTING.md.

E2E (system test) best practices

System tests live in systemtest/src/test/java/io/streamshub/mcp/systemtest/ and extend AbstractST. Every test calls MCP tools via McpAssured.McpStreamableTestClient and validates the JSON responses.

Always validate response content, not just success/error status

Never write a tool call assertion that only checks !isError(). Every tool call must parse the JSON response and verify at least the key fields. A test that only checks !isError() will pass even if the tool returns garbage data.

// BAD — passes even if response is empty or contains wrong data
mcpClient.when()
    .toolsCall("get_kafka_cluster", args, response -> {
        assertFalse(response.isError(), "should not error");
    })
    .thenAssertResults();

// GOOD — verifies the response contains the expected resource
mcpClient.when()
    .toolsCall("get_kafka_cluster", args, response -> {
        JsonNode root = assertToolSuccess(response);
        LOGGER.info("get_kafka_cluster response:\n{}", response.content().getFirst().asText().text());
        assertEquals(CLUSTER_NAME, root.path("name").asText(), "Cluster name should match");
        assertEquals("Ready", root.path("readiness").asText(), "Cluster should be Ready");
        assertEquals(ns, root.path("namespace").asText(), "Namespace should match");
    })
    .thenAssertResults();

Use AbstractST assertion helpers

AbstractST provides shared helpers — use them instead of repeating the same checks:

  • assertToolSuccess(response) — asserts !isError(), !content.isEmpty(), parses JSON. Use instead of manual assertFalse(response.isError()) + parseJson().
  • assertToolError(response, "not found") — asserts isError() and error message contains substrings (case-insensitive). Use for all error test cases.
  • assertDiagnosticReport(root) — validates steps_completed is non-empty array, timestamp and message present. Use for all diagnose_* and assess_* tool responses.
  • assertPodSummaryResponse(root) — validates total_pods > 0, ready_pods >= 0, health_status and timestamp present. Use for all get_*_pods tool responses.
  • assertLogsResponse(root, "cluster_name", expectedName) — validates resource name field, pods array, log_lines, timestamp, message. Use for all get_*_logs tool responses.
  • assertEventsResponse(root, resourceName, namespace) — validates resource_name, namespace, total_events >= 0, timestamp, message. Use for all get_strimzi_events tool responses.

Always verify resource identity in responses

Check that the response contains the correct resource name and namespace — not just that fields exist:

// BAD — only checks field existence
assertFalse(root.path("name").isMissingNode(), "Should have name");

// GOOD — verifies the actual value
assertEquals(EXPECTED_NAME, root.path("name").asText(), "Name should match");
assertEquals(expectedNamespace, root.path("namespace").asText(), "Namespace should match");

Verify counts in list responses

When the test deploys a known number of resources, verify the response count:

assertEquals(3, nodePools.size(), "Should have 3 node pools (controller-np, broker-np1, broker-np2)");
assertTrue(items.size() >= 3, "Should return at least 3 topics");

Always log tool responses

Every tool call must log its response for debugging CI failures. Use shortened logging for large responses (logs, metrics):

// Normal responses — log full content
LOGGER.info("get_kafka_cluster response:\n{}", response.content().getFirst().asText().text());

// Large responses (logs, metrics) — log length only
LOGGER.info("get_kafka_cluster_logs response (length={})",
    response.content().getFirst().asText().text().length());

Validate error responses properly

Error test cases must verify the error message content, not just that isError() is true:

// BAD — passes even if the error message is "NullPointerException"
assertTrue(response.isError(), "Should error");

// GOOD — verifies the error message is user-friendly
assertToolError(response, "not found");

Parse JSON arrays properly

Don't use .toString().contains("value") to check array contents. Iterate the array:

// BAD
assertTrue(pool.path("roles").toString().contains("controller"));

// GOOD
boolean found = false;
for (JsonNode role : pool.path("roles")) {
    if ("controller".equals(role.asText())) { found = true; break; }
}
assertTrue(found, "roles should contain 'controller'");

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.