This is an automated email from the ASF dual-hosted git repository.
epugh pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/solr-mcp.git
The following commit(s) were added to refs/heads/main by this push:
new 71e6959 feat: GraalVM native image support (#92)
71e6959 is described below
commit 71e6959f35734261c949fc41d691bacfb8334c53
Author: Aditya Parikh <[email protected]>
AuthorDate: Thu Apr 23 15:14:29 2026 -0400
feat: GraalVM native image support (#92)
Using GraalVM to provide fast start up.
---------
Signed-off-by: adityamparikh <[email protected]>
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
---
.github/workflows/native.yml | 135 ++++++++
AGENTS.md | 59 ++++
README.md | 35 ++
build.gradle.kts | 168 ++++++++--
docs/specs/graalvm-native-image.md | 368 +++++++++++++++++++++
gradle/libs.versions.toml | 2 +
scripts/benchmark-native.sh | 172 ++++++++++
.../apache/solr/mcp/server/config/SolrConfig.java | 7 +-
.../solr/mcp/server/config/SolrNativeHints.java | 107 ++++++
src/main/resources/logback-spring.xml | 61 ++--
src/main/resources/logback.xml | 32 ++
.../java/org/apache/solr/mcp/server/MainTest.java | 2 +
.../server/collection/CollectionServiceTest.java | 2 +
.../DockerImageStdioIntegrationTest.java | 4 +
.../mcp/server/metadata/SchemaServiceTest.java | 2 +
15 files changed, 1103 insertions(+), 53 deletions(-)
diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml
new file mode 100644
index 0000000..1a05342
--- /dev/null
+++ b/.github/workflows/native.yml
@@ -0,0 +1,135 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# GraalVM native image validation + benchmark.
+#
+# This workflow is INTENTIONALLY SEPARATE from build-and-publish.yml because:
+# - native tests are slow (minutes per run)
+# - nativeCompile is RAM-hungry
+# - Failures in native should not block JVM-path merges
+#
+# Triggers:
+# - Manual (workflow_dispatch)
+# - PRs that touch native-related files
+#
+# Jobs:
+# - native-test: ./gradlew nativeTest against Solr via Testcontainers
+# - native-image: build the native Docker image + run STDIO integration test
+# - benchmark: compare JVM vs native image size / startup / RSS
+
+name: Native Image
+
+on:
+ workflow_dispatch:
+ pull_request:
+ paths:
+ - 'build.gradle.kts'
+ - 'gradle/libs.versions.toml'
+ - 'docs/specs/graalvm-native-image.md'
+ - 'scripts/benchmark-native.sh'
+ - '.github/workflows/native.yml'
+ - 'src/main/java/**/*NativeHints*.java'
+ - 'src/main/resources/META-INF/native-image/**'
+
+jobs:
+ native-test:
+ name: nativeTest
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Set up GraalVM JDK 25
+ uses: graalvm/setup-graalvm@v1
+ with:
+ java-version: '25'
+ distribution: 'graalvm'
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ cache: 'gradle'
+
+ - name: Grant execute permission for gradlew
+ run: chmod +x gradlew
+
+ # nativeTest compiles the test suite into a native image and runs
+ # it. Slow — expect 10+ minutes per compile. JUnit assertions that
+ # rely on Mockito proxies can fail under native; keep an eye on
+ # the output and file focused hints in SolrNativeHints as needed.
+ - name: Run native tests
+ run: ./gradlew nativeTest -Pnative --no-daemon
+
+ native-image:
+ name: native Docker image + STDIO integration
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Set up GraalVM JDK 25
+ uses: graalvm/setup-graalvm@v1
+ with:
+ java-version: '25'
+ distribution: 'graalvm'
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ cache: 'gradle'
+
+ - name: Grant execute permission for gradlew
+ run: chmod +x gradlew
+
+ - name: Build native Docker image
+ run: ./gradlew bootBuildImage --no-daemon
+
+ - name: Run STDIO integration test against native image
+ run: ./gradlew dockerIntegrationTest -Pnative --no-daemon
+
+ - name: Upload integration test results
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: native-integration-results
+ path: build/reports/dockerIntegrationTest
+ retention-days: 7
+
+ benchmark:
+ name: JVM vs native benchmark
+ runs-on: ubuntu-latest
+ needs: native-image
+ timeout-minutes: 60
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Set up GraalVM JDK 25
+ uses: graalvm/setup-graalvm@v1
+ with:
+ java-version: '25'
+ distribution: 'graalvm'
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ cache: 'gradle'
+
+ - name: Grant execute permission for scripts
+ run: |
+ chmod +x gradlew scripts/benchmark-native.sh
+
+ - name: Run benchmark
+ run: ./scripts/benchmark-native.sh
+
+ - name: Upload benchmark results
+ uses: actions/upload-artifact@v4
+ with:
+ name: native-benchmark-results
+ path: docs/specs/benchmark-results.md
+ retention-days: 30
diff --git a/AGENTS.md b/AGENTS.md
index b2236c7..494d274 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -32,6 +32,12 @@ Solr MCP Server is a Spring AI Model Context Protocol (MCP)
server that enables
# Docker
./gradlew jibDockerBuild # Build Docker image locally
+# Native image (experimental, requires GraalVM JDK 25)
+./gradlew nativeCompile -Pnative # Compile native binary (host OS
only)
+./gradlew bootBuildImage # Build native Docker image (any
OS/arch)
+./gradlew nativeTest # Run tests as native image
+./gradlew dockerIntegrationTest -Pnative # Docker integration tests
(native)
+
# Run locally (requires `docker compose up -d` for Solr)
./gradlew bootRun # STDIO mode (default)
PROFILES=http ./gradlew bootRun # HTTP mode
@@ -63,10 +69,63 @@ Four service classes expose MCP tools via `@McpTool`
annotations:
Configuration files: `application-stdio.properties`,
`application-http.properties`
+### Logging Architecture
+
+The STDIO transport uses stdout for JSON-RPC messages, so any stray stdout
output
+corrupts the protocol. Logging is configured in two layers:
+
+- **`logback.xml`** — Loaded by logback BEFORE Spring Boot initializes.
Contains only
+ a `NopStatusListener` to suppress logback's internal status messages
(`|-INFO`,
+ `|-WARN`) that would otherwise be written directly to stdout. Required for
native
+ image where logback falls through to `BasicConfigurator` without it.
+- **`logback-spring.xml`** — Loaded by Spring Boot, overrides `logback.xml`.
Uses
+ `<springProfile>` blocks to scope appenders per transport mode:
+ - **HTTP**: CONSOLE appender (stdout) + OpenTelemetry appender (OTLP log
export with
+ `captureExperimentalAttributes` and `captureKeyValuePairAttributes`
enabled).
+ - **STDIO**: No appenders defined. Relies on `logging.pattern.console=` in
+ `application-stdio.properties` to produce empty output from Spring Boot's
default
+ console appender. The OTEL appender is intentionally excluded to keep
stdout clean.
+- **`application-stdio.properties`** — Sets `logging.pattern.console=` (empty
pattern)
+ which suppresses all Spring-managed console logging after Spring Boot
initializes.
+
+**Init order**: logback.xml → Spring Boot starts → logback-spring.xml →
application-{profile}.properties
+
### Why Jib Instead of Spring Boot Buildpacks
Spring Boot Buildpacks output logs to stdout, breaking MCP's STDIO protocol.
Jib produces clean images with no stdout pollution, plus faster builds and
multi-platform support (amd64/arm64).
+### GraalVM Native Image (Opt-In)
+
+An opt-in native image build is available via `-Pnative`, targeting the STDIO
profile only.
+The native binary is compiled by `org.graalvm.buildtools.native`
(`nativeCompile`) and packaged
+into a Docker image via `bootBuildImage` (Paketo buildpacks). Key
configuration:
+
+- **Opt-in flag:** `val nativeBuild = project.hasProperty("native")` in
`build.gradle.kts`
+- **Cross-platform:** `bootBuildImage` compiles inside a Linux builder
container, so it works on any host OS (macOS, Linux, Windows).
+- **AOT profile:** `processAot` runs with `--spring.profiles.active=stdio`
under `-Pnative`
+ so security autoconfig exclusions from `application-stdio.properties` are
applied during
+ hint generation. The `@SpringBootApplication` annotation is **not** modified.
+- **OTel build-time init:** OTel instrumentation BOM 2.11.0 lacks native
metadata;
+ `--initialize-at-build-time` is set for `io.opentelemetry.api`,
`io.opentelemetry.context`,
+ `io.opentelemetry.instrumentation.api`, and
`io.opentelemetry.instrumentation.logback`.
+ Do **NOT** add `io.opentelemetry.instrumentation.spring` — it contains CGLIB
proxies.
+- **Reflection hints:** `SolrNativeHints.java` registers hints that Spring AOT
does
+ not generate automatically:
+ - **SolrJ types** (no native metadata): `QueryResponse`, `UpdateResponse`,
`NamedList`,
+ `SimpleOrderedMap`, `SolrDocument`, `SolrDocumentList`,
`SolrInputDocument`,
+ `SolrInputField`, `FacetField`, `FacetField.Count`
+ - **MCP tool response records** (invisible to AOT because the MCP framework
uses
+ generic `Object` dispatch): `CollectionCreationResult`, `SolrHealthStatus`,
+ `SolrMetrics`, `IndexStats`, `QueryStats`, `CacheStats`, `CacheInfo`,
+ `HandlerStats`, `HandlerInfo`, `FieldStats`, `SearchResponse`
+ - **Resource**: `logback.xml` (see Logging Architecture above)
+- **Wire format:** `SolrConfig` uses `XMLRequestWriter` instead of the default
+ `JavaBinRequestWriter`. The JavaBin binary codec uses deep reflection that
would
+ require extensive additional native image hints.
+- **Docker tags:** JVM image = `solr-mcp:<version>` (Jib), native image =
`solr-mcp:<version>-native` (bootBuildImage)
+- **CI:** Separate `native.yml` workflow; native failures do not block
JVM-path merges.
+- **Spec:**
[docs/specs/graalvm-native-image.md](docs/specs/graalvm-native-image.md)
+
## Testing Structure
- **Unit tests** (`*Test.java`): Mocked dependencies, fast execution
diff --git a/README.md b/README.md
index 642aee1..f30239e 100644
--- a/README.md
+++ b/README.md
@@ -376,9 +376,44 @@ The `solr://{collection}/schema` resource supports
autocompletion for the `{coll

+## Native image (experimental)
+
+An opt-in GraalVM native image build is available for the STDIO profile. The
+native binary starts faster and uses less memory than the JVM image.
+
+```bash
+# Build the native Docker image (works on any OS — compiles inside a Linux
builder container)
+./gradlew bootBuildImage
+# Produces: solr-mcp:<version>-native (also tagged :latest-native)
+
+# Run it
+docker run -i --rm -e SOLR_URL=http://host.docker.internal:8983/solr/ \
+ solr-mcp:latest-native
+```
+
+### Claude Desktop (native)
+
+```json
+{
+ "mcpServers": {
+ "solr-mcp": {
+ "command": "docker",
+ "args": [
+ "run", "-i", "--rm",
+ "-e", "SOLR_URL=http://host.docker.internal:8983/solr/",
+ "solr-mcp:latest-native"
+ ]
+ }
+ }
+}
+```
+
+See [docs/specs/graalvm-native-image.md](docs/specs/graalvm-native-image.md)
for the design and known risks.
+
## Documentation
- [Auth0 Setup (OAuth2 configuration)](security-docs/AUTH0_SETUP.md)
+- [GraalVM native image spec](docs/specs/graalvm-native-image.md)
## Contributing
diff --git a/build.gradle.kts b/build.gradle.kts
index dd29830..3161a54 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -26,8 +26,33 @@ plugins {
alias(libs.plugins.errorprone)
alias(libs.plugins.spotless)
alias(libs.plugins.jib)
+ alias(libs.plugins.graalvm.native)
}
+// GraalVM Native Image (Opt-In)
+// =============================
+// Invoked via `./gradlew ... -Pnative`. See
docs/specs/graalvm-native-image.md.
+// When true:
+// - AOT tasks (processAot) run with spring.profiles.active=stdio so that
+// security autoconfig exclusions from application-stdio.properties are
+// applied during hint generation.
+// - graalvmNative plugin configures nativeCompile / nativeTest tasks.
+// - Native Docker images use bootBuildImage (see separate configuration).
+// Jib is always JVM-only; it is NOT used for native images.
+val nativeBuild = project.hasProperty("native")
+
+// Shared GraalVM native-image arguments used by both graalvmNative (local
builds)
+// and bootBuildImage (Docker builds via Paketo buildpacks).
+val nativeImageBuildArgs =
+ listOf(
+ "--no-fallback",
+ "-H:+ReportExceptionStackTraces",
+ "--initialize-at-build-time=io.opentelemetry.api",
+ "--initialize-at-build-time=io.opentelemetry.context",
+ "--initialize-at-build-time=io.opentelemetry.instrumentation.api",
+ "--initialize-at-build-time=io.opentelemetry.instrumentation.logback",
+ )
+
group = "org.apache.solr"
version = "1.0.0-SNAPSHOT"
@@ -265,7 +290,11 @@ tasks.register<Test>("dockerIntegrationTest") {
// Depend on building the Docker image first (only if Docker is available)
if (dockerAvailable) {
- dependsOn(tasks.jibDockerBuild)
+ if (nativeBuild) {
+ dependsOn(tasks.named("bootBuildImage"))
+ } else {
+ dependsOn(tasks.jibDockerBuild)
+ }
}
// Configure test task to only run docker integration tests
@@ -273,6 +302,12 @@ tasks.register<Test>("dockerIntegrationTest") {
includeTags("docker-integration")
}
+ // The native image is AOT-compiled for the STDIO profile only.
+ // Exclude the HTTP integration test when testing the native image.
+ if (nativeBuild) {
+ exclude("**/DockerImageHttpIntegrationTest*")
+ }
+
// Use the same test classpath and configuration as regular tests
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
@@ -283,6 +318,14 @@ tasks.register<Test>("dockerIntegrationTest") {
// Set longer timeout for Docker tests
systemProperty("junit.jupiter.execution.timeout.default", "5m")
+ // When invoked as `./gradlew dockerIntegrationTest -Pnative`, the Jib
+ // image produced is `solr-mcp:<version>-native`. BuildInfoReader only
+ // knows the plain version, so pass the tag override through a system
+ // property that the integration test can read.
+ if (nativeBuild) {
+ systemProperty("solr.mcp.docker.image.tag.suffix", "-native")
+ }
+
// Output test results
testLogging {
events("passed", "skipped", "failed", "standardOut", "standardError")
@@ -383,12 +426,9 @@ jib {
}
from {
- // Use Eclipse Temurin JRE 25 as the base image
- // Temurin is the open-source build of OpenJDK from Adoptium
image = "eclipse-temurin:25-jre"
- // Multi-platform support for both AMD64 and ARM64 architectures
- // This allows the image to run on x86_64 machines and Apple Silicon
(M1/M2/M3)
+ // Multi-arch: build for both amd64 and arm64
platforms {
platform {
architecture = "amd64"
@@ -402,32 +442,20 @@ jib {
}
to {
- // Default image name (can be overridden with -Djib.to.image=...)
- // Format: repository/image-name:tag
image = "solr-mcp:$version"
-
- // Tags to apply to the image
- // The version tag is applied by default, plus "latest" tag
tags = setOf("latest")
}
container {
- // Container environment variables
- // These are baked into the image but can be overridden at runtime
- environment =
- mapOf(
- // Disable Spring Boot Docker Compose support when running in
container
- // Docker Compose integration is disabled in the container
image.
- // It is only useful for local development (HTTP profile) where
- // the host has Docker and a compose.yaml. Inside a container,
- // Docker Compose cannot start sibling containers without a
- // Docker socket mount, so it must be turned off.
- // The application-stdio.properties also disables it for STDIO
mode.
- "SPRING_DOCKER_COMPOSE_ENABLED" to "false",
- )
+ // Disable Spring Boot Docker Compose support when running in
container.
+ // Docker Compose integration is disabled in the container image.
+ // It is only useful for local development (HTTP profile) where
+ // the host has Docker and a compose.yaml. Inside a container,
+ // Docker Compose cannot start sibling containers without a
+ // Docker socket mount, so it must be turned off.
+ // The application-stdio.properties also disables it for STDIO mode.
+ environment = mapOf("SPRING_DOCKER_COMPOSE_ENABLED" to "false")
- // JVM flags for containerized environments
- // These optimize the JVM for running in containers
jvmFlags =
listOf(
// Use container-aware memory settings
@@ -458,3 +486,93 @@ jib {
)
}
}
+
+// Native Docker image via Spring Boot Buildpacks
+// ===============================================
+// `bootBuildImage` compiles the native binary inside a Paketo builder
+// container, so it works on any host OS and CPU architecture (macOS
+// Apple Silicon, Linux x86_64, etc.).
+//
+// Always configured for native builds (BP_NATIVE_IMAGE=true).
+//
+// Usage:
+// ./gradlew bootBuildImage # Build native Docker image
+// ./gradlew dockerIntegrationTest -Pnative # Test the native image
+tasks.named<org.springframework.boot.gradle.tasks.bundling.BootBuildImage>("bootBuildImage")
{
+ imageName.set("solr-mcp:$version-native")
+ tags.set(listOf("solr-mcp:latest-native"))
+ environment.set(
+ mapOf(
+ "BP_NATIVE_IMAGE" to "true",
+ "BP_NATIVE_IMAGE_BUILD_ARGUMENTS" to
nativeImageBuildArgs.joinToString(" "),
+ "BP_JVM_VERSION" to "25",
+ // The Paketo builder runs Spring AOT processing inside the
+ // builder container. Set the STDIO profile so security
+ // autoconfig exclusions from application-stdio.properties are
+ // applied during AOT hint generation (same effect as the
+ // processAot args block for local nativeCompile).
+ "SPRING_PROFILES_ACTIVE" to "stdio",
+ // BPE_DEFAULT_* sets default runtime environment variables in
+ // the resulting container image.
+ "BPE_DEFAULT_SPRING_PROFILES_ACTIVE" to "stdio",
+ "BPE_DEFAULT_SPRING_DOCKER_COMPOSE_ENABLED" to "false",
+ ),
+ )
+}
+
+//
─────────────────────────────────────────────────────────────────────────────
+// GraalVM Native Image configuration
+//
─────────────────────────────────────────────────────────────────────────────
+// The `org.graalvm.buildtools.native` plugin registers `nativeCompile` and
+// `nativeTest` tasks. They are only useful when a GraalVM toolchain is
+// available; the plugin's presence does not affect regular JVM builds.
+graalvmNative {
+ binaries {
+ named("main") {
+ imageName.set("solr-mcp")
+ // Uses shared nativeImageBuildArgs which include --no-fallback,
+ // -H:+ReportExceptionStackTraces, and OTel
--initialize-at-build-time entries.
+ // OTel instrumentation BOM 2.11.0 does not ship native-image
metadata.
+ // NOTE: do NOT use io.opentelemetry.instrumentation (too broad) —
that
+ // would catch Spring autoconfigure CGLIB proxies which cannot be
build-time
+ // initialized.
+ buildArgs.addAll(nativeImageBuildArgs)
+ }
+ }
+ // Tests that are incompatible with native image are annotated
+ // @DisabledInNativeImage and skipped during nativeTest:
+ // - Mockito-based tests (ByteBuddy cannot generate classes at run time)
+ // - SolrJ indexing/query integration tests (response parsing uses
+ // reflection that lacks native-image metadata)
+ // Collection management, schema, and observability integration tests
+ // run normally in the native binary.
+ binaries {
+ named("test") {
+ // The test binary inherits the OTel --initialize-at-build-time
entries
+ // from the shared args (filtering out --no-fallback and
+ // -H:+ReportExceptionStackTraces), plus test-specific SDK entries.
+ buildArgs.addAll(
+ nativeImageBuildArgs.filter {
it.startsWith("--initialize-at-build-time=") },
+ )
+ buildArgs.addAll(
+ // opentelemetry-sdk-testing on the test classpath adds a
ServiceLoader
+ // provider (SettableContextStorageProvider) that is loaded at
build time.
+ "--initialize-at-build-time=io.opentelemetry.sdk",
+ // AndroidFriendlyRandomHolder creates a java.util.Random in
<clinit>,
+ // which GraalVM forbids in the image heap (stale seed).
+
"--initialize-at-run-time=io.opentelemetry.sdk.internal.AndroidFriendlyRandomHolder",
+ )
+ }
+ }
+}
+
+// When -Pnative is present, pin spring.profiles.active=stdio on the AOT
+// processor so application-stdio.properties (which excludes
+// SecurityAutoConfiguration + ManagementWebSecurityAutoConfiguration) is
+// applied while hint generation runs. Test AOT is intentionally left alone
+// because individual @SpringBootTest classes set their own profiles.
+if (nativeBuild) {
+ tasks.named<JavaExec>("processAot") {
+ args("--spring.profiles.active=stdio")
+ }
+}
diff --git a/docs/specs/graalvm-native-image.md
b/docs/specs/graalvm-native-image.md
new file mode 100644
index 0000000..97fb2b5
--- /dev/null
+++ b/docs/specs/graalvm-native-image.md
@@ -0,0 +1,368 @@
+# Spec: GraalVM Native Image Support (Opt-In, bootBuildImage, STDIO)
+
+Status: Draft
+Owner: TBD
+Target branch: `claude/graalvm-native-image-support-u1RqL`
+Related: [Spring AI 1.1 blog
post](https://spring.io/blog/2025/05/20/your-first-spring-ai-1)
+
+## 1. Motivation
+
+The Docker image produced by Jib currently ships the app on
`eclipse-temurin:25-jre`.
+For the **local STDIO use case** (Claude Desktop launching the container on
demand
+per session), JVM cold start and memory overhead are the main pain points:
+
+- Each new session pays the JVM warm-up cost.
+- Idle memory of a Spring Boot + Spring AI + SolrJ process is substantial even
before
+ it does any work.
+- The image is hundreds of MB.
+
+A GraalVM native image trades build-time complexity for:
+
+- Sub-second startup.
+- Significantly lower RSS.
+- A smaller, self-contained image (no JRE layer).
+
+Spring AI 1.1 added first-class AOT/native support, which makes this tractable
+for this project.
+
+## 2. Goals
+
+1. Add an **opt-in** native image build path, triggered by a Gradle property
+ (`-Pnative`), that produces a Docker image via `bootBuildImage`.
+2. Keep the default build (JVM mode) unchanged.
+3. Prove correctness: the existing test suite passes under `nativeTest`.
+4. Prove the win: a reproducible benchmark script measures startup time,
+ resident memory, and image size for JVM vs native, and the results are
+ recorded in this spec.
+5. Target transport: **STDIO profile only** for the initial cut. HTTP mode is
+ out of scope for v1 but not precluded.
+
+## 3. Non-Goals
+
+- Replacing the JVM image. Both flavors ship.
+- Native image support for the HTTP profile (OAuth2, actuator, Prometheus
+ registry). These often need extra reachability metadata; deferred to a
+ follow-up.
+- JMH-style throughput benchmarks. Startup / RSS / disk only.
+
+## 4. High-Level Approach
+
+1. Add the **GraalVM Native Build Tools** plugin
+ (`org.graalvm.buildtools.native`) alongside the existing Spring Boot plugin.
+ Spring Boot's AOT tasks (`processAot`, `processTestAot`) are picked up
+ automatically.
+2. For native Docker images, `bootBuildImage` is used with
+ `BP_NATIVE_IMAGE=true`. This compiles the native binary inside a Paketo
+ builder container, so it works on any host OS/architecture — no
+ cross-compilation needed.
+3. Jib remains for JVM images (proven stdout-clean for STDIO).
+4. For local native builds/tests (without Docker), `nativeCompile` and
+ `nativeTest` are still available but produce host-OS binaries.
+5. `processAot` runs with `--spring.profiles.active=stdio` under `-Pnative`
+ so the correct bean graph (with security exclusions) is captured.
+6. Native tests (`nativeTest`) run in a separate CI job, not as part of
+ `./gradlew build`, because they are slow (image compile per run).
+
+### 4.1 Why the Jib / bootBuildImage split
+
+- **Jib for JVM images:** Proven clean stdout, multi-arch support
+ (amd64/arm64), and no Docker daemon needed for registry push. This is the
+ default image used by MCP STDIO clients.
+- **`bootBuildImage` for native images:** Compiles inside a Linux Paketo
+ builder container, solving the cross-OS problem (macOS hosts produce Linux
+ binaries). The native binary IS the entrypoint — no buildpack launcher sits
+ in between — so stdout is clean.
+- The original concern about `bootBuildImage` stdout pollution applies to the
+ **JVM buildpack launcher**, not to native images where the compiled binary
+ runs directly as PID 1.
+
+## 5. Gradle Changes
+
+### 5.1 Plugin
+
+`build.gradle.kts` plugins block:
+```kotlin
+alias(libs.plugins.graalvm.native) // new, version-catalogued
+```
+
+`gradle/libs.versions.toml`:
+```toml
+[versions]
+graalvm-native = "0.10.6" # latest at time of writing; verify
+
+[plugins]
+graalvm-native = { id = "org.graalvm.buildtools.native", version.ref =
"graalvm-native" }
+```
+
+### 5.2 Toolchain & Build Args
+
+`nativeCompile` requires a GraalVM JDK on `PATH` or `JAVA_HOME`. The plugin
+reads the location from the environment (toolchain detection is disabled by
+default in the native build tools plugin). CI sets this up via
+`graalvm/setup-graalvm@v1`; locally, use SDKMAN (`sdk install java
+25.0.2-graalce`) or download from https://www.graalvm.org.
+
+```kotlin
+graalvmNative {
+ binaries {
+ named("main") {
+ imageName.set("solr-mcp")
+ buildArgs.addAll(
+ "--no-fallback",
+ "-H:+ReportExceptionStackTraces",
+ // OTel 2.11.0 lacks native metadata — see §6.2
+ "--initialize-at-build-time=io.opentelemetry.api",
+ "--initialize-at-build-time=io.opentelemetry.context",
+
"--initialize-at-build-time=io.opentelemetry.instrumentation.api",
+
"--initialize-at-build-time=io.opentelemetry.instrumentation.logback",
+ )
+ }
+ named("test") {
+ buildArgs.addAll(
+ "--no-fallback",
+ "--initialize-at-build-time=io.opentelemetry.api",
+ "--initialize-at-build-time=io.opentelemetry.context",
+
"--initialize-at-build-time=io.opentelemetry.instrumentation.api",
+
"--initialize-at-build-time=io.opentelemetry.instrumentation.logback",
+ )
+ }
+ }
+}
+```
+
+### 5.3 Opt-in flag
+
+```kotlin
+val nativeBuild = project.hasProperty("native")
+```
+
+The `-Pnative` flag is only needed for:
+- `nativeCompile` — triggers `processAot` with the STDIO profile.
+- `dockerIntegrationTest` — selects the `-native` image tag suffix.
+
+`bootBuildImage` is always configured for native builds (it passes
+`BP_NATIVE_IMAGE=true` unconditionally). No `-Pnative` flag is required
+to run it.
+
+### 5.4 bootBuildImage config for native
+
+```kotlin
+tasks.named<BootBuildImage>("bootBuildImage") {
+ imageName.set("solr-mcp:${version}-native")
+ tags.set(listOf("solr-mcp:latest-native"))
+ environment.set(mapOf(
+ "BP_NATIVE_IMAGE" to "true",
+ "BP_NATIVE_IMAGE_BUILD_ARGUMENTS" to
nativeImageBuildArgs.joinToString(" "),
+ "BP_JVM_VERSION" to "25",
+ ))
+}
+```
+
+### 5.5 Native tests
+
+No extra config needed beyond the plugin — `./gradlew nativeTest` is provided
+by `org.graalvm.buildtools.native`. We do **not** wire it into `./gradlew
build`.
+It is invoked explicitly in a dedicated CI job.
+
+Docker integration tests (`@Tag("docker-integration")`) should gain a
+native counterpart that builds the `-native` image and re-runs the STDIO
+integration scenario against it. This is the end-to-end proof.
+
+## 6. Reflection / Resource Hints
+
+### 6.1 SolrJ (JSON wire format only)
+
+The client is constructed in `SolrConfig.java` as:
+
+```java
+new HttpJdkSolrClient.Builder(url)
+ .withResponseParser(jsonResponseParser) // JSON, not JavaBin
+ .build();
+```
+
+This means the **JavaBin codec path is not taken**, which is the SolrJ
+surface most frequently cited as native-hostile. The XML response parser
+is similarly out of scope.
+
+`SolrNativeHints.java` registers reflection hints for the narrow set of
+types actually used: `QueryResponse`, `UpdateResponse`, `NamedList`,
+`SolrDocument`, and `SolrDocumentList`.
+
+### 6.2 OpenTelemetry / Micrometer tracing
+
+The OpenTelemetry Spring Boot Starter officially supports native image
+in newer versions. However, the project currently pins
+`opentelemetry-instrumentation-bom:2.11.0`, which does **not** ship
+native-image reachability metadata. The version catalog declares `2.26.1`
+but bumping introduces an OTel SDK incompatibility with Spring Boot
+3.5.x (`io.opentelemetry.common.ComponentLoader` not found), so the
+bump is deferred until the OTel SDK and Spring Boot BOMs are aligned.
+
+**Build-time initialization workaround:** The OTel logback appender's
+`LoggingEventMapper` holds static `AttributeKey` fields (via
+`InternalAttributeKeyImpl`) that end up in the image heap. GraalVM
+requires their types to be build-time initialized. The `graalvmNative`
+block adds targeted `--initialize-at-build-time` for four OTel packages:
+- `io.opentelemetry.api` — `InternalAttributeKeyImpl`, `AttributeType`
+- `io.opentelemetry.context` — context propagation
+- `io.opentelemetry.instrumentation.api` — `MapBackedCache`
+- `io.opentelemetry.instrumentation.logback` — the logback appender
+
+**Important:** `io.opentelemetry.instrumentation.spring` must NOT be
+included — it contains CGLIB proxy classes that cannot be build-time
+initialized.
+
+The OTLP/gRPC exporter is only wired in the HTTP profile, so the STDIO
+native image does not exercise its reflection surface.
+
+### 6.3 Security / OAuth2 on classpath under STDIO
+
+Current state (already good):
+- `application-stdio.properties` excludes `SecurityAutoConfiguration` and
+ `ManagementWebSecurityAutoConfiguration` via `spring.autoconfigure.exclude`.
+- `HttpSecurityConfiguration.java` is annotated `@Profile("http")`.
+- `MethodSecurityConfiguration.java` is `@Profile("http")`.
+
+**AOT mitigation:** The `processAot` Gradle task is configured (under
+`-Pnative` only) to pass `--spring.profiles.active=stdio`, so the STDIO
+property exclusions are active during AOT hint generation.
+
+**Important:** The `@SpringBootApplication` annotation on `Main` is
+**not** modified. Security autoconfiguration remains globally available
+so the HTTP profile continues to work without any special handling.
+
+### 6.4 Hints workflow
+
+1. First pass: build and run `nativeTest` with `-Pnative`. Fix each
+ reflection/resource failure by adding a targeted hint via a
+ `RuntimeHintsRegistrar` in a `@Configuration` class registered with
+ `@ImportRuntimeHints`. Preferred over annotation-scattering because
+ the rules are centralized and reviewable.
+2. Only fall back to the agent (`-agentlib:native-image-agent`) if
+ static analysis of the failures is too noisy. Agent output goes to
+ `src/main/resources/META-INF/native-image/org.apache.solr/solr-mcp/`
+ and is committed.
+
+## 7. Profile / Application Config
+
+- Native v1 targets the STDIO profile. The native image's default profile
+ is set via `SPRING_PROFILES_ACTIVE=stdio` env var in the
+ `bootBuildImage` environment map.
+- The `processAot` task also runs with `--spring.profiles.active=stdio`
+ so the correct bean graph (with security exclusions) is captured.
+- Actuator, Prometheus registry, Security starters: kept on the classpath.
+ They do not interfere with STDIO AOT processing because the STDIO
+ profile excludes security autoconfig and the HTTP-only `@Configuration`
+ classes are not loaded.
+
+## 8. Benchmark Plan
+
+### 8.1 Script
+
+`scripts/benchmark-native.sh` (new). Requirements:
+- Runs on Linux (CI or Linux dev box).
+- Builds both images:
+ - `./gradlew jibDockerBuild` → `solr-mcp:<v>` (JVM)
+ - `./gradlew bootBuildImage` → `solr-mcp:<v>-native`
+- For each image, measures:
+ - **Image size on disk** via `docker image inspect <img> --format
'{{.Size}}'`.
+ - **Startup time**: time from `docker run` until the container prints its
+ MCP "server ready" signal on stdout (STDIO mode). If no such signal
+ exists, add one in `Main` behind a `solr.mcp.startup.log=true` flag that
+ is enabled for benchmarks only.
+ - **Memory after startup**: after server-ready, sample
+ `docker stats --no-stream --format '{{.MemUsage}}'` N times over 5 seconds,
+ record the minimum (steady-state idle RSS).
+ - **Memory after one search**: drive one MCP `search` call via the existing
+ client harness, then resample.
+- Each measurement is the median of 5 runs.
+- Output a markdown table to stdout and write
`docs/specs/benchmark-results.md`.
+
+### 8.2 Results table (to be filled in after implementation)
+
+| Metric | JVM (`:<v>`) | Native (`:<v>-native`) |
Delta |
+|---------------------------------|--------------|------------------------|-------|
+| Image size (MB) | TBD | TBD |
TBD |
+| Cold start (ms) | TBD | TBD |
TBD |
+| Idle RSS after start (MB) | TBD | TBD |
TBD |
+| RSS after first search (MB) | TBD | TBD |
TBD |
+| `nativeTest` wall-clock | n/a | TBD |
n/a |
+
+### 8.3 Acceptance thresholds
+
+The native image is considered a win for the STDIO use case if **all** hold:
+- Startup ≤ 25% of JVM startup.
+- Idle RSS ≤ 50% of JVM idle RSS.
+- Image size ≤ 60% of JVM image size.
+
+If any threshold fails, capture the numbers anyway and keep the native
+path as opt-in behind the same flag; document the gap.
+
+## 9. CI
+
+Add a separate GitHub Actions workflow (or job in the existing one)
+`native.yml`:
+- Triggers: `workflow_dispatch` and on PRs touching this spec, the native
+ config, or `gradle/libs.versions.toml`.
+- Steps:
+ 1. Set up GraalVM JDK 25 (via `graalvm/setup-graalvm@v1`).
+ 2. `./gradlew nativeTest`
+ 3. `./gradlew bootBuildImage`
+ 4. `./gradlew dockerIntegrationTest -Pnative` (native-mode variant of the
+ STDIO integration test).
+ 5. `scripts/benchmark-native.sh` — upload results table as a job artifact.
+
+The default PR build (`./gradlew build`) remains JVM-only and fast.
+
+## 10. Rollout
+
+1. Land Gradle plumbing behind `-Pnative` with no native-specific hints.
+2. Iterate on hints until `nativeTest` is green.
+3. Add `dockerIntegrationTest -Pnative` path and the STDIO integration test
+ variant.
+4. Land `scripts/benchmark-native.sh` and fill in section 8.2.
+5. Update root README with a "Native image (experimental)" section pointing
+ at this spec, plus the one-liner build command.
+6. Tag the native image as `:latest-native` so users can opt in on pull:
+ `docker pull solr-mcp:latest-native`.
+
+## 11. Risks & Open Questions
+
+- **SolrJ native compatibility.** *Downgraded from medium to low-medium.*
+ The project already uses `JsonResponseParser` on `HttpJdkSolrClient`,
+ avoiding the JavaBin/XML reflective surface. Residual risk is
+ `ServiceLoader` metadata and a narrow set of response bean fields;
+ handle via a local `RuntimeHintsRegistrar`. See §6.1.
+- **OpenTelemetry starter.** *Managed via build-time init workaround.*
+ The OTel instrumentation BOM 2.11.0 does not ship native metadata.
+ Bumping to 2.26.1 (declared in the version catalog) fails at AOT time
+ because 2.26.1 requires `io.opentelemetry.common.ComponentLoader` which
+ is not present in the OTel SDK version managed by Spring Boot 3.5.x.
+ The workaround is `--initialize-at-build-time` for four targeted OTel
+ packages (see §6.2). The OTLP/gRPC exporter is only wired in the HTTP
+ profile, so the STDIO native image does not exercise its reflection
+ surface. **Follow-up:** align OTel BOM + SDK versions when Spring Boot
+ upgrades its managed OTel dependency.
+- **Spring Security + OAuth2 resource server.** *Downgraded.* Already
+ excluded via `spring.autoconfigure.exclude` in
+ `application-stdio.properties` and all security config classes carry
+ `@Profile("http")`. The AOT concern is addressed by pinning
+ `spring.profiles.active=stdio` on the `processAot` Gradle task so the
+ exclusions are applied before hint generation. The `@SpringBootApplication`
+ annotation is **not** modified — security autoconfiguration remains
+ globally available for the HTTP profile.
+- **AOT profile correctness.** AOT runs once at build time with one
+ profile active. Building the native image with the wrong (or no)
+ profile means the wrong bean graph is captured. V1 commits to STDIO
+ only; HTTP native is an explicit follow-up.
+- **Paketo builder download size.** `bootBuildImage` downloads a large
+ Paketo builder on first run (~1 GB). CI caching mitigates this.
+- **Build time & memory.** `nativeCompile` is RAM-hungry (commonly 4–8 GB).
+ Ensure CI runners have headroom.
+- **`mcp-server-security` library.** Small, non-Spring-official. Verify
+ it has no eager `@Configuration` classes that load outside `@Profile("http")`
+ that would force its classes into the STDIO AOT graph.
+ image.
+- HTTP profile native image (Actuator, Prometheus, OAuth2).
+- Profile-Guided Optimization (PGO) builds.
+- Publishing the native image from CI to GHCR / Docker Hub.
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 95f906a..7f2d2e0 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -5,6 +5,7 @@ spring-dependency-management = "1.1.7"
errorprone-plugin = "5.1.0"
jib = "3.5.3"
spotless = "7.0.2"
+graalvm-native = "0.10.6"
# Main dependencies
spring-ai = "1.1.4"
@@ -110,3 +111,4 @@ spring-dependency-management = { id =
"io.spring.dependency-management", version
errorprone = { id = "net.ltgt.errorprone", version.ref = "errorprone-plugin" }
jib = { id = "com.google.cloud.tools.jib", version.ref = "jib" }
spotless = { id = "com.diffplug.spotless", version.ref = "spotless" }
+graalvm-native = { id = "org.graalvm.buildtools.native", version.ref =
"graalvm-native" }
diff --git a/scripts/benchmark-native.sh b/scripts/benchmark-native.sh
new file mode 100755
index 0000000..34774ee
--- /dev/null
+++ b/scripts/benchmark-native.sh
@@ -0,0 +1,172 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# benchmark-native.sh — compare the JVM and native Docker images on:
+# - image size on disk
+# - startup time (time from `docker run` to context ready)
+# - resident memory after startup
+#
+# Prerequisites:
+# - Docker daemon running
+# - GraalVM JDK 25 on PATH (for the JVM build's processAot)
+# - Works on any OS/arch (native build runs inside Paketo builder container)
+#
+# Usage:
+# ./scripts/benchmark-native.sh
+#
+# Output:
+# - Markdown table on stdout
+# - docs/specs/benchmark-results.md (overwritten)
+
+set -euo pipefail
+
+cd "$(dirname "$0")/.."
+
+RUNS="${RUNS:-5}"
+SOLR_URL="${SOLR_URL:-http://host.docker.internal:8983/solr/}"
+VERSION="$(grep '^version = ' build.gradle.kts | sed 's/version =
"\(.*\)"/\1/')"
+JVM_IMAGE="solr-mcp:${VERSION}"
+NATIVE_IMAGE="solr-mcp:${VERSION}-native"
+RESULT_FILE="docs/specs/benchmark-results.md"
+# Require this many consecutive RSS samples within 1 MB to declare startup
complete
+STABLE_THRESHOLD="${STABLE_THRESHOLD:-3}"
+
+need() { command -v "$1" >/dev/null || { echo "missing: $1" >&2; exit 1; }; }
+need docker
+need awk
+need bc
+
+log() { printf '▶ %s\n' "$*" >&2; }
+
+build_images() {
+ log "Building JVM image…"
+ ./gradlew jibDockerBuild
+ log "Building native image (this can take several minutes)…"
+ ./gradlew bootBuildImage
+}
+
+image_size_mb() {
+ # Bytes -> MB with 1 decimal place
+ docker image inspect "$1" --format '{{.Size}}' | awk '{printf "%.1f",
$1/1024/1024}'
+}
+
+# Start container and time until it is "ready". STDIO MCP servers do not emit a
+# ready signal on stdout, so we sample process memory until RSS stabilizes
+# (STABLE_THRESHOLD consecutive samples within 1 MB of each other), which is a
+# reasonable proxy for end-of-startup on both JVM and native.
+run_one() {
+ local image="$1"
+ local cid
+ local t_start t_ready rss_mb prev_rss=0 stable_count=0
+ t_start="$(date +%s%N)"
+ # Do not use --rm so we can reliably inspect and clean up the container
+ cid="$(docker run -d \
+ -e SOLR_URL="${SOLR_URL}" \
+ -e SPRING_DOCKER_COMPOSE_ENABLED=false \
+ "${image}")"
+
+ # Poll at 25ms intervals for up to 60s
+ for i in $(seq 1 2400); do
+ if ! docker inspect "${cid}" >/dev/null 2>&1; then
+ docker logs "${cid}" >&2 || true
+ docker rm -f "${cid}" >/dev/null 2>&1 || true
+ echo "container exited prematurely" >&2
+ return 1
+ fi
+ rss_mb="$(docker stats --no-stream --format '{{.MemUsage}}'
"${cid}" \
+ | awk '{print $1}' | sed 's/MiB//; s/MB//;
s/GiB/*1024/; s/GB/*1024/' \
+ | bc 2>/dev/null || echo 0)"
+ if [[ "$(echo "${rss_mb} > 0 && (${rss_mb} - ${prev_rss} < 1)
&& (${prev_rss} - ${rss_mb} < 1)" | bc)" == "1" ]] \
+ && [[ "${prev_rss}" != "0" ]]; then
+ stable_count=$((stable_count + 1))
+ if [[ "${stable_count}" -ge "${STABLE_THRESHOLD}" ]];
then
+ t_ready="$(date +%s%N)"
+ break
+ fi
+ else
+ stable_count=0
+ fi
+ prev_rss="${rss_mb}"
+ sleep 0.025
+ done
+
+ if [[ -z "${t_ready:-}" ]]; then
+ docker logs "${cid}" >&2 || true
+ docker rm -f "${cid}" >/dev/null 2>&1 || true
+ echo "never stabilized" >&2
+ return 1
+ fi
+
+ local startup_ms
+ startup_ms=$(( (t_ready - t_start) / 1000000 ))
+ docker rm -f "${cid}" >/dev/null 2>&1 || true
+ printf '%s %s\n' "${startup_ms}" "${rss_mb}"
+}
+
+median() {
+ sort -n | awk '
+ { a[NR] = $1 }
+ END {
+ if (NR % 2) print a[(NR+1)/2];
+ else printf "%.1f", (a[NR/2] + a[NR/2+1]) / 2
+ }'
+}
+
+measure() {
+ local image="$1"
+ local startups=() rss=()
+ for i in $(seq 1 "${RUNS}"); do
+ read -r s r < <(run_one "${image}")
+ startups+=("${s}")
+ rss+=("${r}")
+ log " run ${i}: startup=${s}ms rss=${r}MB"
+ done
+ local med_startup med_rss
+ med_startup="$(printf '%s\n' "${startups[@]}" | median)"
+ med_rss="$(printf '%s\n' "${rss[@]}" | median)"
+ printf '%s %s\n' "${med_startup}" "${med_rss}"
+}
+
+build_images
+
+log "Measuring JVM image (${RUNS} runs)…"
+read -r jvm_startup jvm_rss < <(measure "${JVM_IMAGE}")
+jvm_size="$(image_size_mb "${JVM_IMAGE}")"
+
+log "Measuring native image (${RUNS} runs)…"
+read -r native_startup native_rss < <(measure "${NATIVE_IMAGE}")
+native_size="$(image_size_mb "${NATIVE_IMAGE}")"
+
+pct() { echo "scale=1; ($1 / $2) * 100" | bc; }
+
+size_pct="$(pct "${native_size}" "${jvm_size}")"
+startup_pct="$(pct "${native_startup}" "${jvm_startup}")"
+rss_pct="$(pct "${native_rss}" "${jvm_rss}")"
+
+{
+ echo "# Native vs JVM Benchmark Results"
+ echo
+ echo "Generated $(date -u +%FT%TZ) on $(uname -sm)"
+ echo "Version: \`${VERSION}\`, runs: ${RUNS} per image, startup = time
to RSS stabilization"
+ echo
+ echo "| Metric | JVM | Native | Native / JVM |"
+ echo "| --- | --- | --- | --- |"
+ echo "| Image size (MB) | ${jvm_size} | ${native_size} | ${size_pct}% |"
+ echo "| Startup (ms, median) | ${jvm_startup} | ${native_startup} |
${startup_pct}% |"
+ echo "| RSS after start (MB, median) | ${jvm_rss} | ${native_rss} |
${rss_pct}% |"
+ echo
+ echo "Acceptance thresholds (see spec §8.3): startup ≤25%, RSS ≤50%,
size ≤60%."
+} | tee "${RESULT_FILE}"
diff --git a/src/main/java/org/apache/solr/mcp/server/config/SolrConfig.java
b/src/main/java/org/apache/solr/mcp/server/config/SolrConfig.java
index 0fc720b..b604783 100644
--- a/src/main/java/org/apache/solr/mcp/server/config/SolrConfig.java
+++ b/src/main/java/org/apache/solr/mcp/server/config/SolrConfig.java
@@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.TimeUnit;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpJdkSolrClient;
+import org.apache.solr.client.solrj.request.XMLRequestWriter;
import
org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -189,9 +190,11 @@ public class SolrConfig {
}
}
- // Use with explicit base URL; JSON wire format replaces the
JavaBin default
+ // JSON wire format for responses; XML wire format for update
requests.
+ // The default JavaBin request writer uses a binary codec that
requires
+ // additional reflection metadata in GraalVM native images.
return new
HttpJdkSolrClient.Builder(url).withConnectionTimeout(CONNECTION_TIMEOUT_MS,
TimeUnit.MILLISECONDS)
.withIdleTimeout(SOCKET_TIMEOUT_MS,
TimeUnit.MILLISECONDS).withResponseParser(jsonResponseParser)
- .build();
+ .withRequestWriter(new
XMLRequestWriter()).build();
}
}
diff --git
a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java
b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java
new file mode 100644
index 0000000..4dda254
--- /dev/null
+++ b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.solr.mcp.server.config;
+
+import java.util.List;
+import org.apache.solr.client.solrj.response.FacetField;
+import org.apache.solr.client.solrj.response.QueryResponse;
+import org.apache.solr.client.solrj.response.UpdateResponse;
+import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrDocumentList;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.SolrInputField;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.SimpleOrderedMap;
+import org.jspecify.annotations.Nullable;
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.ImportRuntimeHints;
+
+/**
+ * GraalVM native image reachability hints for SolrJ types this project
actually
+ * uses.
+ *
+ * <p>
+ * The project uses the JSON wire format (SolrJ {@code JsonResponseParser} on
+ * {@code HttpJdkSolrClient}), avoiding the JavaBin/XML codec paths that
+ * historically drive most SolrJ native-image issues. The hints below cover the
+ * narrow remaining surface: response containers and the {@code NamedList}
admin
+ * shape returned by the mbeans path.
+ *
+ * <p>
+ * This class is registered unconditionally — on the JVM path it is a no-op
+ * because no runtime reflection happens against these types at startup. It is
+ * only meaningful when running as a native image.
+ *
+ * @see SolrConfig
+ */
+@Configuration
+@ImportRuntimeHints(SolrNativeHints.Registrar.class)
+public class SolrNativeHints {
+
+ /**
+ * Package-private record types returned by {@code @McpTool} methods.
Jackson
+ * needs reflection access to serialize these as MCP tool responses in
native
+ * image.
+ */
+ private static final List<String> MCP_RESPONSE_RECORDS = List.of(
+
"org.apache.solr.mcp.server.collection.CollectionCreationResult",
+
"org.apache.solr.mcp.server.collection.SolrHealthStatus",
+ "org.apache.solr.mcp.server.collection.SolrMetrics",
"org.apache.solr.mcp.server.collection.IndexStats",
+ "org.apache.solr.mcp.server.collection.FieldStats",
"org.apache.solr.mcp.server.collection.QueryStats",
+ "org.apache.solr.mcp.server.collection.CacheStats",
"org.apache.solr.mcp.server.collection.CacheInfo",
+ "org.apache.solr.mcp.server.collection.HandlerStats",
"org.apache.solr.mcp.server.collection.HandlerInfo",
+ "org.apache.solr.mcp.server.search.SearchResponse");
+
+ static class Registrar implements RuntimeHintsRegistrar {
+ @Override
+ public void registerHints(RuntimeHints hints, @Nullable
ClassLoader classLoader) {
+ MemberCategory[] categories =
{MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
+ MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.DECLARED_FIELDS};
+
+ // SolrJ response types
+ hints.reflection().registerType(QueryResponse.class,
categories);
+ hints.reflection().registerType(UpdateResponse.class,
categories);
+ hints.reflection().registerType(NamedList.class,
categories);
+ hints.reflection().registerType(SimpleOrderedMap.class,
categories);
+ hints.reflection().registerType(SolrDocument.class,
categories);
+ hints.reflection().registerType(SolrDocumentList.class,
categories);
+
+ // SolrJ input/indexing types
+
hints.reflection().registerType(SolrInputDocument.class, categories);
+ hints.reflection().registerType(SolrInputField.class,
categories);
+
+ // SolrJ facet types
+ hints.reflection().registerType(FacetField.class,
categories);
+ hints.reflection().registerType(FacetField.Count.class,
categories);
+
+ // MCP tool response records (package-private,
registered by name)
+ for (String className : MCP_RESPONSE_RECORDS) {
+
hints.reflection().registerTypeIfPresent(classLoader, className, categories);
+ }
+
+ // Include logback.xml in the native image so logback's
early
+ // initialization (before Spring Boot) finds it and
applies the
+ // NopStatusListener. Without this, logback falls
through to
+ // BasicConfigurator and writes status messages to
stdout,
+ // corrupting the MCP STDIO JSON-RPC framing.
+ hints.resources().registerPattern("logback.xml");
+ }
+ }
+}
diff --git a/src/main/resources/logback-spring.xml
b/src/main/resources/logback-spring.xml
index b71f9fb..e85a13b 100644
--- a/src/main/resources/logback-spring.xml
+++ b/src/main/resources/logback-spring.xml
@@ -16,34 +16,45 @@
limitations under the License.
-->
<configuration>
- <!-- Import Spring Boot's default logging configuration -->
- <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
-
- <!-- Console appender - used by all profiles -->
- <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>${CONSOLE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS} %5p
--- [%15.15t] %-40.40logger{39} : %m%n}
- </pattern>
- <charset>UTF-8</charset>
- </encoder>
- </appender>
-
<!--
- OpenTelemetry appender for log export (HTTP mode only)
- This appender sends logs to the OpenTelemetry Collector via OTLP.
- The appender is installed programmatically by
OpenTelemetryAppenderInstaller
- which connects it to the Spring-managed OpenTelemetry SDK instance.
+ Suppress logback internal status messages (|-INFO, |-WARN lines).
+ Without this, logback writes status output directly to stdout during
+ initialization, BEFORE the profile-specific root logger is configured.
+ In STDIO mode this corrupts the MCP JSON-RPC framing.
-->
- <appender name="OTEL"
class="io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender">
- <captureExperimentalAttributes>true</captureExperimentalAttributes>
- <captureKeyValuePairAttributes>true</captureKeyValuePairAttributes>
- </appender>
+ <statusListener class="ch.qos.logback.core.status.NopStatusListener"/>
+
+ <!-- Import Spring Boot's default logging configuration -->
+ <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<!--
HTTP mode - Full observability with console logging and OTEL export
Used when running as HTTP server with PROFILES=http
+
+ Appenders are defined inside the profile block so they do not exist
+ under the STDIO profile. This avoids logback "not referenced" warnings
+ and keeps STDIO stdout completely clean.
-->
<springProfile name="http">
+ <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>${CONSOLE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS}
%5p --- [%15.15t] %-40.40logger{39} : %m%n}
+ </pattern>
+ <charset>UTF-8</charset>
+ </encoder>
+ </appender>
+
+ <!--
+ OpenTelemetry appender for log export.
+ Sends logs to the OpenTelemetry Collector via OTLP.
+ The appender is installed programmatically by
OpenTelemetryAppenderInstaller
+ which connects it to the Spring-managed OpenTelemetry SDK instance.
+ -->
+ <appender name="OTEL"
class="io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender">
+ <captureExperimentalAttributes>true</captureExperimentalAttributes>
+ <captureKeyValuePairAttributes>true</captureKeyValuePairAttributes>
+ </appender>
+
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="OTEL"/>
@@ -51,12 +62,10 @@
</springProfile>
<!--
- STDIO mode (default) - No console logging
- STDIO mode must have NO stdout output as it uses stdin/stdout
- for MCP protocol communication. Default profile is stdio.
+ STDIO mode (default) - stdout suppressed via logging.pattern.console=
+ in application-stdio.properties. No logback-level overrides needed;
+ Spring Boot's empty console pattern keeps stdout clean for MCP
+ JSON-RPC framing.
-->
- <springProfile name="stdio">
- <root level="OFF"/>
- </springProfile>
</configuration>
\ No newline at end of file
diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml
new file mode 100644
index 0000000..9463f02
--- /dev/null
+++ b/src/main/resources/logback.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!--
+ Early logback configuration loaded BEFORE Spring Boot initializes.
+
+ Logback's own initialization discovers this file (logback.xml) and
+ applies it immediately. Without it, logback falls through to its
+ BasicConfigurator, which writes internal status messages (|-INFO,
+ |-WARN) directly to stdout — corrupting the MCP STDIO JSON-RPC
+ framing in native images.
+
+ Spring Boot subsequently loads logback-spring.xml, which overrides
+ this configuration with profile-specific settings (HTTP vs STDIO).
+-->
+<configuration>
+ <statusListener class="ch.qos.logback.core.status.NopStatusListener"/>
+</configuration>
diff --git a/src/test/java/org/apache/solr/mcp/server/MainTest.java
b/src/test/java/org/apache/solr/mcp/server/MainTest.java
index 1b9ae42..92d921b 100644
--- a/src/test/java/org/apache/solr/mcp/server/MainTest.java
+++ b/src/test/java/org/apache/solr/mcp/server/MainTest.java
@@ -21,6 +21,7 @@ import org.apache.solr.mcp.server.indexing.IndexingService;
import org.apache.solr.mcp.server.metadata.SchemaService;
import org.apache.solr.mcp.server.search.SearchService;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
@@ -33,6 +34,7 @@ import
org.springframework.test.context.bean.override.mockito.MockitoBean;
*/
@SpringBootTest
@ActiveProfiles("test")
+@DisabledInNativeImage
class MainTest {
@MockitoBean
diff --git
a/src/test/java/org/apache/solr/mcp/server/collection/CollectionServiceTest.java
b/src/test/java/org/apache/solr/mcp/server/collection/CollectionServiceTest.java
index 81777d0..51d31a3 100644
---
a/src/test/java/org/apache/solr/mcp/server/collection/CollectionServiceTest.java
+++
b/src/test/java/org/apache/solr/mcp/server/collection/CollectionServiceTest.java
@@ -37,11 +37,13 @@ import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
+@DisabledInNativeImage
class CollectionServiceTest {
@Mock
diff --git
a/src/test/java/org/apache/solr/mcp/server/containerization/DockerImageStdioIntegrationTest.java
b/src/test/java/org/apache/solr/mcp/server/containerization/DockerImageStdioIntegrationTest.java
index 26e6a27..7efb11e 100644
---
a/src/test/java/org/apache/solr/mcp/server/containerization/DockerImageStdioIntegrationTest.java
+++
b/src/test/java/org/apache/solr/mcp/server/containerization/DockerImageStdioIntegrationTest.java
@@ -110,6 +110,10 @@ class DockerImageStdioIntegrationTest {
DockerImageName.parse(DOCKER_IMAGE)).withNetwork(network).withEnv("SOLR_URL",
"http://solr:8983/solr/")
.withEnv("SPRING_DOCKER_COMPOSE_ENABLED", "false")
.withLogConsumer(new
Slf4jLogConsumer(log).withPrefix("MCP-SERVER"))
+ // Keep stdin open so the STDIO MCP server does not
exit on EOF.
+ // Native images start in milliseconds and read stdin
immediately;
+ // without this the container exits before the test can
observe it.
+ .withCreateContainerCmdModifier(cmd ->
cmd.withStdinOpen(true))
// Give the application time to start (STDIO mode
doesn't produce logs to wait
// for)
.withStartupTimeout(Duration.ofSeconds(60));
diff --git
a/src/test/java/org/apache/solr/mcp/server/metadata/SchemaServiceTest.java
b/src/test/java/org/apache/solr/mcp/server/metadata/SchemaServiceTest.java
index 964c3a5..00e9b75 100644
--- a/src/test/java/org/apache/solr/mcp/server/metadata/SchemaServiceTest.java
+++ b/src/test/java/org/apache/solr/mcp/server/metadata/SchemaServiceTest.java
@@ -30,6 +30,7 @@ import
org.apache.solr.client.solrj.response.schema.SchemaRepresentation;
import org.apache.solr.client.solrj.response.schema.SchemaResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledInNativeImage;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -39,6 +40,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
* functionality with various scenarios including success and error cases.
*/
@ExtendWith(MockitoExtension.class)
+@DisabledInNativeImage
class SchemaServiceTest {
@Mock