streamshub-mcp
AGENTS.md5 starsChanged 20 days 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.3.x, Fabric8 Kubernetes client. CRITICAL: When implementing new features or modifying existing functionality, you MUST update the relevant documentation: Update the relevant ref-*/con-*/proc-* module (for a new tool, the matching documentation/modules/tools/ref-*-tools.adoc) and bump the corresponding count attribute ({ToolCount}, {PromptCount}, {ResourceCount}, {DiagnosticToolCount}) in documentation/shared/attributes.adoc. Never hardcode a tool/prompt/resource count in prose -- use the attribute. Run ./mvnw -N -Pdocs package to verify…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository7 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/add-diagnostic-tool.mdcCursor rule
- .cursor/rules/add-mcp-tool.mdcCursor rule
- .cursor/rules/add-system-test.mdcCursor rule
- .cursor/rules/code-review.mdcCursor rule
- .cursor/rules/test-coverage.mdcCursor rule
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
66 rules. About 0 are common, 22 are distinctive, and 44 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.
44
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 14
CRITICAL: When implementing new features or modifying existing functionality, you MUST update the relevant documentation:
- Very specific: line 22
Update the relevant ref-*/con-*/proc-* module (for a new tool, the matching documentation/modules/tools/ref-*-tools.adoc) and bump the …
- Very specific: line 40
Add entries under the ## [Unreleased] section using Keep a Changelog categories: Added, Changed, Deprecated, Removed, Fixed, Security
- Distinctive: line 258
Tools: call domain services and return typed responses.
- Very specific: line 331
Every tool method is annotated with @WithSpan("tool.<tool_name>") where the span name matches the @Tool(name = ...) value.
- Very specific: line 336
Every @Tool method is annotated with @RunOnVirtualThread.
- Very specific: line 345
All tools declare @Tool.Annotations nested inside @Tool(...
- Very specific: line 352
All tool methods use native @ToolGuardrails to attach a guardrail palette:
- Very specific: line 386
Every tool method is annotated with @MetaField annotations from io.quarkiverse.mcp.server.MetaField to provide structured metadata in the …
- Very specific: line 408
Use snake_case: list_kafka_clusters, get_kafka_topic, get_kafka_bootstrap_servers
- Very specific: line 411
Use StrimziToolsPrompts constants for shared parameter descriptions (NS_DESC, CLUSTER_DESC, etc.)
- Distinctive: line 416
No filler phrases ("Perfect for...", "Essential for...", "Use this to...")
- Very specific: line 418
Use string concatenation for multi-line: "First part." + " Second part."
- Distinctive: line 500
Phase 1 — Initial data gathering: Always runs. Gathers cluster status, node pools, pods.
- Distinctive: line 501
If namespace is ambiguous and Elicitation is supported, asks the user to choose.
- Distinctive: line 502
Phase 2 — Deep investigation: If Sampling is supported, sends Phase 1 results to LLM and asks which areas need deeper investigation.
- Very specific: line 504
Pod filtering: When collecting cluster logs, the service identifies problematic pods (not Running, not ready, or restart count > …
- Distinctive: line 506
If problematic pods exist, logs are collected only from those pods.
- Distinctive: line 512
Phase 3 — Analysis: If Sampling is supported, sends all gathered data to LLM for root cause analysis.
- Distinctive: line 547
Use between discrete workflow steps (after gathering data, before next phase)
- Distinctive: line 556
Use poll-based for synchronous code paths (gathering data, parsing responses, building reports)
- Distinctive: line 557
Use push-based for async operations (Sampling, Elicitation, long-running external API calls)
- Very specific: line 591
All cancellation-aware overloads accept an optional AtomicBoolean cancelled parameter.
- Very specific: line 616
Create the report DTO in strimzi-mcp/src/.../strimzi/dto/
- Very specific: line 617
Create the diagnostic service in strimzi-mcp/src/.../strimzi/service/ extending BaseDiagnosticService (common/) — provides objectMapper, …
- Very specific: line 621
Add the @Tool method to DiagnosticTools
- Very specific: line 622
Add the tool name to McpDiscoveryTest.testToolDiscovery() expected list
- Very specific: line 623
Create a service test in strimzi-mcp/src/test/.../strimzi/service/
- Distinctive: line 628
Use specific resource names in log messages and client notifications:
- Very specific: line 681
Use StrimziToolsPrompts.systemMessage() for consistent persona across all prompts
- Very specific: line 736
Use CompletionService (strimzi) for domain-specific completions
- Very specific: line 737
Use CompletionHelper (common) for generic Kubernetes completions (namespaces, etc.)
- Distinctive: line 800
Every tool accepts an optional namespace.
- Very specific: line 802
Use InputUtils.normalizeInput() for all user-supplied strings (namespace, cluster name, etc.).
- Distinctive: line 820
Never return error objects.
- Very specific: line 841
Use @JsonProperty with snake_case names on every field
- Very specific: line 842
Use @JsonInclude(JsonInclude.Include.NON_NULL) to omit null fields
- Distinctive: line 871
All URI patterns are defined once here — never hardcode URI strings elsewhere.
- Very specific: line 874
Before adding a new constant, check if it already exists in ResourceLabels, ProcessRoles, KafkaListenerType, or other Strimzi API classes.
- Distinctive: line 884
Import order: third-party, javax, java, static (alphabetical within groups, blank line between)
- Distinctive: line 885
All public types, methods, and fields require Javadoc
- Very specific: line 891
Use final on method parameters
- Very specific: line 892
Use if/else over multi-line ternary operators.
- Very specific: line 894
Use InputUtils.normalizeInput() for all user-supplied input
- Very specific: line 895
Prefer List.of() for empty immutable lists
- Very specific: line 896
Use LOG.infof() / LOG.debugf() (JBoss logging with format strings)
- Distinctive: line 898
Every file must end with a newline (trailing newline).
- Distinctive: line 906
Keep descriptions concise, start with a verb or noun (not "This method...")
- Very specific: line 907
Use {@code ...} for inline code references
- Very specific: line 912
Create or update the DTO record in strimzi-mcp/src/.../strimzi/dto/
- Very specific: line 913
Add the service method to the appropriate domain service in strimzi-mcp/src/.../strimzi/service/
- Very specific: line 914
Add the @Tool method to the corresponding tools class in strimzi-mcp/src/.../strimzi/tool/
- Very specific: line 916
Add @MetaField(name = ToolMetaFields.COMPOSITE, value = "true", type = MetaField.Type.BOOLEAN) for composite tools
- Very specific: line 918
Add expected metadata to McpDiscoveryTest.testToolMetadata() maps
- Very specific: line 919
Run ./mvnw compile to verify checkstyle + compilation
- Very specific: line 920
Run ./mvnw test to verify tests pass
- Very specific: line 924
Create a new directory at the repo root (e.g., new-module/)
- Very specific: line 925
Add pom.xml with parent reference to streamshub-mcp
- Very specific: line 927
Add module to parent pom.xml <modules> list
- Very specific: line 928
Add META-INF/beans.xml to src/main/resources/ for CDI bean discovery
- Very specific: line 940
Every test calls MCP tools via McpAssured.McpStreamableTestClient and validates the JSON responses.
- Very specific: line 944
Never write a tool call assertion that only checks !isError().
- Distinctive: line 981
Check that the response contains the correct resource name and namespace — not just that fields exist:
- Distinctive: line 994
When the test deploys a known number of resources, verify the response count:
- Distinctive: line 1003
Every tool call must log its response for debugging CI failures.
- Very specific: line 1029
Don't use .toString().contains("value") to check array contents.
≈ “Common” is an estimate: at least 1 in 5 of the 43,423 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.
Files
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.3.x, Fabric8 Kubernetes client.
Documentation Structure
- User docs:
documentation/-- Installation, configuration, usage, and troubleshooting for end users, written as modular AsciiDoc following the Strimzi convention: single-purposecon-/proc-/ref-module files underdocumentation/modules/<topic>/, stitched together bydocumentation/assemblies/assembly-*.adoc, with shared values (product names, counts, versions) indocumentation/shared/attributes.adoc. Each MCP server has its own master book (e.g.,documentation/strimzi-mcp/strimzi-mcp.adoc) that includes the assemblies;documentation/index.adocis the top-level StreamsHub landing. Build to HTML with./mvnw -N -Pdocs package(the build fails on brokeninclude::/xref:references). - 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:
User documentation (
documentation/) -- 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
Update the relevant
ref-*/con-*/proc-*module (for a new tool, the matchingdocumentation/modules/tools/ref-*-tools.adoc) and bump the corresponding count attribute ({ToolCount},{PromptCount},{ResourceCount},{DiagnosticToolCount}) indocumentation/shared/attributes.adoc. Never hardcode a tool/prompt/resource count in prose -- use the attribute. Run./mvnw -N -Pdocs packageto verify the build.- 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
- 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
- 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
- Changing build, test, or CI workflows (
- 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 modulesmetrics-prometheus(streamshub-metrics-prometheus) - Prometheus/Thanos metrics provider (pluggable, replaceable JAR)loki-log-provider(streamshub-loki-log-provider) - Loki log provider (pluggable, replaceable JAR)opensearch-log-provider(streamshub-opensearch-log-provider) - 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/q/health and /q/metrics are on the Quarkus management interface (port 9000, 9001 in tests; quarkus.management.enabled, build time), not on the MCP port. In @QuarkusTest, use @TestHTTPResource(value = "/metrics", management = true) (the /q root is added for you).
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, LogFetchRequest (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),
│ ImageBuildStatus + ImageBuildInspection (generic container-image
│ build status and inspection result),
│ 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, TextTruncator (byte-exact,
│ line-aware text fitting used by ResponseSizeLimitGuardrail), FairShare (byte-budget
│ sharing used by TextTruncator and ResponseSizeLimitGuardrail), GuardedResponses,
│ Redactor (shared pattern + key-name redaction; used by LogRedactionGuardrail and
│ by the diagnostic Sampling path), SensitiveKeys (word-based secret key matcher
│ and config-map redaction; applied at source to Kafka/Connector/Bridge/Topic configs),
│ JsonNodeSanitizer (recursive text-node transformer for argument sanitization)
├── 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 core/v1 events by resource name and kind; time = last observation, works for events.k8s.io-created events),
│ │ KubernetesQueryException (typed exception for Kubernetes API failures),
│ │ OpenShiftDetector (cached build.openshift.io probe),
│ │ ImageBuildInspectionService (generic builder-pod / OpenShift Build
│ │ introspection; failure-only log excerpts; domain-agnostic)
│ ├── log/ → LogCollectionService, LogCollectorProvider, KubernetesLogProvider,
│ │ LogFilterUtils (shared keyword/regex log line filtering),
│ │ LogQueryException (typed exception for log collection failures).
│ │ LogCollectorProvider.fetchLogs takes a single LogFetchRequest (namespace,
│ │ pod, filtering fields, and optional container selector);
│ │ LogCollectorProvider.searchScopeNote (default null) reports a limit the
│ │ provider applied (e.g. Loki's filter-lookback), added once to warnings;
│ │ LogCollectorProvider.emptyContainerHint (default null) explains an empty
│ │ container-filtered result (Loki: label mapping, with a limit-1 probe
│ │ over max-lookback; OpenSearch: field mapping, with a size-1 probe).
│ └── 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),
│ EnvVarUtils (describe a valueFrom env var source, e.g. secretKeyRef:name/key, and envFrom sources that could supply a variable),
│ GlobMatcher (prefix/glob name matching: '*'/'?', case-sensitive),
│ PaginationUtils (offset/limit helpers for paginated list responses),
│ QueryLiteralSanitizer (label-name check and string-literal escaping shared
│ by PromQLSanitizer and LogQLSanitizer)
└── 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/ → PromQLSanitizerLoki log provider module (loki-log-provider/)
io.streamshub.mcp.loki.
├── config/ → LokiConfig (label mapping, auth mode, JSON message unwrap, lookbacks;
│ @DurationMin constraints checked at startup via quarkus-hibernate-validator)
├── service/ → LokiClient, LokiAuthFilter
├── util/ → LogQLSanitizer
└── LokiLogProvider (implements LogCollectorProvider)OpenSearch log provider module (opensearch-log-provider/)
io.streamshub.mcp.opensearch.
├── config/ → OpenSearchConfig (field mapping, auth mode, index pattern, filter lookback)
├── service/ → OpenSearchClient, OpenSearchAuthFilter
├── util/ → OpenSearchQuerySanitizer
├── OpenSearchResponse (response record with nested Hit record)
└── OpenSearchLogProvider (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 (list_kafka_topics supports optional nameFilter glob
│ │ and statusFilter — a TopicStatusFilter enum arg rendered as a schema enum)
│ ├── kafkauser/ → KafkaUserTools
│ ├── kafkanodepool/ → KafkaNodePoolTools
│ ├── kafkarebalance/ → KafkaRebalanceTools
│ ├── kafkabridge/ → KafkaBridgeTools
│ ├── kafkaconnect/ → KafkaConnectTools, KafkaConnectorTools
│ ├── kafkamirrormaker2/ → KafkaMirrorMaker2Tools
│ ├── draincleaner/ → DrainCleanerTools
│ ├── operator/ → StrimziOperatorTools, StrimziEventsTools
│ ├── strimzipodset/ → StrimziPodSetTools
│ ├── diagnostic/ → DiagnosticTools (composite diagnostic tools)
│ └── metrics/ → MetricsTools (the six get_*_metrics tools take an aggregation
│ AggregationLevel enum arg rendered as a schema enum)
├── service/ → Business logic, organized by domain sub-packages
│ ├── kafka/ → KafkaService, KafkaCertificateService, KafkaConfigService,
│ │ KafkaConfigComparisonService, KafkaClusterOverviewService,
│ │ KafkaFleetOverviewService, BootstrapMatcher,
│ │ KafkaClusterDiagnosticService, KafkaConnectivityDiagnosticService,
│ │ KafkaMetricsDiagnosticService, UpgradeReadinessDiagnosticService,
│ │ UpgradePreflightChecks (deterministic topic-durability / version-path findings),
│ ├── kafkatopic/ → KafkaTopicService, KafkaTopicDiagnosticService
│ ├── kafkauser/ → KafkaUserService
│ ├── kafkanodepool/ → KafkaNodePoolService, KafkaNodePoolDiagnosticService
│ ├── kafkarebalance/ → KafkaRebalanceService, KafkaRebalanceDiagnosticService
│ ├── draincleaner/ → DrainCleanerService
│ ├── operator/ → StrimziOperatorService, StrimziEventsService,
│ │ OperatorMetricsDiagnosticService
│ ├── kafkabridge/ → KafkaBridgeService, KafkaBridgeDiagnosticService
│ ├── kafkaconnect/ → KafkaConnectService, KafkaConnectorService, KafkaConnectBuildService
│ │ (Strimzi spec.build adapter; delegates introspection to the common
│ │ ImageBuildInspectionService),
│ │ KafkaConnectDiagnosticService (treats build failures as a category),
│ │ KafkaConnectorDiagnosticService.
│ │ `get_kafka_connect` returns optional `build` object when `spec.build`
│ │ is configured (K8s Buildah/Kaniko builder pod or OpenShift Build)
│ ├── kafkamirrormaker2/ → KafkaMirrorMaker2Service,
│ │ KafkaMirrorMaker2DiagnosticService
│ ├── metrics/ → KafkaMetricsService, KafkaExporterMetricsService,
│ │ KafkaBridgeMetricsService, KafkaConnectMetricsService,
│ │ StrimziOperatorMetricsService, CruiseControlMetricsService
│ ├── strimzipodset/ → StrimziPodSetService
│ └── (root) → CompletionService
├── dto/ → Strimzi response records and diagnostic reports
│ ├── kafkabridge/ → KafkaBridgeResponse, etc.
│ ├── kafkaconnect/ → KafkaConnectResponse, KafkaConnectorResponse, KafkaConnectBuildInfo, etc.
│ ├── kafkamirrormaker2/ → KafkaMirrorMaker2Response, KafkaMirrorMaker2DiagnosticReport, etc.
│ ├── kafkauser/ → KafkaUserResponse, KafkaUserAclMatrixResponse, AclResourceType
│ │ (resourceType enum arg on get_kafka_user_acls_matrix, rendered as a schema enum)
│ ├── strimzipodset/ → StrimziPodSetResponse, StrimziPodSetListResponse
│ └── metrics/ → KafkaMetricsResponse, KafkaExporterMetricsResponse,
│ KafkaBridgeMetricsResponse, KafkaConnectMetricsResponse,
│ StrimziOperatorMetricsResponse, CruiseControlMetricsResponse
├── prompt/ → MCP prompt templates (DiagnoseClusterIssuePrompt, TroubleshootConnectivityPrompt,
│ TroubleshootTopicPrompt, TroubleshootConnectPrompt, TroubleshootConnectorPrompt,
│ TroubleshootBridgePrompt, TroubleshootMirrorMakerPrompt,
│ TroubleshootKafkaStoragePrompt, TroubleshootKafkaRebalancePrompt,
│ 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, MetricsBackendLayer 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 theMcpErrorsfactory (not-found, invalid-params, ambiguity) so clients receive machine-readableerror.data; see Error handling. Use plainToolCallExceptiononly for errors that should remain failed tool responses (rate-limit, cancellation). - Common services are generic Kubernetes helpers shared across modules.
- DTOs are immutable
recordtypes. Use static factory methods (of(),empty()) not constructors directly. - Metrics providers implement
MetricsProviderinterface. Selected via@LookupIfPropertyonmcp.metrics.provider. Domain services useMetricsQueryService(in common/) to query metrics — it handles provider lookup, query param construction, and delegation. Do not injectInstance<MetricsProvider>directly in domain services.mcp.metrics.max-samplesis a per-metric limit (PerMetricSampleLimit), enforced by every provider and again byMetricsQueryService. Filter on label values with thelabelRegexMatchersoverload (PromQL=~; pod scraping applies the same full-match semantics) so the filter runs before the limit, not on a truncated result. A series that lacks the label is compared as"", so a regex without an empty alternative drops it; end the regex with|(for exampleProduce|FetchConsumer|) to keep metrics without that label in the same query. Scope a component's query withComponentScope.matchers(label, value)(label=~"value|"), since components of one cluster share names such asjvm_*; the empty alternative keeps series from setups without thestrimzi_io_*relabeling. - Metrics aggregation uses
AggregatedTimeSeries.fromSamples(samples, level)to group and average metric samples byAggregationLevel(PARTITION → TOPIC → BROKER → CLUSTER).MetricLabelFilter.labelsForAggregation()strips labels at each level. Each*MetricCategoriesclass definesfinestLevel()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 andNamespaceElicitationHelper(common/) for namespace disambiguation. Individual step failures do not abort the workflow. - Metric category constants are defined as public
static final Stringfields in each*MetricCategoriesclass (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
Every @Tool method is annotated with @RunOnVirtualThread. All tools perform blocking I/O —
sequential Kubernetes API calls, pod log streaming, pod-proxy metrics scraping, Loki/OpenSearch
queries, and (for composite tools) LLM sampling round-trips — which would otherwise block and
exhaust the standard Quarkus worker thread pool under concurrent MCP client load. Annotating them
offloads execution to virtual threads. The @RunOnVirtualThread annotation sits above @WithSpan
in the annotation stack. ToolGuardrailsEnforcementTest fails the build if a @Tool method lacks it.
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 — fits oversized responses into
mcp.guardrail.max-response-bytes(serialized bytes): shares the budget across large text fields withFairShare(unused share goes to the others), cuts at line boundaries viaTextTruncator(pod logs keep the newest whole lines of every pod, sectioned byLogCollectionService.POD_HEADER_PREFIX), and flags it with roottruncated: true, amessagenote, andhas_more/log_lineson truncatedlogsobjects. Leaves the response unchanged (WARN) when non-text content alone is too large.
The guardrails run in the declared order. All 67 @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 bymcp.guardrail.rate-limit.log-rpm - MetricsRateLimitGuardrail — for metrics tools (
get_*_metrics); throttled bymcp.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,checkresource— the Strimzi/Kubernetes resource:kafka,kafkatopic,kafkauser,kafkanodepool,kafkarebalance,strimzi-operator,strimzi-event,drain-cleaner,kafkaconnect,kafkaconnector,kafkabridge,kafkamirrormaker2,strimzi-pod-setcomposite(boolean, only whentrue) — 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
StrimziToolsPromptsconstants 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 (67 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)
- 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.
- 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.
- Pod filtering: When collecting cluster logs, the service identifies problematic pods
(not Running, not ready, or restart count >
- 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-tokensandmcp.sampling.analysis-max-tokens - OpenTelemetry tracing: Gather/triage/analysis methods are annotated with
@WithSpanfor distributed tracing. Methods are package-private (not private) so Quarkus ArC subclass-based interception can intercept self-invocations fromdiagnose(). Span names follow the patterndiagnose.{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 clientcheckCancellation(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 insertionelicitSelection(Elicitation, message, propertyName, description, options)— generic single-select ElicitationextractSamplingText(SamplingResponse)— safe text extraction from Sampling responseMAP_TYPE_REF— reusableTypeReference<Map<String, Object>>for JSON parsing
Cancellation Patterns
Diagnostic services support two cancellation mechanisms:
- 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)
- 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 textperformSampling(sampling, systemPrompt, data, maxTokens, cancelled)— overload with push-based cancellation supportperformAnalysis(sampling, systemPrompt, fullData)— convenience wrapper usinganalysisMaxTokensperformAnalysis(sampling, systemPrompt, fullData, cancelled)— overload with push-based cancellation supportperformTriage(sampling, systemPrompt, phase1Summary)— sends triage Sampling, parses JSON response to MapperformTriage(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 carriesMcpErrorDatawith categoryAMBIGUOUSelicitNamespace(McpException, Elicitation, context)— reads candidate namespaces from the structuredMcpErrorData.candidates()and combines withDiagnosticHelper.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, metricsKafkaConnectivityDiagnosticReport— cluster, bootstrap servers, certificates, pods, logsKafkaMetricsDiagnosticReport— cluster, pods, replication/performance/resource/throughput metricsOperatorMetricsDiagnosticReport— operator, reconciliation/resource/JVM metrics, logsKafkaConnectorDiagnosticReport— connector, parent Connect cluster, pods, logsKafkaSecurityAuditReport— cluster security config, authorization type, certificates, KafkaUser inventory, ACL matrices (broad grants flagged)
Adding a new composite diagnostic tool
- Create the report DTO in
strimzi-mcp/src/.../strimzi/dto/ - Create the diagnostic service in
strimzi-mcp/src/.../strimzi/service/extendingBaseDiagnosticService(common/) — providesobjectMapper,triageMaxTokens,analysisMaxTokens,defaultTailLines, and theperformSampling(),performAnalysis(),performTriage()utility methods - Add the
@Toolmethod toDiagnosticTools - Add the tool name to
McpDiscoveryTest.testToolDiscovery()expected list - Create a service test in
strimzi-mcp/src/test/.../strimzi/service/ - 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) andNamespaceElicitationHelper.elicitNamespaceMrtr()(for namespace disambiguation). Services callBaseDiagnosticService.performAnalysisMrtr(...)orelicitNamespaceMrtr(...)— 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.performTriageonisServerInitiatedRequestSupported()) and run analysis over all gathered data. NoteSampling.isSupported()reflects the client's capability and istrueeven for stateless clients, so the skip must key offisServerInitiatedRequestSupported(), notisSupported(). InputRequiredExceptionMUST propagate uncaught AND unwrapped to the framework (it is converted to aninput_requiredJSON-RPC result). Everycatchbetween the service and the framework must pass it through: it is excluded from@WrapBusinessError(unless = ...)onDiagnosticToolsand explicitly rethrown ahead of the genericcatch (Exception)inDiagnosticHelper.sendSampling/analysisSamplingMrtr. Any newcatch (Exception)on the diagnostic path must do the same — treatInputRequiredExceptionexactly likeMcpException.requestStatecarries the resolved namespace across round-trips becauseInputResponsesdoes not accumulate. Pass the gathered resource's resolved namespace as theString requestStateargument when callingperformAnalysisMrtr. When the primary elicited resource has no namespace accessor (e.g.KafkaTopicResponse), thread the namespace that resolved the gather out to the caller (seeKafkaTopicDiagnosticService.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 explicitnamespace1/namespace2.
Shared helpers:
DiagnosticHelper.analysisSamplingMrtr(Sampling, ObjectMapper, String systemPrompt, Map data, int maxTokens, String key, String requestState, AtomicBoolean cancelled)— forks to stateful/stateless paths;requestStateis aString(not a map), andcancelledshort-circuits the stateful call before/aftersendAndAwait()BaseDiagnosticService.performAnalysisMrtr(Sampling, String systemPrompt, Map fullData, String key, String requestState, AtomicBoolean cancelled)— convenience wrapper delegating toanalysisSamplingMrtrNamespaceElicitationHelper.elicitNamespaceMrtr(...)— namespace disambiguation via Elicitation (SSE) or MRTR (stateless). It self-guards onisFormModeSupported()and falls back to the structured error otherwise.DiagnosticHelper.effectiveNamespace(...)— resolves namespace from tool arg orrequestState
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:- An assistant-role persona via
StrimziToolsPrompts.systemMessage("domain")— sets the SRE expert persona - A user-role task with step-by-step instructions
- An assistant-role persona via
- 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.) - Tool arguments cannot be completed. MCP
completion/completeonly supportsref/promptandref/resource;@CompleteArgattaches to@CompletePrompt/@CompleteResourceTemplate, never@Tool. To advertise a fixed allowed-value set on a tool argument, declare it as a Java enum parameter — the generated input schema carries a JSON-schemaenum(e.g.TopicStatusFilteronlist_kafka_topics,AggregationLevelon the sixget_*_metricsaggregationargs, andAclResourceTypeonget_kafka_user_acls_matrix).quarkus.jackson.accept-case-insensitive-enums=truekeeps these arguments case-insensitive on input, so clients may still send lowercase values; values outside the enum are rejected by the framework before the tool runs.
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 delaymcp.watch.reconnect-max-delay-ms(default: 60000) — maximum reconnect delaymcp.watch.reconnect-max-attempts(default: 10) — maximum reconnect attempts before giving upmcp.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 theMcpErrorsfactory (common/.../util/McpErrors.java). They propagate unwrapped through@WrapBusinessError(which excludesMcpException). Use for:- Missing/invalid params:
throw McpErrors.invalidParams("Cluster name is required")→ code-32602, categoryINVALID_PARAMS - Resource not found:
throw McpErrors.notFound("Kafka cluster", name, namespace)→ code-32002, categoryRESOURCE_NOT_FOUND(passnamespace = nullfor all-namespace searches;name = nullwhen there is no single name) - Multiple matches:
throw McpErrors.ambiguous("Kafka cluster", name, candidateNamespaces)→ code-32602, categoryAMBIGUOUS(candidates carried inerror.data.candidates)
- Missing/invalid params:
- Failed tool responses (
isError: true, text only) — plainToolCallException. 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).@WrapBusinessErroralso wraps any uncaught infrastructure exception into this shape — notablyKubernetesResourceServicewraps Kubernetes failures (including RBAC/403) inKubernetesQueryExceptionwith 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
@JsonPropertywith 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
@paramtags 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 genericUNKNOWNfallback valueStrimziConstants(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_LABELfromio.strimzi.api.ResourceLabels - Node pool roles: use
ProcessRoles.BROKER.toValue()fromio.strimzi.api.kafka.model.nodepool.ProcessRoles - Listener types: use
KafkaListenerType.INTERNAL.toValue()etc. fromio.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@ResourceTemplateannotations andResourceSubscriptionManager. 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
finalon method parameters - Use
if/elseover 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
assertstatements (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,
@paramfor each parameter,@returnfor return value - Record-level: describe the record,
@paramfor each component - Keep descriptions concise, start with a verb or noun (not "This method...")
- Use
{@code ...}for inline code references - Non-empty
@param/@return/@throwsdescriptions (checkstyle enforced)
Adding a New Strimzi Tool
- Create or update the DTO record in
strimzi-mcp/src/.../strimzi/dto/ - Add the service method to the appropriate domain service in
strimzi-mcp/src/.../strimzi/service/ - Add the
@Toolmethod to the corresponding tools class instrimzi-mcp/src/.../strimzi/tool/- Include
@MetaFieldannotations fortype(fromToolMetaFields) andresource(fromStrimziToolResources) - Add
@MetaField(name = ToolMetaFields.COMPOSITE, value = "true", type = MetaField.Type.BOOLEAN)for composite tools
- Include
- Add the tool name to
McpDiscoveryTest.testToolDiscovery()expected list - Add expected metadata to
McpDiscoveryTest.testToolMetadata()maps - Run
./mvnw compileto verify checkstyle + compilation - Run
./mvnw testto verify tests pass
Adding a New Module
- Create a new directory at the repo root (e.g.,
new-module/) - Add
pom.xmlwith parent reference tostreamshub-mcp - Depend on
streamshub-mcp-commonfor shared Kubernetes helpers - Add module to parent
pom.xml<modules>list - Add
META-INF/beans.xmltosrc/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 manualassertFalse(response.isError())+parseJson().assertToolError(response, "not found")— assertsisError()and error message contains substrings (case-insensitive). Use for all error test cases.assertDiagnosticReport(root)— validatessteps_completedis non-empty array,timestampandmessagepresent. Use for alldiagnose_*andassess_*tool responses.assertPodSummaryResponse(root)— validatestotal_pods > 0,ready_pods >= 0,health_statusandtimestamppresent. Use for allget_*_podstool responses.assertLogsResponse(root, "cluster_name", expectedName)— validates resource name field,podsarray,log_lines,timestamp,message. Use for allget_*_logstool responses.assertEventsResponse(root, resourceName, namespace)— validatesresource_name,namespace,total_events >= 0,timestamp,message. Use for allget_strimzi_eventstool 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'");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
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.

