Mirror of https://github.com/modelcontextprotocol/java-sdk — The official Java SDK for Model Context Protocol servers and clients. Maintained in collaboration with Spring AI
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Dariusz Jędrzejczyk 22a0efa577 feat!: enforce required MCP spec fields in McpSchema; lenient wire deserialization (#928)
Every wire-serialized record in McpSchema now validates spec-required
fields at construction time. Wire deserialization is intentionally
lenient: a missing required field is replaced with a documented default
and a WARN is logged, instead of failing the parse. A required-first
builder convention is introduced across the schema so it is no longer
possible to obtain a builder that is missing required state.

Required-field guards
---------------------
Every wire record's compact constructor asserts non-null (and non-empty
for String identifiers like name, uri, uriTemplate, version) on its
spec-required components. Passing null now throws
IllegalArgumentException at construction time instead of silently
producing invalid JSON via @JsonInclude(NON_ABSENT). This applies to
the JSON-RPC envelopes, lifecycle types, resource/prompt/tool requests
and results, sampling and elicitation, content records, root, complete,
logging and progress notifications, and the two CompleteReference
implementations. See MIGRATION-2.0.md for the full list.

Lenient wire deserialization
----------------------------
For each of those records (except JSONRPCResponse.JSONRPCError, which
still fails fast) a @JsonCreator static `fromJson` factory substitutes
a documented default for any absent required field — "" for strings,
[] for collections, {} for maps, 0 / 0.0 for numerics, INFO for
LoggingLevel, USER for SamplingMessage.role, ASSISTANT for
CreateMessageResult.role, CANCEL for ElicitResult.action, {values=[]}
for CompleteResult.completion — and logs a WARN naming the field and
the value used. Application code can still observe a malformed message
and react, but the SDK no longer halts the conversation.

Builder convention
------------------
Records that have a builder gain a required-first factory method
`builder(req1, req2, …)`; setters for required fields are removed from
the builder so it cannot be left in an invalid state. Existing no-arg
`builder()` factories and required-field setters are kept where source
compatibility demands it but are marked @Deprecated. New builders are
also added for several records that previously had none (ProgressNotification,
JSONRPCError, CompleteRequest, list/result types, content records, ...).

JSON-RPC envelope ergonomics
----------------------------
Previously every JSON-RPC envelope had to be constructed via the
canonical record constructor and the literal "2.0" string had to be
threaded through every call site, e.g.

    new JSONRPCRequest("2.0", "tools/call", id, params)
    new JSONRPCResponse("2.0", id, result, null)
    new JSONRPCResponse("2.0", id, null, new JSONRPCError(code, message, null))

Now:

    new JSONRPCRequest("tools/call", id, params)              // jsonrpc defaulted
    new JSONRPCNotification("notifications/initialized")       // params optional
    JSONRPCResponse.result(id, result)                        // factory
    JSONRPCResponse.error(id, new JSONRPCError(code, message)) // 2-arg error

JSONRPCResponse's compact constructor additionally enforces the
JSON-RPC invariant that exactly one of `result` / `error` is set —
previously the SDK could build envelopes that violated the protocol.

CompleteReference changes
-------------------------
- PromptReference.equals/hashCode now key on `name` only (previously
  derived from identifier()+type()). Two refs with the same name but
  different titles now compare equal — code using PromptReference as a
  map/set key should be audited.
- PromptReference's compact constructor pins `type` to "ref/prompt"
  and logs a WARN if the caller supplies a different non-null value.
  The legacy two-arg `PromptReference(String type, String name)`
  constructor remains @Deprecated.
- ResourceReference's record components are reduced from (type, uri)
  to (uri) — positional construction breaks. The legacy
  `ResourceReference(String type, String uri)` constructor stays
  @Deprecated and ignores `type`.
- CompleteReference.identifier() is @Deprecated and now returns null
  via a default method on the interface.

Tests / refactor
----------------
Conformance harness, integration tests, sample apps, and internal
callers were migrated to the new builder factories and convenience
constructors. No semantic changes to client/server runtime behaviour
beyond the McpSchema changes above.

Docs
----
- MIGRATION-2.0.md: required-field section now covers the broader
  record set and the lenient-deserialization behaviour; PromptReference
  WARN behaviour and ResourceReference component reduction are
  documented; the JSON-RPC envelope section is rewritten to compare the
  pre-2.0 surface with the new one.
- CONTRIBUTING.md: the "Evolving wire-serialized records" recipe is
  split into two cases — adding a new optional field (existing rules)
  and adding/maintaining a spec-required field (new rules covering
  Assert in compact constructor, @JsonCreator fromJson with defaults
  and WARN, required-first builder factory).

Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
2026-05-04 21:01:46 +02:00
.github Update dependabot PR labels 2026-03-02 17:08:14 +01:00
.mvn/wrapper initial 2024-12-06 16:41:17 +01:00
conformance-tests feat!: enforce required MCP spec fields in McpSchema; lenient wire deserialization (#928) 2026-05-04 21:01:46 +02:00
docs docs: document best practice for handling argument errors in MCP tools (#891) 2026-04-02 11:07:04 +02:00
mcp Next development version 2026-03-13 13:31:03 +01:00
mcp-bom Next development version 2026-03-13 13:31:03 +01:00
mcp-core feat!: enforce required MCP spec fields in McpSchema; lenient wire deserialization (#928) 2026-05-04 21:01:46 +02:00
mcp-json-jackson2 Next development version 2026-03-13 13:31:03 +01:00
mcp-json-jackson3 Next development version 2026-03-13 13:31:03 +01:00
mcp-test feat!: enforce required MCP spec fields in McpSchema; lenient wire deserialization (#928) 2026-05-04 21:01:46 +02:00
.gitattributes initial 2024-12-06 16:41:17 +01:00
.gitignore Add embedded MkDocs documentation site (#795) 2026-02-15 19:00:21 +01:00
CODE_OF_CONDUCT.md Add Contributing Guidelines and Code of Conduct 2025-05-16 11:47:39 +02:00
CONTRIBUTING.md feat!: enforce required MCP spec fields in McpSchema; lenient wire deserialization (#928) 2026-05-04 21:01:46 +02:00
DEPENDENCY_POLICY.md Add governance documentation for SEP-1730 (#808) 2026-02-20 18:11:26 +01:00
LICENSE Update license text and GH actions 2025-01-28 14:36:31 +01:00
MIGRATION-1.0.md Add migration notes for 0.18.1 to 1.0.0 update (#828) 2026-02-23 14:21:04 +01:00
MIGRATION-2.0.md feat!: enforce required MCP spec fields in McpSchema; lenient wire deserialization (#928) 2026-05-04 21:01:46 +02:00
mkdocs.yml Move mcp-spring-webflux and mcp-spring-webmvc to Spring AI 2.0 (#805) 2026-02-20 15:39:36 +01:00
mvnw initial 2024-12-06 16:41:17 +01:00
mvnw.cmd initial 2024-12-06 16:41:17 +01:00
pom.xml Next development version 2026-03-13 13:31:03 +01:00
README.md docs: add conformance summary to README 2026-04-02 10:54:27 +02:00
ROADMAP.md Add governance documentation for SEP-1730 (#808) 2026-02-20 18:11:26 +01:00
SECURITY.md Update SECURITY.md to use GitHub Security Advisories 2026-02-20 11:27:32 +01:00
VERSIONING.md Add governance documentation for SEP-1730 (#808) 2026-02-20 18:11:26 +01:00

MCP Java SDK

License Build Status Maven Central Java Version

A set of projects that provide Java SDK integration for the Model Context Protocol. This SDK enables Java applications to interact with AI models and tools through a standardized interface, supporting both synchronous and asynchronous communication patterns.

📚 Reference Documentation

MCP Java SDK documentation

For comprehensive guides and SDK API documentation

Spring AI MCP documentation

Spring AI MCP extends the MCP Java SDK with Spring Boot integration, providing both client and server starters. The MCP Annotations - provides annotation-based method handling for MCP servers and clients in Java. The MCP Security - provides comprehensive OAuth 2.0 and API key-based security support for Model Context Protocol implementations in Spring AI. Bootstrap your AI applications with MCP support using Spring Initializer.

Development

Building from Source

./mvnw clean install -DskipTests

Running Tests

To run the tests you have to pre-install Docker and npx.

./mvnw test

Conformance Tests

The SDK is validated against the MCP conformance test suite at 0.1.15 version. Full details and instructions are in conformance-tests/VALIDATION_RESULTS.md.

Latest results:

Suite Result
Server ✅ 40/40 passed (100%)
Client 🟡 3/4 scenarios, 9/10 checks passed
Auth (Spring) 🟡 12/14 scenarios fully passing (98.9% checks)

To run the conformance tests locally you need npx installed.

# Server conformance
./mvnw compile -pl conformance-tests/server-servlet -am exec:java
npx @modelcontextprotocol/conformance server --url http://localhost:8080/mcp --suite active

# Client conformance
./mvnw clean package -DskipTests -pl conformance-tests/client-jdk-http-client -am
for scenario in initialize tools_call elicitation-sep1034-client-defaults sse-retry; do
  npx @modelcontextprotocol/conformance client \
    --command "java -jar conformance-tests/client-jdk-http-client/target/client-jdk-http-client-2.0.0-SNAPSHOT.jar" \
    --scenario $scenario
done

# Auth conformance (Spring HTTP Client)
./mvnw clean package -DskipTests -pl conformance-tests/client-spring-http-client -am
npx @modelcontextprotocol/conformance@0.1.15 client \
  --spec-version 2025-11-25 \
  --command "java -jar conformance-tests/client-spring-http-client/target/client-spring-http-client-2.0.0-SNAPSHOT.jar" \
  --suite auth

Contributing

Contributions are welcome! Please follow the Contributing Guidelines.

Team

  • Christian Tzolov
  • Dariusz Jędrzejczyk
  • Daniel Garnier-Moiroux

Architecture and Design Decisions

Introduction

Building a general-purpose MCP Java SDK requires making technology decisions in areas where the JDK provides limited or no support. The Java ecosystem is powerful but fragmented: multiple valid approaches exist, each with strong communities. Our goal is not to prescribe "the one true way," but to provide a reference implementation of the MCP specification that is:

  • Pragmatic – makes developers productive quickly
  • Interoperable – aligns with widely used libraries and practices
  • Pluggable – allows alternatives where projects prefer different stacks
  • Grounded in team familiarity – we chose technologies the team can be productive with today, while remaining open to community contributions that broaden the SDK

Key Choices and Considerations

The SDK had to make decisions in the following areas:

  1. JSON serialization – mapping between JSON and Java types

  2. Programming model – supporting asynchronous processing, cancellation, and streaming while staying simple for blocking use cases

  3. Observability – logging and enabling integration with metrics/tracing

  4. Remote clients and servers – supporting both consuming MCP servers (client transport) and exposing MCP endpoints (server transport with authorization)

The following sections explain what we chose, why it made sense, and how the choices align with the SDK's goals.

1. JSON Serialization

  • SDK Choice: Jackson for JSON serialization and deserialization, behind an SDK abstraction (package io.modelcontextprotocol.json in mcp-core)

  • Why: Jackson is widely adopted across the Java ecosystem, provides strong performance and a mature annotation model, and is familiar to the SDK team and many potential contributors.

  • How we expose it: Public APIs use a bundled abstraction. Jackson is shipped as the default implementation (mcp-json-jackson3), but alternatives can be plugged in.

  • How it fits the SDK: This offers a pragmatic default while keeping flexibility for projects that prefer different JSON libraries.

2. Programming Model

  • SDK Choice: Reactive Streams for public APIs, with Project Reactor as the internal implementation and a synchronous facade for blocking use cases

  • Why: MCP builds on JSON-RPC's asynchronous nature and defines a bidirectional protocol on top of it, enabling asynchronous and streaming interactions. MCP explicitly supports:

    • Multiple in-flight requests and responses
    • Notifications that do not expect a reply
    • STDIO transports for inter-process communication using pipes
    • Streaming transports such as Server-Sent Events and Streamable HTTP

    These requirements call for a programming model more powerful than single-result futures like CompletableFuture.

    • Reactive Streams: the Community Standard

      Reactive Streams is a small Java specification that standardizes asynchronous stream processing with backpressure. It defines four minimal interfaces (Publisher, Subscriber, Subscription, and Processor). These interfaces are widely recognized as the standard contract for async, non-blocking pipelines in Java.

    • Reactive Streams Implementation

      The SDK uses Project Reactor as its implementation of the Reactive Streams specification. Reactor is mature, widely adopted, provides rich operators, and integrates well with observability through context propagation. Team familiarity also allowed us to deliver a solid foundation quickly. We plan to convert the public API to only expose Reactive Streams interfaces. By defining the public API in terms of Reactive Streams interfaces and using Reactor internally, the SDK stays standards-based while benefiting from a practical, production-ready implementation.

    • Synchronous Facade in the SDK

      Not all MCP use cases require streaming pipelines. Many scenarios are as simple as "send a request and block until I get the result." To support this, the SDK provides a synchronous facade layered on top of the reactive core. Developers can stay in a blocking model when it's enough, while still having access to asynchronous streaming when needed.

  • How it fits the SDK: This design balances scalability, approachability, and future evolution such as Virtual Threads and Structured Concurrency in upcoming JDKs.

3. Observability

  • SDK Choice: SLF4J for logging; Reactor Context for observability propagation

  • Why: SLF4J is the de facto logging facade in Java, with broad compatibility. Reactor Context enables propagation of observability data such as correlation IDs and tracing state across async boundaries. This ensures interoperability with modern observability frameworks.

  • How we expose it: Public APIs log through SLF4J only, with no backend included. Observability metadata flows through Reactor pipelines. The SDK itself does not ship metrics or tracing implementations.

  • How it fits the SDK: This provides reliable logging by default and seamless integration with Micrometer, OpenTelemetry, or similar systems for metrics and tracing.

4. Remote MCP Clients and Servers

MCP supports both clients (applications consuming MCP servers) and servers (applications exposing MCP endpoints). The SDK provides support for both sides.

Client Transport in the SDK

  • SDK Choice: JDK HttpClient (Java 11+) as the default client

  • Why: The JDK HttpClient is built-in, portable, and supports streaming responses. This keeps the default lightweight with no extra dependencies.

  • How we expose it: MCP Client APIs are transport-agnostic. The core module ships with JDK HttpClient transport. Spring WebClient-based transport is available in Spring AI 2.0+.

  • How it fits the SDK: This ensures all applications can talk to MCP servers out of the box, while allowing richer integration in Spring and other environments.

Server Transport in the SDK

  • SDK Choice: Jakarta Servlet implementation in core

  • Why: Servlet is the most widely deployed Java server API, providing broad reach across blocking and non-blocking models without additional dependencies.

  • How we expose it: Server APIs are transport-agnostic. Core includes Servlet support. Spring WebFlux and WebMVC server transports are available in Spring AI 2.0+.

  • How it fits the SDK: This allows developers to expose MCP servers in the most common Java environments today, while enabling other transport implementations such as Netty, Vert.x, or Helidon.

Authorization in the SDK

  • SDK Choice: Pluggable authorization hooks for MCP servers; no built-in implementation

  • Why: MCP servers must restrict access to authenticated and authorized clients. Authorization needs differ across environments such as Spring Security, MicroProfile JWT, or custom solutions. Providing hooks avoids lock-in and leverages proven libraries.

  • How we expose it: Authorization is integrated into the server transport layer. The SDK does not include its own authorization system.

  • How it fits the SDK: This keeps server-side security ecosystem-neutral, while ensuring applications can plug in their preferred authorization strategy.

Project Structure of the SDK

The SDK is organized into modules to separate concerns and allow adopters to bring in only what they need:

  • mcp-bom – Dependency versions
  • mcp-core – Reference implementation (STDIO, JDK HttpClient, Servlet), JSON binding interface definitions
  • mcp-json-jackson2 – Jackson 2 implementation of JSON binding
  • mcp-json-jackson3 – Jackson 3 implementation of JSON binding
  • mcp – Convenience bundle (core + Jackson 3)
  • mcp-test – Shared testing utilities

Spring integrations (WebClient, WebFlux, WebMVC) are now part of Spring AI 2.0+ (group org.springframework.ai).

For example, a minimal adopter may depend only on mcp (core + Jackson), while a Spring-based application can use the Spring AI mcp-spring-webflux or mcp-spring-webmvc artifacts for deeper framework integration.

Additionally, mcp-test contains integration tests for mcp-core. mcp-core needs a JSON implementation to run full integration tests. Implementations such as mcp-json-jackson3, depend on mcp-core, and therefore cannot be imported in mcp-core for tests. Instead, all integration tests that need a JSON implementation are now in mcp-test, and use jackson3 by default. A jackson2 maven profile allows to run integration tests with Jackson 2, like so:

./mvnw -pl mcp-test -am -Pjackson2 test

Future Directions

The SDK is designed to evolve with the Java ecosystem. Areas we are actively watching include: Concurrency in the JDK – Virtual Threads and Structured Concurrency may simplify the synchronous API story

License

This project is licensed under the MIT License.