Per the SSE specification (WHATWG HTML Living Standard 9.2.6), an event with no explicit event field MUST be dispatched as a message event. HttpClientStreamableHttpTransport previously used strict equality and silently dropped such frames in the reconnect/GET stream path, causing server-initiated notifications to never reach the handler. Extract classification into a package-private isMessageEvent helper and cover with parameterized unit tests.
Closes gh-885
- DefaultJsonSchemaValidator now emits a neutral message;
- Call sites in ToolInputValidator and the server output handlers
prepend their own context prefix,
- Integration test assertions strengthened accordingly.
Closes#986
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
* address review comments
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
* address review comments
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
---------
Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
Add URL-type elicitation schema support allowing servers to request URL
input from users during tool execution. This enables out-of-band
interactions like payment processing or API key entry.
Breaking changes:
- `ElicitRequest` changed from a `record` to an `interface`.
- The original `ElicitRequest` record was renamed to `ElicitFormRequest`.
- `McpClient` builder `elicitation()` methods now accept `ElicitFormRequest` instead of `ElicitRequest`.
New APIs:
- `ElicitUrlRequest` record for URL-mode elicitation.
- `urlElicitation()` builder methods in `McpClient`.
- `elicitationCompleteConsumer()` and `elicitationCompleteConsumers()` builder methods in `McpClient`.
- `sendElicitationComplete()` methods in `McpAsyncServer` and `McpSyncServer`.
- `McpError.URL_ELICITATION_REQUIRED` and `McpSchema.ErrorCodes.URL_ELICITATION_REQUIRED`.
- `ElicitationCompleteNotification` record and `METHOD_NOTIFICATION_ELICITATION_COMPLETE` constant.
Co-authored-by: Daniel Garnier-Moiroux <git@garnier.wf>
Co-authored-by: Sainath Reddy Bobbala <bsnr@amazon.com>
Use explicit package names instead of a wildcard glob to avoid
embedding mcp-core classes into the jackson module JARs.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The logging is sometimes too verbose and uses inappropriate level. With this
change there should be less disturbing logs and less duplication.
Notable changes:
* `LifeCycleInitializer#handleException` - duplicated log, already handled in
transports that use the initializer.
* `McpClientSession#sendRequest` - an MCP protocol level error in JSON-RPC is
not really a reason for ERROR level log. Using INFO with more details.
* `DefaultJsonSchemaValidator` - ERROR logs in `validate` are always logged by
the users of this method. `validateSchema` surfaces as
`IllegalArgumentException` and can be logged at higher levels by the user.
Also: remove DEBUG logs from mcp-test module.
Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
Adds an opt-in McpClient builder option `applyElicitationDefaults(boolean)`
that, when enabled, fills missing keys of an accepted ElicitResult.content
with `default` values declared in the requestedSchema before returning the
result to the server. Mirrors the TypeScript SDK's applyElicitationDefaults
behavior, but exposed as a local client config rather than a wire capability.
Co-authored-by: Sainath Reddy Bobbala <bsnr@amazon.com>
Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
Add Icon record and icons field to Implementation, Resource,
ResourceTemplate, Prompt, and Tool records per SEP-973. Add
websiteUrl and description fields to Implementation.
All fields are optional and backward compatible. Existing
constructors and builders continue to work unchanged.
Icon.src is validated as required per the spec.
Icon.theme field supports light/dark theme variants.
Includes serialization, deserialization, round-trip, and backward
compatibility tests for all modified records.
Closes modelcontextprotocol#694
Co-authored-by: Sainath Reddy Bobbala <bsnr@amazon.com>
MCP embeds JSON Schema documents in three places — Tool.inputSchema,
Tool.outputSchema, and ElicitRequest.requestedSchema — and SEP-1613
mandates that these documents conform to JSON Schema 2020-12 by default.
Servers now reject malformed schemas at both build time (McpServer.build())
and runtime (McpAsyncServer/McpStatelessAsyncServer.addTool()), returning
an IllegalArgumentException that identifies the offending field and
references SEP-1613. Elicitation requests whose requestedSchema violates
the meta-schema are rejected before being sent to the client.
Schemas that explicitly declare a different dialect via $schema are accepted
without meta-schema validation, since 2020-12 is the default, not the only
permitted dialect.
Refine meta-schema loading and deprecate orphan JsonSchemaValidator
Resolves#700
Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
Instead of fully breaking the API, this is a step
which depreactes the existing non-argument builder.
It allows the users to gradually migrate while preserving
the necessary checks.
Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
Co-authored-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
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>
Recent changes don't coerce null completion arguments to empty lists so we have
to check for null when handling prompt completions.
Resolves#932
Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
The MCP specification evolves continuously; domain types must absorb
new fields and subtypes without breaking existing clients or servers.
On the 1.x line this is structurally prevented by sealed interfaces,
which make it impossible to add a permitted subtype without breaking
exhaustive pattern-match switch expressions in caller code. This
commit opens the 2.0 release line, where those constraints are lifted
and serialization is made self-contained — independent of any global
ObjectMapper configuration.
Breaking changes for users migrating from 1.x
- Sealed interfaces removed from JSONRPCMessage, Request, Result,
Notification, ResourceContents, CompleteReference and Content.
Exhaustive switch expressions over these types must add a default
branch.
- Prompt(name, description, null) no longer silently coerces null
arguments to an empty list. Use Prompt.withDefaults() to preserve
the previous behaviour.
- CompleteCompletion.total and .hasMore are now absent from the wire
when not set, rather than being emitted as null.
- ServerParameters no longer carries Jackson annotations; it is an
internal configuration class, not a wire type.
What now works that did not before
- CompleteReference polymorphic dispatch (PromptReference vs
ResourceReference) works through a plain readValue or convertValue
call — no hand-rolled map inspection required.
- LoggingLevel deserialization is lenient: unknown level strings
produce null instead of throwing.
- All domain records now tolerate unknown JSON fields, so a client
built against an older SDK version will not fail when a newer server
sends fields it does not yet recognise.
- Null optional fields are consistently absent from serialized output
regardless of ObjectMapper configuration.
Documentation
- CONTRIBUTING adds an "Evolving wire-serialized records" section: a
9-rule recipe and example for adding a field safely.
- MIGRATION-2.0 documents all breaking changes listed above.
Follow-up coming next
Several spec-required fields (e.g. JSONRPCError.code/message,
ProgressNotification.progress, CreateMessageRequest.maxTokens,
CallToolResult.content) are stored as nullable Java types without a
null guard. If constructed with null, the NON_ABSENT rule silently
omits them, producing invalid wire JSON without throwing. Fix: compact
canonical constructors with Assert.notNull, following the pattern
already in JSONRPCRequest.
Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
Both HttpClientSseClientTransport and HttpClientStreamableHttpTransport
set Content-Type to 'application/json' without specifying the charset.
While Java's BodyPublishers.ofString() uses UTF-8 by default, the
missing charset in the header can cause the server to interpret the
request body using a different encoding (e.g., ISO-8859-1), corrupting
non-ASCII characters such as Chinese tool names.
Explicitly set Content-Type to 'application/json; charset=utf-8' in
POST requests on both client transports.
Fixes#260
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Daniel Garnier-Moiroux <git@garnier.wf>
Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
Deprecate Builder.customizeRequest() in HttpClientSseClientTransport and HttpClientStreamableHttpTransport
customizeRequest() executes its consumer once at build time, freezing
headers into the shared requestBuilder. This silently breaks OAuth
token refresh scenarios where the Authorization header needs to be
updated after the transport is built.
Add @Deprecated and update Javadoc to clarify the build-time-only
semantics and guide users toward httpRequestCustomizer() or
asyncHttpRequestCustomizer() which run on every request.
Closes#788
Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
Resolves#356
Clarify the two-tier error model:
- Recoverable tool errors: use CallToolResult with isError(true)
- Protocol-level errors: throw McpError / let exceptions propagate as JSON-RPC errors
Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>