From d3f3e79c14abc8293f89896be683137ba31fe0b2 Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Fri, 20 Nov 2026 17:58:27 -0500 Subject: [PATCH 1/2] chore(deps): upgrade to Spring Boot 4.2.0 and Spring AI 2.1.0 - Spring Boot 4.1.1 -> 4.2.0, Spring AI 2.0.1 -> 2.1.0. - Drop the mcp-bom 2.0.1 pin. Spring AI 2.1.0 depends on MCP SDK 2.2.0 itself, and the pin, declared ahead of spring-ai-bom, would have held the SDK back at 2.0.1 under "first declaration wins". - opentelemetry-logback-appender 2.28.1-alpha -> 2.34.0-alpha, the release built against Boot 4.2's OpenTelemetry 1.68.0. The old appender left opentelemetry-api-incubator at 1.62.0-alpha, which fails OpenTelemetrySdk creation with NoClassDefFoundError: io/opentelemetry/api/internal/ConfigUtil. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- AGENTS.md | 13 +++++++------ CHANGELOG.md | 2 +- build.gradle.kts | 8 +------- dev-docs/graalvm-native-image.md | 11 +++++++---- gradle/libs.versions.toml | 15 +++------------ 5 files changed, 19 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 72abf222..45bdb213 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ Solr MCP Server is a Spring AI Model Context Protocol (MCP) server that enables - **Status:** Apache incubating project (v1.0.0-SNAPSHOT) - **Java:** 25+ (centralized in build.gradle.kts) -- **Framework:** Spring Boot 4.1.1, Spring AI 2.0.1 +- **Framework:** Spring Boot 4.2.0, Spring AI 2.1.0 - **License:** Apache 2.0 ## Common Commands @@ -146,7 +146,7 @@ Configuration files: `application-stdio.properties`, `application-http.propertie ### SBOM Architecture CycloneDX SBOM generation is wired by applying the `org.cyclonedx.bom` plugin, -version **3.4.1**. Spring Boot 4.1.1's `CyclonedxPluginAction` recognises 3.x and +version **3.4.1**. Spring Boot 4's `CyclonedxPluginAction` recognises 3.x and auto-configures the `cyclonedxBom` task (type `org.cyclonedx.gradle.CyclonedxAggregateTask`): it writes `build/reports/cyclonedx/application.cdx.json`, embeds that in the bootJar at `META-INF/sbom/application.cdx.json`, and sets the `Sbom-Format` / `Sbom-Location` @@ -335,8 +335,8 @@ buildpacks (`bootBuildImage -Pnative`). Key configuration: ### Spring Boot 4 Notes -The move from Spring Boot 3.5 / Spring AI 1.1 to Spring Boot 4.1.1 / Spring AI 2.0.1 -([release announcement](https://spring.io/blog/2026/06/12/spring-ai-2-0-0-GA-available-now)) +The move from Spring Boot 3.5 / Spring AI 1.1 to Spring Boot 4 / Spring AI 2 +([Spring AI 2.0 announcement](https://spring.io/blog/2026/06/12/spring-ai-2-0-0-GA-available-now)) changed these things; keep them in mind when reading older docs or PRs: - **Jackson 3:** `tools.jackson.databind` replaces `com.fasterxml.jackson.databind`. Annotations @@ -351,8 +351,9 @@ changed these things; keep them in mind when reading older docs or PRs: - **Observability:** Uses `spring-boot-starter-opentelemetry` for traces, metrics, and log export via OTLP. The `micrometer-tracing-bridge-otel` + manual OTel BOM approach and the Prometheus registry (`/actuator/prometheus`) are gone. -- **MCP SDK:** `io.modelcontextprotocol.sdk:mcp` 2.0.1 via `mcp-bom`, with the Jackson 3 - module (`mcp-json-jackson3`). +- **MCP SDK:** `io.modelcontextprotocol.sdk:mcp`, with the Jackson 3 module + (`mcp-json-jackson3`), at the version Spring AI depends on (2.2.0 under Spring AI + 2.1.0). There is no separate SDK pin; Spring AI 2.0.1 needed one via `mcp-bom`. - **Span naming:** `@Observed` spans use `ClassName#methodName` (PascalCase) instead of the earlier `class-name#method-name` (kebab-case). diff --git a/CHANGELOG.md b/CHANGELOG.md index d8c00aa3..ee277feb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## [Unreleased] -Apache Solr MCP 1.0.0 is the project's first release: a Model Context Protocol (MCP) server that lets AI assistants search, index and manage Apache Solr. It runs over STDIO for desktop and IDE clients, or over HTTP for remote use with OAuth2 authentication on by default. It is built on Spring Boot 4.1 and Spring AI 2.0, works with Solr 9.4 through 10, and ships as a JAR (Java 25), a multi-architecture JVM Docker image and GraalVM native images. +Apache Solr MCP 1.0.0 is the project's first release: a Model Context Protocol (MCP) server that lets AI assistants search, index and manage Apache Solr. It runs over STDIO for desktop and IDE clients, or over HTTP for remote use with OAuth2 authentication on by default. It is built on Spring Boot 4.2 and Spring AI 2.1, works with Solr 9.4 through 10, and ships as a JAR (Java 25), a multi-architecture JVM Docker image and GraalVM native images. ### Added diff --git a/build.gradle.kts b/build.gradle.kts index 36072d6a..6a84e65f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -94,7 +94,7 @@ java { // CycloneDX SBOM // ============== -// What we no longer configure: *output*. Spring Boot 4.1.1's `CyclonedxPluginAction` +// What we no longer configure: *output*. Spring Boot 4's `CyclonedxPluginAction` // auto-configures the `cyclonedxBom` task (type `org.cyclonedx.gradle.CyclonedxAggregateTask`) // for cyclonedx 3.x -- it sets the output to `build/reports/cyclonedx/application.cdx.json` // and makes the bootJar embed it at `META-INF/sbom/application.cdx.json`. The @@ -202,12 +202,6 @@ dependencies { dependencyManagement { imports { - // Declared before spring-ai-bom: the dependency-management plugin uses - // Maven "first declaration wins" semantics. spring-ai-bom does not manage - // the MCP SDK at all -- Spring AI 2.0.1 depends on mcp 2.0.0 directly -- - // so this BOM is what lifts the whole SDK to 2.0.1 as one coherent set - // rather than pinning mcp-core and leaving mcp-json-jackson3 behind. - mavenBom("io.modelcontextprotocol.sdk:mcp-bom:${libs.versions.mcp.sdk.get()}") mavenBom("org.springframework.ai:spring-ai-bom:${libs.versions.spring.ai.get()}") } } diff --git a/dev-docs/graalvm-native-image.md b/dev-docs/graalvm-native-image.md index 930d052a..85f0d97f 100644 --- a/dev-docs/graalvm-native-image.md +++ b/dev-docs/graalvm-native-image.md @@ -204,10 +204,13 @@ four `--initialize-at-build-time` entries in `nativeImageBuildArgs`: proxy classes that cannot be build-time initialized; including it breaks the build. -**OTel dependency alignment.** Spring Boot 4.1 manages the OpenTelemetry SDK -(`opentelemetry-api:1.62.0`) through the starter, so the logback appender is -held at `2.28.1-alpha` — the newest release built against `1.62.0`, whose -transitive `opentelemetry-api-incubator:1.62.0-alpha` matches. A newer appender +**OTel dependency alignment.** Spring Boot 4.2 manages the OpenTelemetry SDK +(`opentelemetry-api:1.68.0`) through the starter, so the logback appender is +held at `2.34.0-alpha` — the newest release built against `1.68.0`, whose +transitive `opentelemetry-api-incubator:1.68.0-alpha` matches. Boot does not +manage the incubator, so a stale appender leaves it behind while the SDK moves +on: on Boot 4.2 the 1.62 incubator fails `OpenTelemetrySdk` creation with +`NoClassDefFoundError: io/opentelemetry/api/internal/ConfigUtil`. A newer appender is built against a newer API that the Boot BOM would downgrade, risking a `NoSuchMethodError` (an older one pulls an incubator lacking `DeclarativeConfigProperties.get(String)`, which SB4's `OpenTelemetrySdk` diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 0c7771e9..d89638d2 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -16,7 +16,7 @@ # [versions] # Build plugins -spring-boot = "4.1.1" +spring-boot = "4.2.0" spring-dependency-management = "1.1.7" errorprone-plugin = "5.1.1" jib = "3.5.4" @@ -26,18 +26,12 @@ cyclonedx-plugin = "3.4.1" changelog-plugin = "2.5.0" # Main dependencies -spring-ai = "2.0.1" +spring-ai = "2.1.0" solr = "10.0.0" mcp-server-security = "0.1.14" -# MCP Java SDK. Spring AI 2.0.1 pulls 2.0.0 transitively; 2.0.1 fixes error -# handling when a handler is not registered on a stateless server (our HTTP -# profile), empty-completion handling for unmatched refs, and adds bounded -# reads on the HTTP and STDIO transports. Drop this pin once a Spring AI -# release ships 2.0.1 or later itself. -mcp-sdk = "2.0.1" # OpenTelemetry -opentelemetry-logback-appender = "2.28.1-alpha" +opentelemetry-logback-appender = "2.34.0-alpha" commonmark = "0.30.0" @@ -75,9 +69,6 @@ spring-ai-starter-mcp-server-webmvc = { module = "org.springframework.ai:spring- spring-ai-spring-boot-docker-compose = { module = "org.springframework.ai:spring-ai-spring-boot-docker-compose" } spring-ai-spring-boot-testcontainers = { module = "org.springframework.ai:spring-ai-spring-boot-testcontainers" } -# MCP Java SDK (pinned ahead of what Spring AI 2.0.1 resolves; see [versions]) -mcp-bom = { module = "io.modelcontextprotocol.sdk:mcp-bom", version.ref = "mcp-sdk" } - # MCP Security mcp-server-security = { module = "org.springaicommunity:mcp-server-security", version.ref = "mcp-server-security" } From 25e96ceddb7dba60a454471340b250a57f87fb2c Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Sat, 14 Nov 2026 10:26:16 -0500 Subject: [PATCH 2/2] feat(mcp): serve the MCP 2026-07-28 revision with MCP_PROTOCOL=modern Spring AI 2.1.0 ships the modern MCP server for the 2026-07-28 spec revision: no initialize handshake or session, server/discover, _meta on every request, and Mcp-Method/Mcp-Name headers on a single POST /mcp. MCP_PROTOCOL=modern turns it on for the HTTP and STDIO profiles. The defaults stay on the 2025 revisions (stateless HTTP, streamable STDIO) because the new revision is not wire-compatible with today's clients. - Allow the Mcp-Method and Mcp-Name headers in the HTTP CORS config. - Work around two Spring AI 2.1.0 modern STDIO bugs: the JVM exited right after startup because the stdin reader runs on daemon threads, and a request sent at launch could be read before the context was ready. - Add HTTP, method-security and STDIO integration tests that speak raw 2026-07-28 JSON-RPC, since the SDK has no modern client yet. - Document the mode in docs/modern-protocol.md, with the setting in the README, AGENTS.md, THREAT_MODEL.md, the architecture and native-image dev-docs, the HTTP security CORS list and the CHANGELOG. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- AGENTS.md | 16 +- CHANGELOG.md | 1 + README.md | 2 + THREAT_MODEL.md | 5 +- dev-docs/ARCHITECTURE.md | 7 + dev-docs/graalvm-native-image.md | 7 + docs/modern-protocol.md | 102 +++++++ docs/security/http.md | 4 +- .../ModernStdioTransportConfiguration.java | 107 +++++++ .../security/HttpSecurityConfiguration.java | 10 +- .../resources/application-http.properties | 7 +- .../resources/application-stdio.properties | 3 + .../McpModernProtocolHttpIntegrationTest.java | 281 ++++++++++++++++++ .../McpModernProtocolMethodSecurityTest.java | 154 ++++++++++ ...McpModernProtocolStdioIntegrationTest.java | 140 +++++++++ .../mcp/server/modern/ModernMcpRequests.java | 79 +++++ .../server/security/McpInspectorCorsTest.java | 25 ++ 17 files changed, 942 insertions(+), 8 deletions(-) create mode 100644 docs/modern-protocol.md create mode 100644 src/main/java/org/apache/solr/mcp/server/config/ModernStdioTransportConfiguration.java create mode 100644 src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolHttpIntegrationTest.java create mode 100644 src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolMethodSecurityTest.java create mode 100644 src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolStdioIntegrationTest.java create mode 100644 src/test/java/org/apache/solr/mcp/server/modern/ModernMcpRequests.java diff --git a/AGENTS.md b/AGENTS.md index 45bdb213..4f26eb8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,6 +141,12 @@ count. - **STDIO** (default): For Claude Desktop integration. Uses stdin/stdout for communication. Spring Web disabled. - **HTTP**: For MCP Inspector and remote access. Servlet-based with optional OAuth2 security. +Both transports speak the 2025 MCP revisions by default (`stateless` HTTP, `streamable` +STDIO; up to 2025-11-25). `MCP_PROTOCOL=modern` switches either one to the 2026-07-28 +revision, served by the modern server in MCP Java SDK 2.2.0 (the first GA SDK release +with it) that Spring AI 2.1.0 auto-configures. It is opt-in because the revisions are not +wire-compatible. See [docs/modern-protocol.md](docs/modern-protocol.md). + Configuration files: `application-stdio.properties`, `application-http.properties` ### SBOM Architecture @@ -298,7 +304,10 @@ buildpacks (`bootBuildImage -Pnative`). Key configuration: `--spring.profiles.active=$nativeProfile` where `nativeProfile` is `stdio` by default or `http` if `-Pprofile=http` is passed. Activating both profiles during AOT picks `servlet` and forces Tomcat regardless of runtime - `PROFILES`, breaking stdio — hence one native image per profile. + `PROFILES`, breaking stdio — hence one native image per profile. The MCP + protocol revision is frozen the same way: Spring AI picks the modern server + with `@ConditionalOnProperty`, so `MCP_PROTOCOL` at runtime has no effect on a + native image (see [docs/modern-protocol.md](docs/modern-protocol.md)). - **Cross-platform builds:** `bootBuildImage` compiles inside a Linux builder container, so it works on any host OS (macOS, Linux, Windows). Multi-arch (amd64+arm64) is handled in CI via a GitHub Actions matrix; local builds @@ -354,6 +363,8 @@ changed these things; keep them in mind when reading older docs or PRs: - **MCP SDK:** `io.modelcontextprotocol.sdk:mcp`, with the Jackson 3 module (`mcp-json-jackson3`), at the version Spring AI depends on (2.2.0 under Spring AI 2.1.0). There is no separate SDK pin; Spring AI 2.0.1 needed one via `mcp-bom`. + SDK 2.2.0 is the first GA release with the 2026-07-28 ("modern") server, behind + `MCP_PROTOCOL=modern`. - **Span naming:** `@Observed` spans use `ClassName#methodName` (PascalCase) instead of the earlier `class-name#method-name` (kebab-case). @@ -489,6 +500,9 @@ Remaining known differences from Solr 9: Environment variables: - `SOLR_URL`: Solr URL (default: `http://localhost:8983/solr/`) - `PROFILES`: Transport mode (`stdio` or `http`) +- `MCP_PROTOCOL`: MCP spec revision. Unset = 2025 revisions (`stateless` HTTP, `streamable` + STDIO); `modern` = 2026-07-28. Sets `spring.ai.mcp.server.protocol`; fixed at build time in + native images. - `OAUTH2_ISSUER_URI`: OAuth2 issuer URL (HTTP mode only) - `OTEL_SAMPLING_PROBABILITY`: trace sampling rate (default `1.0`) - `OTEL_TRACES_URL` / `OTEL_METRICS_URL` / `OTEL_LOGS_URL`: OTLP/HTTP endpoints diff --git a/CHANGELOG.md b/CHANGELOG.md index ee277feb..21c93695 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Apache Solr MCP 1.0.0 is the project's first release: a Model Context Protocol ( - **Schema inspection and additive changes**: `get-schema`, `add-fields` and `add-field-types`. The schema tools only add; they never change or remove existing fields or field types. - **Prompts, resources and completions**: guided prompts (`explore-collections`, `setup-collection`, `search-collection`, `index-data`, `view-schema`, `design-schema`), the `solr://collections` and `solr://{collection}/schema` resources, and collection-name completion for their arguments. - **STDIO and HTTP transports**: STDIO is the default; `PROFILES=http` serves stateless streamable HTTP. +- **MCP 2026-07-28 protocol, opt-in**: `MCP_PROTOCOL=modern` serves the newest MCP spec revision (no `initialize` handshake or session, `server/discover`, `Mcp-Method`/`Mcp-Name` headers) over HTTP or STDIO, with every tool, resource, prompt and completion. Built on the modern server in MCP Java SDK 2.2.0, the SDK's first GA release with this revision. The default stays on the 2025 revisions that current clients speak. - **OAuth2 security for HTTP, on by default**: JWT bearer tokens from the issuer in `OAUTH2_ISSUER_URI`, with audience validation and configurable CORS origins (`MCP_CORS_ALLOWED_ORIGINS`). Setup guides cover Auth0 and Keycloak. - **Docker images**: `apache/solr-mcp`, a JVM image (amd64 and arm64) that serves both transports, and GraalVM native images for each transport (`-native-stdio`, `-native-http`) on GHCR. - **Observability in HTTP mode**: OpenTelemetry traces, metrics and logs exported over OTLP/HTTP, with a span for every tool call and logs correlated to the trace they were written in. diff --git a/README.md b/README.md index 53e3e9a9..4ff48f77 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ The server reads configuration from environment variables. The essentials: |----------|-------------|---------| | `SOLR_URL` | Solr base URL | `http://localhost:8983/solr/` | | `PROFILES` | Transport mode: `stdio` (default, for Claude Desktop) or `http` (remote / multi-client) | `stdio` | +| `MCP_PROTOCOL` | MCP spec revision: the 2025 revisions today's clients speak (default), or `modern` for the [2026-07-28 revision](docs/modern-protocol.md) | `stateless` (HTTP), `streamable` (STDIO) | Running in **HTTP mode** — OAuth2, CORS, and the `HTTP_SECURITY_ENABLED` toggle (secured by default) — is covered in the [security docs](docs/security/). Tracing, metrics and log-export env vars (`OTEL_SAMPLING_PROBABILITY`, `OTEL_TRACES_URL`, `OTEL_METRICS_URL`, `OTEL_LOGS_URL`) are covered in [Observability](docs/observability.md). @@ -214,6 +215,7 @@ Running in **HTTP mode** — OAuth2, CORS, and the `HTTP_SECURITY_ENABLED` toggl - [Quick start](#quick-start) · [Client setup](docs/clients/) — Claude Desktop, Claude Code, Codex, ChatGPT, VS Code, Cursor, JetBrains, Zed, MCP Inspector - [Tutorial: your first collection](docs/tutorial.md) — index a dataset twice, schemaless then with a designed schema, and see why field types matter - [Observability](docs/observability.md) — OpenTelemetry traces, metrics, logs +- [MCP 2026-07-28 protocol (`MCP_PROTOCOL=modern`)](docs/modern-protocol.md) — opting in to the newest spec revision, and what it changes for clients - Security: [Deployment model (single-tenant)](docs/security/deployment-model.md) · [STDIO model](docs/security/stdio.md) · [HTTP model](docs/security/http.md) · OAuth2 setup: [Auth0](docs/security/auth0.md) · [Keycloak](docs/security/keycloak.md) **Developing it** diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 7495c26e..22faf979 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -211,11 +211,12 @@ reaching the backend Solr directly, bypassing this server, is out of model (§3) | `PROFILES` | `stdio` | Selects transport. `stdio` = no network listener, OS-user trust. `http` = network listener, OAuth2. The two are **different threat models**; this document covers both. | Q-transport | | `HTTP_SECURITY_ENABLED` | `true` | HTTP mode is **secured by default**. `false` activates an unsecured filter chain — every MCP/actuator endpoint anonymous. Documented as "local development only… unsafe on any network-reachable deployment." | Q-httpsec | | `OAUTH2_ISSUER_URI` | empty (placeholder) | With HTTP security on and no issuer, the chain still returns 401/403 on every non-permitted endpoint (locked down, no token validator). A real issuer enables JWT signature/issuer/exp/**audience** validation. | Q-httpsec | +| `MCP_PROTOCOL` | unset (`stateless` HTTP, `streamable` STDIO; 2025 revisions) | `modern` serves the MCP 2026-07-28 revision (MCP Java SDK 2.2.0's modern server): no `initialize`/session, `server/discover`, `Mcp-Method`/`Mcp-Name` headers (added to the CORS header allowlist). The same `@PreAuthorize` checks guard every entry point. Multi-round-trip requests return a sealed `requestState`, keyed per instance unless `spring.ai.mcp.server.modern.request-state-secret` is set. Fixed at build time in native images. | *(documented — [docs/modern-protocol.md](docs/modern-protocol.md))* | | `MCP_CORS_ALLOWED_ORIGINS` | MCP Inspector localhost proxy | Explicit CORS allowlist; wildcard-with-credentials is rejected by construction (`setAllowedOrigins`, not patterns). | *(documented)* | | `SOLR_USERNAME` / `SOLR_PASSWORD` | unset | When both set, static HTTP Basic Auth to backend Solr on every request; when unset, unauthenticated backend calls. | Q-backendcreds | -**How HTTP mode enforces auth** *(maintainer — Q-transport.)*: the transport -is streamable HTTP running in **stateless** mode +**How HTTP mode enforces auth** *(maintainer — Q-transport.)*: by default the +transport is streamable HTTP running in **stateless** mode (`spring.ai.mcp.server.protocol=stateless`), so there is no sampling, progress or elicitation channel and no per-request context feature. `/mcp` is `permitAll()` at the filter-chain level; authentication is enforced instead by diff --git a/dev-docs/ARCHITECTURE.md b/dev-docs/ARCHITECTURE.md index 49a30724..b7e5ef48 100644 --- a/dev-docs/ARCHITECTURE.md +++ b/dev-docs/ARCHITECTURE.md @@ -108,6 +108,13 @@ Additional Jib benefits: - Requires additional security measures for production - Useful for testing and remote deployments +#### MCP protocol revision + +Both transports speak the 2025 MCP revisions by default. `MCP_PROTOCOL=modern` serves the +2026-07-28 revision instead (no `initialize` handshake or session, `server/discover`), using +the modern server in MCP Java SDK 2.2.0 that Spring AI 2.1.0 auto-configures. The tools, +resources and prompts are the same in both. See [modern-protocol.md](../docs/modern-protocol.md). + ### Document Processing The document creator pattern allows for: diff --git a/dev-docs/graalvm-native-image.md b/dev-docs/graalvm-native-image.md index 85f0d97f..801dee28 100644 --- a/dev-docs/graalvm-native-image.md +++ b/dev-docs/graalvm-native-image.md @@ -103,6 +103,13 @@ This is also why the JVM Jib image can be dual-mode while the native images cannot: the JVM image makes the `web-application-type` decision at *runtime* from the `PROFILES` env var; the native image already made it at *build time*. +The MCP protocol revision is frozen the same way. Spring AI chooses between the +2025-revision servers and the 2026-07-28 ("modern") server with +`@ConditionalOnProperty` on `spring.ai.mcp.server.protocol`, which `MCP_PROTOCOL` +sets, so a native image serves whichever revision was in effect when `processAot` +ran (the 2025 revisions by default) and ignores `MCP_PROTOCOL` at `docker run` +time. See [docs/modern-protocol.md](../docs/modern-protocol.md#native-images). + ## Why Jib for JVM, Paketo for native - **Jib (JVM image).** Plain `java -jar` entrypoint, no launcher script, so diff --git a/docs/modern-protocol.md b/docs/modern-protocol.md new file mode 100644 index 00000000..2426c9df --- /dev/null +++ b/docs/modern-protocol.md @@ -0,0 +1,102 @@ +# MCP 2026-07-28 protocol (`MCP_PROTOCOL=modern`) + +Solr MCP Server can serve the +[2026-07-28 revision](https://modelcontextprotocol.io/specification/2026-07-28) of the +Model Context Protocol. The server is the modern one in MCP Java SDK 2.2.0, the first GA +SDK release to support that revision, as auto-configured by Spring AI 2.1.0. + +It is **opt-in**. The 2026-07-28 revision is not wire-compatible with the 2025 revisions, +and most clients in use today (MCP Inspector, Claude Desktop, the Java, Python and TypeScript +SDK clients) still speak the 2025 revisions. Turn it on only when your clients speak the new +revision. + +| Transport | Default (`MCP_PROTOCOL` unset) | `MCP_PROTOCOL=modern` | +|-----------|--------------------------------|-----------------------| +| HTTP (`PROFILES=http`) | `stateless` streamable HTTP, 2025 revisions | 2026-07-28 revision on `POST /mcp` | +| STDIO (default profile) | `streamable`, 2025 revisions | 2026-07-28 revision, newline-delimited JSON-RPC | + +## Turning it on + +```bash +# HTTP +PROFILES=http MCP_PROTOCOL=modern SOLR_URL=http://localhost:8983/solr/ \ + java -jar build/libs/solr-mcp-.jar + +# STDIO +MCP_PROTOCOL=modern SOLR_URL=http://localhost:8983/solr/ \ + java -jar build/libs/solr-mcp-.jar +``` + +`MCP_PROTOCOL` sets `spring.ai.mcp.server.protocol`, so +`-Dspring.ai.mcp.server.protocol=modern` works the same way. + +Every tool, resource, resource template, prompt and completion is served unchanged in +either mode, and the `@PreAuthorize` scopes on tools apply the same way. + +## What changes for clients + +- **No `initialize` handshake and no session.** A client calls `server/discover` to learn + the server's capabilities, `serverInfo` and instructions. There is no `Mcp-Session-Id`, + and `ping` is gone. +- **Every request carries `_meta`** with the protocol version, the client's capabilities and + the client's info: + + ```json + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "list-collections", + "arguments": {}, + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { "name": "my-client", "version": "1.0.0" } + } + } + } + ``` + +- **Over HTTP, requests carry routing headers.** `MCP-Protocol-Version: 2026-07-28` and + `Mcp-Method` on every request, plus `Mcp-Name` (the tool, prompt or resource URI) on + `tools/call`, `prompts/get` and `resources/read`. A header that doesn't match the body is + rejected with HTTP 400 and JSON-RPC error `-32020`. + +## CORS + +The HTTP profile's CORS configuration allows the `Mcp-Method`, `Mcp-Name` and +`MCP-Protocol-Version` headers, so browser-based clients can send them from the allowed +origins. + +## Running more than one instance + +When a request takes more than one round trip, the modern server seals a `requestState` +for the client to send back. Unless a secret is set, each instance seals it with its own +random key, so the follow-up must reach the same instance. Behind a load balancer, give every +instance the same secret of at least 32 bytes: + +```properties +spring.ai.mcp.server.modern.request-state-secret=${MCP_REQUEST_STATE_SECRET} +``` + +## Native images + +The transport is chosen by `@ConditionalOnProperty` conditions, which a GraalVM native image +fixes at build time. To get a native image that serves the modern protocol, set +`MCP_PROTOCOL=modern` when running `nativeCompile`. This has not been tested yet. + +## Spring AI 2.1 STDIO workaround + +In Spring AI 2.1.0, the modern STDIO transport has two problems +when the server runs without a web server, as it does in the STDIO profile: + +1. The SDK's stdin reader runs on daemon threads and Spring AI does not block on it, so the + JVM exits as soon as startup finishes and the first request gets no answer. +2. The reader starts before the application context has finished starting, so a request sent + right at launch can fail with `-32602` (`clientCapabilities is malformed`), `-32603`, or no + answer at all. + +`ModernStdioTransportConfiguration` replaces the transport bean in modern STDIO mode only. It +starts reading stdin once the application is ready and keeps the JVM alive on a non-daemon +thread until stdin closes. It can be removed once Spring AI fixes both upstream. diff --git a/docs/security/http.md b/docs/security/http.md index cc39da79..8513f486 100644 --- a/docs/security/http.md +++ b/docs/security/http.md @@ -111,7 +111,9 @@ The CORS allowlist is intentionally narrow: credentials is the [classic CWE-942 misconfiguration](https://cwe.mitre.org/data/definitions/942.html). - **Methods**: `GET, POST, DELETE, OPTIONS` — the methods used by the MCP Streamable HTTP transport. -- **Headers**: `Authorization, Content-Type, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID`. +- **Headers**: `Authorization, Content-Type, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID`, + plus `Mcp-Method, Mcp-Name`, the routing headers of the + [2026-07-28 revision](../modern-protocol.md) (`MCP_PROTOCOL=modern`). - **Credentials**: allowed (Bearer-token flows). Add origins via `MCP_CORS_ALLOWED_ORIGINS` (comma-separated). Real production diff --git a/src/main/java/org/apache/solr/mcp/server/config/ModernStdioTransportConfiguration.java b/src/main/java/org/apache/solr/mcp/server/config/ModernStdioTransportConfiguration.java new file mode 100644 index 00000000..9e51e9d8 --- /dev/null +++ b/src/main/java/org/apache/solr/mcp/server/config/ModernStdioTransportConfiguration.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 io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper; +import io.modelcontextprotocol.modern.server.McpServer; +import io.modelcontextprotocol.modern.server.transport.StdioMcpTransport; +import java.util.concurrent.atomic.AtomicBoolean; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import tools.jackson.databind.json.JsonMapper; + +/** + * Makes the STDIO server on the MCP 2026-07-28 revision ({@code MCP_PROTOCOL=modern}) reliable. + * + *

Spring AI 2.1.0 starts the SDK's modern {@link StdioMcpTransport} as soon as its lifecycle + * bean starts, which is before the application context has finished refreshing, and the transport + * runs on daemon threads only. Measured against the packaged jar, that causes two failures a + * desktop client hits on its very first request: + * + *

    + *
  • A request written to stdin straight after launch, as clients do, is read while the context + * is still starting. The answer is then random: the correct result, {@code -32602 + * clientCapabilities is malformed}, {@code -32603 Internal error}, or nothing at all. The + * same request sent a few seconds later always succeeds. + *
  • STDIO is a non-web application, so once {@code main} returns no non-daemon thread holds the + * JVM open. The process exits a moment after startup and a request still in flight is dropped + * without a response. + *
+ * + *

This transport therefore starts reading stdin only once the application is ready, and holds + * one non-daemon thread until the session ends (the client closes stdin, or the context shuts + * down). It replaces the auto-configured transport, which is {@code @ConditionalOnMissingBean}. + * Remove this class once Spring AI defers and keeps alive the modern STDIO transport itself. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty(name = "spring.ai.mcp.server.stdio", havingValue = "true") +@ConditionalOnProperty(name = "spring.ai.mcp.server.protocol", havingValue = "modern") +class ModernStdioTransportConfiguration { + + static final String KEEP_ALIVE_THREAD_NAME = "solr-mcp-stdio-keep-alive"; + + @Bean + StdioMcpTransport mcpModernStdioTransport( + McpServer mcpServer, @Qualifier("mcpServerJsonMapper") JsonMapper jsonMapper) { + return new ReadyStdioMcpTransport(mcpServer, new JacksonMcpJsonMapper(jsonMapper)); + } + + /** + * A modern STDIO transport that starts reading on {@link ApplicationReadyEvent} and keeps a + * non-daemon thread alive for the length of the session. + */ + static final class ReadyStdioMcpTransport extends StdioMcpTransport + implements ApplicationListener { + + private final Sinks.Empty session = Sinks.empty(); + + private final AtomicBoolean started = new AtomicBoolean(); + + ReadyStdioMcpTransport(McpServer server, JacksonMcpJsonMapper jsonMapper) { + super(server, jsonMapper); + } + + /** Called by Spring AI's lifecycle during refresh; reading waits for the ready event. */ + @Override + public Mono start() { + return session.asMono(); + } + + @Override + public void onApplicationEvent(ApplicationReadyEvent event) { + if (!started.compareAndSet(false, true)) { + return; + } + Mono reading = super.start(); + Thread keepAlive = + new Thread( + () -> { + reading.onErrorComplete().block(); + session.tryEmitEmpty(); + }, + KEEP_ALIVE_THREAD_NAME); + keepAlive.setDaemon(false); + keepAlive.start(); + } + } +} diff --git a/src/main/java/org/apache/solr/mcp/server/security/HttpSecurityConfiguration.java b/src/main/java/org/apache/solr/mcp/server/security/HttpSecurityConfiguration.java index ca43fa78..3f4bd940 100644 --- a/src/main/java/org/apache/solr/mcp/server/security/HttpSecurityConfiguration.java +++ b/src/main/java/org/apache/solr/mcp/server/security/HttpSecurityConfiguration.java @@ -123,15 +123,19 @@ public CorsConfigurationSource corsConfigurationSource() { configuration.setAllowedOrigins(allowedOrigins); // Only the HTTP methods used by the MCP Streamable HTTP transport. configuration.setAllowedMethods(List.of("GET", "POST", "DELETE", "OPTIONS")); - // Only the headers the MCP specification requires for the Streamable HTTP - // transport. + // Only the headers the MCP specification requires: Mcp-Session-Id and + // Last-Event-ID for the Streamable HTTP transport, Mcp-Method and Mcp-Name for + // the 2026-07-28 revision (MCP_PROTOCOL=modern), which a browser client such as + // the MCP Inspector must send on every request. configuration.setAllowedHeaders( List.of( "Authorization", "Content-Type", "Mcp-Session-Id", "MCP-Protocol-Version", - "Last-Event-ID")); + "Last-Event-ID", + "Mcp-Method", + "Mcp-Name")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); diff --git a/src/main/resources/application-http.properties b/src/main/resources/application-http.properties index 5940a782..dd21458d 100644 --- a/src/main/resources/application-http.properties +++ b/src/main/resources/application-http.properties @@ -16,7 +16,12 @@ # spring.main.web-application-type=servlet spring.ai.mcp.server.type=sync -spring.ai.mcp.server.protocol=stateless +# MCP protocol revision. stateless (default) serves the 2025 spec revisions that today's +# clients (MCP Inspector, Claude Desktop, the Java/Python/TypeScript SDK clients) speak. +# MCP_PROTOCOL=modern serves the 2026-07-28 revision instead: no initialize handshake or +# session, server/discover, and Mcp-Method/Mcp-Name headers on a single POST /mcp endpoint. +# The two are not wire-compatible, so pick the one your clients speak. See docs/modern-protocol.md. +spring.ai.mcp.server.protocol=${MCP_PROTOCOL:stateless} spring.ai.mcp.server.stdio=false # Docker Compose integration: automatically start Solr and other services on bootRun. # Spring Boot detects compose.yaml and starts declared services before the application context. diff --git a/src/main/resources/application-stdio.properties b/src/main/resources/application-stdio.properties index 18dbd737..42c69f11 100644 --- a/src/main/resources/application-stdio.properties +++ b/src/main/resources/application-stdio.properties @@ -25,6 +25,9 @@ spring.main.banner-mode=off # the same JVM, which Spring Framework 7's test-context pausing makes routine. # STDIO stays silent because logback-spring.xml declares no appenders for it. spring.ai.mcp.server.stdio=true +# MCP protocol revision over STDIO: streamable (default, 2025 spec revisions) or +# modern (2026-07-28 revision). See docs/modern-protocol.md. +spring.ai.mcp.server.protocol=${MCP_PROTOCOL:streamable} spring.autoconfigure.exclude=\ org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration,\ org.springframework.boot.security.autoconfigure.actuate.web.servlet.ManagementWebSecurityAutoConfiguration diff --git a/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolHttpIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolHttpIntegrationTest.java new file mode 100644 index 00000000..c59d11df --- /dev/null +++ b/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolHttpIntegrationTest.java @@ -0,0 +1,281 @@ +/* + * 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.modern; + +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.PROTOCOL_VERSION; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.firstText; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.parse; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.request; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.result; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import java.util.Map; +import org.apache.solr.mcp.server.TestDocuments; +import org.apache.solr.mcp.server.TestcontainersConfiguration; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * The HTTP server on the MCP 2026-07-28 revision, selected with {@code MCP_PROTOCOL=modern}. + * + *

Covers every primitive the server exposes (tools, resources, resource templates, prompts and + * completions) over the single POST endpoint, plus the parts of the revision that differ from the + * stateless transport: {@code server/discover} instead of {@code initialize}, and the {@code + * Mcp-Method} / {@code Mcp-Name} headers that must match the body. + */ +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "http.security.enabled=false", + "spring.docker.compose.enabled=false", + "MCP_PROTOCOL=modern" + }) +@ActiveProfiles("http") +@Import(TestcontainersConfiguration.class) +@Tag("integration") +@Testcontainers(disabledWithoutDocker = true) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class McpModernProtocolHttpIntegrationTest { + + private static final String COLLECTION = "modern-protocol-test"; + + private static final HttpClient HTTP = HttpClient.newHttpClient(); + + @LocalServerPort private int port; + + private HttpResponse post( + String method, Map params, @Nullable String mcpName) throws Exception { + HttpRequest.Builder builder = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/mcp")) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("Mcp-Method", method) + .header("MCP-Protocol-Version", PROTOCOL_VERSION) + .POST(HttpRequest.BodyPublishers.ofString(request(method, params))); + if (mcpName != null) { + builder.header("Mcp-Name", mcpName); + } + return HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + } + + private Map call( + String method, Map params, @Nullable String mcpName) throws Exception { + HttpResponse response = post(method, params, mcpName); + assertEquals(200, response.statusCode(), () -> method + " failed: " + response.body()); + return result(response.body()); + } + + private Map callTool(String name, Map arguments) + throws Exception { + Map result = + call("tools/call", Map.of("name", name, "arguments", arguments), name); + assertEquals( + Boolean.FALSE, result.get("isError"), () -> name + " returned an error: " + result); + return result; + } + + @Test + @Order(1) + @SuppressWarnings("unchecked") + void discoverAdvertisesTheRevisionAndEveryCapability() throws Exception { + Map discover = call("server/discover", Map.of(), null); + + assertEquals(List.of(PROTOCOL_VERSION), discover.get("supportedVersions")); + Map capabilities = (Map) discover.get("capabilities"); + for (String capability : List.of("tools", "resources", "prompts", "completions")) { + assertTrue( + capabilities.containsKey(capability), + () -> "server/discover must advertise " + capability + ": " + capabilities); + } + Map serverInfo = + (Map) + ((Map) discover.get("_meta")).get("io.modelcontextprotocol/serverInfo"); + assertEquals("solr-mcp", serverInfo.get("name")); + assertTrue( + ((String) discover.get("instructions")).contains("list-collections"), + "the server instructions must reach the client through server/discover"); + } + + @Test + @Order(2) + @SuppressWarnings("unchecked") + void toolsListKeepsEveryToolAndItsHints() throws Exception { + List> tools = + (List>) call("tools/list", Map.of(), null).get("tools"); + List names = tools.stream().map(t -> t.get("name")).toList(); + + for (String tool : + List.of( + "search", + "list-collections", + "get-collection-stats", + "check-health", + "create-collection", + "index-json-documents", + "index-markdown-documents", + "get-schema", + "add-fields", + "add-field-types")) { + assertTrue(names.contains(tool), () -> "missing tool " + tool + " in " + names); + } + Map search = + tools.stream().filter(t -> "search".equals(t.get("name"))).findFirst().orElseThrow(); + assertEquals( + Boolean.TRUE, + ((Map) search.get("annotations")).get("readOnlyHint"), + "behavior hints must survive the conversion to the modern schema"); + } + + @Test + @Order(3) + void toolsCallCreatesIndexesAndSearches() throws Exception { + callTool("create-collection", Map.of("name", COLLECTION)); + callTool( + "index-json-documents", + Map.of( + "collection", + COLLECTION, + "documents", + TestDocuments.json( + """ + [ + {"id": "1", "title": "Modern MCP", "category": "protocol"}, + {"id": "2", "title": "Stateless servers", "category": "protocol"}, + {"id": "3", "title": "Solr basics", "category": "search"} + ] + """))); + + String text = + firstText( + callTool( + "search", + Map.of( + "collection", + COLLECTION, + "query", + "*:*", + "filterQueries", + List.of("category:protocol")))); + + Map response = parse(text); + assertEquals(2, ((Number) response.get("numFound")).intValue(), text); + } + + @Test + @Order(4) + @SuppressWarnings("unchecked") + void resourcesAndTemplatesAreReadable() throws Exception { + List> resources = + (List>) call("resources/list", Map.of(), null).get("resources"); + assertTrue(resources.stream().anyMatch(r -> "solr://collections".equals(r.get("uri")))); + + List> templates = + (List>) + call("resources/templates/list", Map.of(), null).get("resourceTemplates"); + assertTrue( + templates.stream() + .anyMatch(t -> "solr://{collection}/schema".equals(t.get("uriTemplate")))); + + String schemaUri = "solr://" + COLLECTION + "/schema"; + List> contents = + (List>) + call("resources/read", Map.of("uri", schemaUri), schemaUri).get("contents"); + assertTrue( + ((String) contents.getFirst().get("text")).contains("fields"), + "the schema resource template must resolve against the live collection"); + } + + @Test + @Order(5) + @SuppressWarnings("unchecked") + void promptsAndCompletionsWork() throws Exception { + List> prompts = + (List>) call("prompts/list", Map.of(), null).get("prompts"); + assertTrue(prompts.stream().anyMatch(p -> "search-collection".equals(p.get("name")))); + + Map prompt = + call( + "prompts/get", + Map.of( + "name", + "search-collection", + "arguments", + Map.of("collection", COLLECTION, "question", "protocol docs")), + "search-collection"); + assertFalse(((List) prompt.get("messages")).isEmpty()); + + Map completion = + (Map) + call( + "completion/complete", + Map.of( + "ref", + Map.of("type", "ref/prompt", "name", "search-collection"), + "argument", + Map.of("name", "collection", "value", "modern")), + null) + .get("completion"); + assertTrue( + ((List) completion.get("values")).contains(COLLECTION), + () -> "collection-name completion must offer the new collection: " + completion); + } + + @Test + @Order(6) + void mcpNameHeaderMustMatchTheBody() throws Exception { + HttpResponse response = + post( + "tools/call", + Map.of("name", "list-collections", "arguments", Map.of()), + "search" /* deliberately not the tool in the body */); + + assertEquals(400, response.statusCode(), response.body()); + assertEquals(-32020, errorCode(response.body()), "the revision's header-mismatch error code"); + } + + @Test + @Order(7) + void legacyInitializeIsNotServed() throws Exception { + HttpResponse response = post("initialize", Map.of(), null); + + // The 2026-07-28 revision removes the handshake, so a pre-2026 client cannot connect to a + // server in modern mode. That is why MCP_PROTOCOL defaults to stateless. + assertNotEquals(200, response.statusCode(), response.body()); + } + + @SuppressWarnings("unchecked") + private static int errorCode(String body) { + return ((Number) ((Map) parse(body).get("error")).get("code")).intValue(); + } +} diff --git a/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolMethodSecurityTest.java b/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolMethodSecurityTest.java new file mode 100644 index 00000000..88a86b70 --- /dev/null +++ b/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolMethodSecurityTest.java @@ -0,0 +1,154 @@ +/* + * 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.modern; + +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.PROTOCOL_VERSION; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.parse; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.request; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.result; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Map; +import org.apache.solr.mcp.server.TestcontainersConfiguration; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.web.filter.OncePerRequestFilter; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * {@code @PreAuthorize} on tools and resources must keep working when the server runs on the + * 2026-07-28 revision. + * + *

Method security reads the {@code SecurityContext} of the thread that invokes the tool. The + * modern transport has its own request manager, so if it ever ran handlers on another thread an + * authenticated caller would be rejected (and an anonymous one could never be told apart). This + * test drives real HTTP requests through the secured filter chain: a stand-in for the bearer-token + * filter authenticates requests that carry {@value #TEST_USER_HEADER}, and the same tool call must + * fail without it and succeed with it. + */ +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"spring.docker.compose.enabled=false", "MCP_PROTOCOL=modern"}) +@ActiveProfiles("http") +@Import({TestcontainersConfiguration.class, McpModernProtocolMethodSecurityTest.TestAuth.class}) +@Tag("integration") +@Testcontainers(disabledWithoutDocker = true) +class McpModernProtocolMethodSecurityTest { + + static final String TEST_USER_HEADER = "X-Test-User"; + + private static final HttpClient HTTP = HttpClient.newHttpClient(); + + @LocalServerPort private int port; + + private HttpResponse listCollections(boolean authenticated) throws Exception { + HttpRequest.Builder builder = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/mcp")) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("Mcp-Method", "tools/call") + .header("Mcp-Name", "list-collections") + .header("MCP-Protocol-Version", PROTOCOL_VERSION) + .POST( + HttpRequest.BodyPublishers.ofString( + request( + "tools/call", Map.of("name", "list-collections", "arguments", Map.of())))); + if (authenticated) { + builder.header(TEST_USER_HEADER, "alice"); + } + return HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + } + + @Test + void anonymousCallToSecuredToolIsRejected() throws Exception { + HttpResponse response = listCollections(false); + + Map body = parse(response.body()); + boolean rejected = + body.containsKey("error") + || (body.get("result") instanceof Map r && Boolean.TRUE.equals(r.get("isError"))); + assertTrue( + rejected, + "list-collections carries @PreAuthorize(\"isAuthenticated()\"); an anonymous modern-protocol " + + "call must not run it: " + + response.body()); + } + + @Test + void authenticatedCallToSecuredToolSucceeds() throws Exception { + HttpResponse response = listCollections(true); + + assertEquals(200, response.statusCode(), response.body()); + assertEquals( + Boolean.FALSE, + result(response.body()).get("isError"), + "an authenticated caller must reach the tool; a rejection here means the modern transport " + + "ran the tool without the request's SecurityContext: " + + response.body()); + } + + /** + * Authenticates any request carrying {@value #TEST_USER_HEADER}. Registered after the Spring + * Security chain, exactly where a bearer-token filter's result would be visible to the + * dispatcher, so the tool sees the context only if the transport invokes it on the request + * thread. + */ + @TestConfiguration(proxyBeanMethods = false) + static class TestAuth { + + @Bean + FilterRegistrationBean testUserFilter() { + OncePerRequestFilter filter = + new OncePerRequestFilter() { + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + String user = request.getHeader(TEST_USER_HEADER); + if (user != null) { + SecurityContextHolder.getContext() + .setAuthentication( + UsernamePasswordAuthenticationToken.authenticated( + user, "n/a", AuthorityUtils.createAuthorityList("ROLE_USER"))); + } + chain.doFilter(request, response); + } + }; + return new FilterRegistrationBean<>(filter); + } + } +} diff --git a/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolStdioIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolStdioIntegrationTest.java new file mode 100644 index 00000000..7a08b2e3 --- /dev/null +++ b/src/test/java/org/apache/solr/mcp/server/modern/McpModernProtocolStdioIntegrationTest.java @@ -0,0 +1,140 @@ +/* + * 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.modern; + +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.PROTOCOL_VERSION; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.firstText; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.request; +import static org.apache.solr.mcp.server.modern.ModernMcpRequests.result; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import org.apache.solr.mcp.server.BuildInfoReader; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.testcontainers.containers.SolrContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +/** + * The packaged jar over STDIO on the 2026-07-28 revision ({@code MCP_PROTOCOL=modern}), the way a + * desktop client launches it: one JSON-RPC message per line on stdin and stdout, no {@code + * initialize} handshake. + * + *

Also guards the STDIO invariant that nothing but JSON-RPC reaches stdout: every line read back + * must parse as a response. + */ +@Tag("integration") +@Testcontainers(disabledWithoutDocker = true) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class McpModernProtocolStdioIntegrationTest { + + @Container + static final SolrContainer SOLR = + new SolrContainer( + DockerImageName.parse(System.getProperty("solr.test.image", "solr:9.9.0-slim"))); + + @SuppressWarnings("NotNullFieldNotInitialized") // set by start() + private Process server; + + @SuppressWarnings("NotNullFieldNotInitialized") // set by start() + private BufferedWriter stdin; + + @SuppressWarnings("NotNullFieldNotInitialized") // set by start() + private BufferedReader stdout; + + @BeforeAll + void start() throws Exception { + String solrUrl = "http://" + SOLR.getHost() + ":" + SOLR.getMappedPort(8983) + "/solr/"; + ProcessBuilder builder = + new ProcessBuilder("java", "-jar", "build/libs/" + BuildInfoReader.getJarFileName()) + .redirectError(ProcessBuilder.Redirect.DISCARD); + builder.environment().put("SOLR_URL", solrUrl); + builder.environment().put("MCP_PROTOCOL", "modern"); + builder.environment().put("SPRING_DOCKER_COMPOSE_ENABLED", "false"); + server = builder.start(); + stdin = + new BufferedWriter( + new OutputStreamWriter(server.getOutputStream(), StandardCharsets.UTF_8)); + stdout = + new BufferedReader(new InputStreamReader(server.getInputStream(), StandardCharsets.UTF_8)); + } + + @AfterAll + void stop() throws Exception { + server.destroy(); + if (!server.waitFor(10, TimeUnit.SECONDS)) { + server.destroyForcibly(); + } + } + + private Map send(String method, Map params) throws Exception { + stdin.write(request(method, params)); + stdin.newLine(); + stdin.flush(); + String line = + CompletableFuture.supplyAsync( + () -> { + try { + return stdout.readLine(); + } catch (java.io.IOException e) { + throw new java.io.UncheckedIOException(e); + } + }) + .get(90, TimeUnit.SECONDS); + assertNotNull(line, "the server closed stdout instead of answering " + method); + return result(line); + } + + /** + * The first request goes out the moment the process starts, before Spring has finished starting, + * because that is what desktop clients do. On Spring AI 2.1.0's own modern STDIO transport this + * request got a random answer (or none); see {@code ModernStdioTransportConfiguration}. + */ + @Test + @SuppressWarnings("unchecked") + void firstRequestRightAfterLaunchThenDiscoverAndList() throws Exception { + Map collections = + send( + "tools/call", + Map.of("name", "list-collections", "arguments", Map.of())); // no Mcp-Name over STDIO + assertEquals( + Boolean.FALSE, collections.get("isError"), () -> "list-collections failed: " + collections); + assertTrue(firstText(collections).startsWith("["), "list-collections returns a JSON array"); + + Map discover = send("server/discover", Map.of()); + assertEquals(List.of(PROTOCOL_VERSION), discover.get("supportedVersions")); + + List> tools = + (List>) send("tools/list", Map.of()).get("tools"); + assertTrue(tools.stream().anyMatch(t -> "search".equals(t.get("name")))); + } +} diff --git a/src/test/java/org/apache/solr/mcp/server/modern/ModernMcpRequests.java b/src/test/java/org/apache/solr/mcp/server/modern/ModernMcpRequests.java new file mode 100644 index 00000000..b15e64ac --- /dev/null +++ b/src/test/java/org/apache/solr/mcp/server/modern/ModernMcpRequests.java @@ -0,0 +1,79 @@ +/* + * 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.modern; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** + * Builds and parses JSON-RPC messages for the MCP 2026-07-28 ("modern") protocol revision. + * + *

The MCP Java SDK that Spring AI 2.1 ships has a modern server but no modern client + * yet, so these tests speak the wire format directly. Under the 2026-07-28 revision there is no + * {@code initialize} handshake and no session: every request carries the protocol version and the + * client capabilities in {@code params._meta}, and clients learn the server's features from {@code + * server/discover}. + */ +final class ModernMcpRequests { + + /** The spec revision Spring AI 2.1.0 (MCP Java SDK 2.2.0) serves by default. */ + static final String PROTOCOL_VERSION = "2026-07-28"; + + static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final AtomicInteger IDS = new AtomicInteger(); + + private ModernMcpRequests() {} + + /** A JSON-RPC request whose {@code params._meta} carries the version and capabilities. */ + static String request(String method, Map params) { + Map meta = new HashMap<>(); + meta.put("io.modelcontextprotocol/protocolVersion", PROTOCOL_VERSION); + meta.put("io.modelcontextprotocol/clientCapabilities", Map.of()); + meta.put( + "io.modelcontextprotocol/clientInfo", Map.of("name", "solr-mcp-tests", "version", "1")); + Map withMeta = new HashMap<>(params); + withMeta.put("_meta", meta); + return JSON.writeValueAsString( + Map.of( + "jsonrpc", "2.0", "id", IDS.incrementAndGet(), "method", method, "params", withMeta)); + } + + static Map parse(String json) { + return JSON.readValue(json, new TypeReference<>() {}); + } + + /** The {@code result} object of a JSON-RPC response, failing loudly on a JSON-RPC error. */ + @SuppressWarnings("unchecked") + static Map result(String json) { + Map response = parse(json); + if (response.containsKey("error")) { + throw new AssertionError("Expected a result but got a JSON-RPC error: " + json); + } + return (Map) response.get("result"); + } + + /** The text of the first content block of a {@code tools/call} result. */ + @SuppressWarnings("unchecked") + static String firstText(Map callToolResult) { + var content = (java.util.List>) callToolResult.get("content"); + return (String) content.getFirst().get("text"); + } +} diff --git a/src/test/java/org/apache/solr/mcp/server/security/McpInspectorCorsTest.java b/src/test/java/org/apache/solr/mcp/server/security/McpInspectorCorsTest.java index 374d3729..c34f8959 100644 --- a/src/test/java/org/apache/solr/mcp/server/security/McpInspectorCorsTest.java +++ b/src/test/java/org/apache/solr/mcp/server/security/McpInspectorCorsTest.java @@ -130,6 +130,31 @@ void inspectorTransportMethodsAreAllowed() throws Exception { } } + /** + * The 2026-07-28 revision ({@code MCP_PROTOCOL=modern}) requires {@code Mcp-Method} on every + * request and {@code Mcp-Name} on tools/call, prompts/get and resources/read. A browser client + * cannot send either unless preflight allows it, so leaving them out of the allowlist would make + * modern mode unusable from the Inspector while server-side tests stay green. + */ + @Test + void modernProtocolHeadersAreAllowed() throws Exception { + HttpResponse response = + preflight(INSPECTOR_ORIGIN, HttpMethod.POST, "Mcp-Method,Mcp-Name,MCP-Protocol-Version"); + + assertEquals(HttpStatus.OK.value(), response.statusCode()); + String allowed = + response + .headers() + .firstValue(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS) + .orElse("") + .toLowerCase(java.util.Locale.ROOT); + for (String header : List.of("mcp-method", "mcp-name", "mcp-protocol-version")) { + assertTrue( + allowed.contains(header), + () -> "preflight must allow " + header + "; Allow-Headers was: " + allowed); + } + } + @Test void unknownOriginIsRejected() throws Exception { assertEquals(