On this page
MCP
Integration with MCP (Model Context Protocol).
For this project, you can find a list of releases (with release notes) here: https://github.com/micronaut-projects/micronaut-mcp/releases
This section documents breaking changes between Micronaut MCP versions.
2.2.0
-
The STDIO server now accepts up to 16,777,216 UTF-16 code units per inbound JSON-RPC line, excluding the line terminator. A longer line ends the stdio session without a JSON-RPC error response. Clients that send large tool arguments must keep the entire serialized request within this limit.
-
With the HTTP transport, the requests and notifications handed to the SDK carry their parameters as parsed JSON:
McpSchema.JSONRPCRequest.params()andMcpSchema.JSONRPCNotification.params()are now anio.micronaut.json.tree.JsonNode(an object or an array) instead of aMap. They are still aMap(or aList) when the application replaces theMcpJsonMapperbean, even with a mapper that delegates to the Micronaut one. The SDK handlers convert the parameters with theMcpJsonMapper, so this only affects code that replaces or decorates theMcpStatelessServerHandlerbean and readsparams()directly. Such code can convert the parameters with theMcpJsonMapperbean, which accepts both forms:mcpJsonMapper.convertValue(request.params(), new TypeRef<Map<String, Object>>() { }). -
With the HTTP transport, a message that is not a valid JSON-RPC 2.0 request or notification gets HTTP 400 with the JSON-RPC error
-32600(Invalid Request), anullid and a message that names the problem. Before, such a message either got HTTP 500 or reached the SDK. This includes ajsonrpcmember that is missing or other than"2.0", amethodthat is missing or not a string, anidthat isnull, a boolean, a fractional number or larger than a 64-bit integer,paramsthat are neither an object nor an array, and a batch (an array of messages). -
With the HTTP transport, an exception other than an
McpErrorthat the SDK throws outside your tools, prompts, resources and completions, for example while it converts the request parameters, is logged atERRORand answered with the JSON-RPC error-32603and the messageInternal error, without the message of the exception. An exception other than anMcpErrorthrown by your prompts, resources and completions is also answered with-32603and the messageInternal error, and logged atWARNwith its stack trace, unless anMcpErrorExceptionMappermaps it: map the exceptions whose message the client may see. Tools report their failures as tool execution errors instead, see below. A notification whose handling fails is answered with the HTTP status of the error and no body, because a JSON-RPC error response needs an id. -
A
@ToolArgparameter is always a named property of the input schema of a tool, even when its type has a@JsonSchema. Only a parameter without@ToolArgcan provide the schema of the whole input. -
The
$idof generated JSON schemas, which clients see intools/list, defaults toclasspath:META-INF/schemas/<name>with Micronaut JSON Schema 2.3.2 and later, instead ofhttp://localhost:8080/schemas/<name>. Set themicronaut.jsonschema.baseUriannotation processor option to choose another base. -
A tool method that throws an unmapped exception now returns a result with
isErrorset totrueand a generic message identifying the tool. Argument binding and bean validation failures returnisErrorwith a message describing the invalid input. With the HTTP transport the response status is200instead of400or500. In particular, a bean validation failure of a tool argument is no longer the error-32602. ExistingMcpErrorExceptionMapperbeans still produce JSON-RPC errors for the exceptions they map. To answer with a JSON-RPC error, throw anio.modelcontextprotocol.spec.McpError, or map an exception that Micronaut MCP does not map itself with anMcpErrorExceptionMapper. Clients that detect a failed call by theerrormember of the JSON-RPC response must also checkisErrorin itsresult. Likewise, access logs, firewall rules and alerts that count4xxresponses no longer see tool arguments that fail validation, which are logged atDEBUGlevel. See Tool Errors. -
A tool failure that no
McpErrorExceptionMappermaps is logged by theio.micronaut.mcp.server.registry.ToolRegistrylogger atWARNlevel. The registry renders the exception and its stack trace on one log line. A tool that fails often for expected reasons, such as an unknown identifier, should return aCallToolResultwhoseisErroristrueinstead of throwing, which is not logged. See Tool Errors. -
The message of a structured content or tool input that does not match its JSON schema lists the schema errors, separated by semicolons, after the prefix the SDK adds, for example
Tool (moon-phase-at-date) input validation failed: /date: does not match the date pattern must be a valid RFC 3339 full-date. It no longer containsValidation failed: structuredContent does not match tool outputSchemanor theValidationMessageAdapterrepresentation of the errors. -
Every
@ResourceTemplatedeclaration must now specifyuriTemplate. Update any declarations that omit it before recompiling. -
The values of resource template variables are now percent-decoded before they are bound. This is URI decoding: a
+is no longer turned into a space, asURLDecoder.decodedid. Remove any decoding of the values from your methods, or they are decoded twice:%2525is bound as%25, which a second decoding turns into%. Values that used to arrive escaped can now contain control characters, such as a CR LF line break from%0D%0A, so methods that log or concatenate them must sanitize them. Malformed escapes, invalid UTF-8, and an encoded/(%2F) in a simple variable such as{path}yield an invalid params error. The same error applies when the SDK routes a URI to a template whose path it fails to match. To accept an encoded/, declare a reserved variable such as{+path}. See Resource Template Variable Decoding. -
The HTTP endpoint now validates the
OriginandMCP-Protocol-Versionrequest headers, as the MCP specification requires. A browser-based client whose origin is neither a loopback origin nor listed inmicronaut.mcp.server.transport-security.allowed-originsnow gets403 Forbidden; add its origin to the list (and enable CORS for it). A request with anMCP-Protocol-Versionheader naming a version the server does not support (it supports2025-03-26,2025-06-18and2025-11-25) now gets400 Bad Request. See Transport Security. -
With the HTTP transport, the server advertises
listChangedandsubscribeasfalse. This overrides thelist-changedandsubscribeproperties and anyBeanCreatedEventListenerofMcpSchema.ServerCapabilities.Builder, because the server cannot send notifications outside the response to a request. -
A server with
list-changedset totruefor tools, prompts or resources advertises that capability even when it has none of them, so they can be added at runtime. Clients may then list them and get an empty list. Setlist-changedtofalseif your clients should not see an empty capability. -
The LangChain4j MCP client connects to every connection of
micronaut.mcp.client.httpandmicronaut.mcp.client.stdiotogether.micronaut.mcp.client.transportis deprecated and no longer selects the transport: withSTDIO, the HTTP connections, including theembeddedServerconnection of an application that is itself an HTTP MCP server, are no longer left out, so their tools reach theMcpToolProvider. Remove the HTTP connections you do not want, and leave out the tools ofembeddedServerwith anMcpToolFilter. See LangChain4j MCP Client. -
The
McpToolProviderof the LangChain4j client skips the servers that cannot be reached instead of failing, and connects to each server when its client is first used rather than when the provider is created. While one request creates the client of a connection, the other requests get no tools from that server instead of waiting. -
With Micronaut Management, the new
mcphealth indicator of the LangChain4j client is down when any server cannot be reached, so/healthand/health/readinessanswer503. Disable it withendpoints.health.mcp.enabled=false. -
The LangChain4j
StdioMcpTransportandStreamableHttpMcpTransportbeans are prototypes owned and closed by their client, instead of singletons. Inject theMcpClientof a connection rather than its transport. -
The application fails to start when two MCP client connections have the same name, when an HTTP connection has no
url, or when a STDIO connection has nocommand. -
The Java SDK clients connect to their server when the bean is created, so injecting a client of a server that cannot be reached throws a
BeanInstantiationException, which can fail the startup of the application. Inject ajakarta.inject.Provideror aBeanProviderof the client to connect when it is first used. -
A connection has either a synchronous or an asynchronous Java SDK client: creating the second one fails. Declare a connection for each if the application needs both.
Micronaut MCP Server support is based on the MCP Java SDK.
To use it, add the following dependency:
implementation("io.micronaut.mcp:micronaut-mcp-server-java-sdk")Set the name and the version of your MCP server; both are required. You can also give it a title, a description, a website URL, icons (each with a src and optionally a mime-type, sizes and a theme), and instructions that clients may add to the model’s prompt:
micronaut.mcp.server.info.name=weather
micronaut.mcp.server.info.version=1.0.0
micronaut.mcp.server.info.title=Weather
micronaut.mcp.server.info.description=Forecasts by city
micronaut.mcp.server.info.website-url=https://example.com
micronaut.mcp.server.info.icons[0].src=https://example.com/weather.png
micronaut.mcp.server.info.icons[0].mime-type=image/png
micronaut.mcp.server.info.icons[0].sizes[0]=48x48
micronaut.mcp.server.info.icons[0].theme=light
micronaut.mcp.server.info.instructions=Ask for a city before asking for a forecast.|
Note
|
Without name and version, clients receive the default server information of the MCP Java SDK, and the other properties on this page are ignored: the server logs a warning at startup. Every icon requires a src that is an HTTPS URL or a data:image/… URI (an HTTP URL is accepted, for example for local development), the website-url must be an HTTPS or HTTP URL, neither may contain a user name or password, and an icon theme, when set, must be light or dark in lowercase; otherwise the server fails to start.
|
|
Warning
|
Every client that connects reads the server information, including the website-url and the icon sources, and the instructions in the response to initialize, and clients may add the instructions to the model’s prompt. Do not put secrets or internal details in them.
|
To create a server, you will need to define the property micronaut.mcp.server.transport
with one of the values STDIO, HTTP.
If you define the property micronaut.mcp.server.reactive with the value true, you can define primitives (tools, prompts or resources) with call handlers wrapped in a Project Reactor Mono.
The protocol currently defines two standard transport mechanisms for client-server communication: stdio (communication over standard in and standard out) and Streamable HTTP
For stdio transport, define the property micronaut.mcp.server.transport as STDIO.
For HTTP transport, define the property micronaut.mcp.server.transport as HTTP.
|
Warning
|
Server to Client communication via an SSE stream is not yet supported. The server responses are currently only of Content-Type: application/json.
|
For stdio transport, your configuration may look like
micronaut.mcp.server.transport=STDIO
micronaut.mcp.server.info.name=pgn-resources
micronaut.mcp.server.info.version=1.0.0For HTTP transport, your configuration may look like
micronaut.mcp.server.transport=HTTP
micronaut.mcp.server.info.name=pgn-resources
micronaut.mcp.server.info.version=1.0.0Based on the transport and reactive setting, an MCP Java SDK Server class instance is created with @Context scope.
micronaut.mcp.server.transport |
micronaut.mcp.server.reactive |
Server | Server Specification |
|---|---|---|---|
STDIO |
false |
|
|
STDIO |
true |
|
|
HTTP |
false |
|
|
HTTP |
true |
|
|
McpServer.SyncSpecification, McpServer.AsyncSpecification, McpServer.StatelessAsyncSpecification, McpServer.StatelessSyncSpecification are builder classes. Thus, you can create beans of type BeanCreatedEventListener to customize the server specification and creation further.
To create primitives (tools, prompts or resources), you will create beans of a particular type (typically in a bean factory). The bean type depends on the server type selected:
micronaut.mcp.server.transport |
micronaut.mcp.server.reactive |
Prompt Bean Type | Tool Bean Type | Resource Bean Type | Resource Template Bean Type |
|---|---|---|---|---|---|
STDIO |
false |
|
|
|
|
STDIO |
true |
|
|
|
|
HTTP |
false |
|
|
|
|
HTTP |
true |
|
|
|
|
The injectable McpSchema.ServerCapabilities bean exposes the capabilities configured through your primitive beans and the list-changed and subscribe properties. You can customize these capabilities with a BeanCreatedEventListener for McpSchema.ServerCapabilities.Builder.
To read the capabilities clients receive in the initialize response, call getServerCapabilities() on the active SDK server bean. For example, with HTTP and micronaut.mcp.server.tools.list-changed=true, the injectable capabilities bean reports tools.listChanged as true and the server advertises it as false.
The HTTP server turns off listChanged and subscribe because it can send notifications only during a request. A BeanCreatedEventListener that replaces the capabilities on the server specification itself can override these flags, but clients would then wait for notifications that never arrive. See Adding and Removing Primitives at Runtime.
|
Warning
|
If you use Standard Input/Output (stdio) protocol, your server MUST NOT write anything to its stdout.
|
Disable the Micronaut banner and configure Logback not to log to stdout.
For example, you can configure Logback to log to a file or to stderr (see <target>System.err</target> in the configuration file below):
<configuration>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDERR" />
</root>
</configuration>To test the MCP Server, implementation you can use the MCP Inspector
The MCP inspector is a developer tool for testing and debugging MCP servers.
Micronaut MCP ships MicronautMcpTransportContext, an extension to io.modelcontextprotocol.common.McpTransportContext, which allows you to access concepts such as the authenticated user, locale, host, etc.
With the HTTP transport, the context reads its values from the HTTP request the first time they are asked for, and it keeps the request reachable for as long as the context is reachable. Do not keep the context after the request is handled, for example in a cache or a background task: copy the values you need instead.
The host comes from the request headers (Forwarded, X-Forwarded-Host and Host by default), which the client can set. Do not use it for security decisions, such as building callback URLs or choosing a tenant, unless the host resolution is configured for your proxy, for example with micronaut.server.host-resolution.allowed-hosts.
Declare a parameter of type McpRequestContext in a tool, prompt, resource or completion method to report progress, send log messages to the client, check whether the client disconnected, or ask the client for information:
The parameter is not part of the tool’s input schema or of the prompt’s arguments. Its transportContext() is the transport context of the request, described in MCP Transport Context; it is typed as the SDK McpTransportContext.
McpRequestContext is an interface, so a unit test that calls a primitive method directly can pass a mock or its own implementation.
Progress
progress sends a notification only when the client sent a progress token with the request, in _meta.progressToken; otherwise it does nothing. progressToken() returns the token, or null. Since every progress notification repeats it, the token must be a string of at most 256 characters or an integer, as the protocol allows; another token is ignored, as if the client had not asked for progress.
Log messages
log sends a log message to the client. When a primitive declares an McpRequestContext parameter, the server advertises the logging capability, since it may send log messages.
The STDIO server applies the level a client sets with logging/setLevel. The stateless HTTP server returns a JSON-RPC Method not found error for a valid logging/setLevel request because it cannot apply a threshold across requests.
|
Warning
|
Log messages are sent to the client, and usually reach the language model. They are not server logs: as the specification requires, do not put credentials, personal data, exception messages or internal details such as hosts, queries or file paths in them. Over HTTP, all levels are eligible for delivery, including debug.
|
The response over HTTP
Over the HTTP transport, the response stays JSON until the method sends its first notification. If the client accepts both application/json and text/event-stream, the response then becomes an event stream: each notification is sent as an event while the method runs, followed by the JSON-RPC response. A log message of any level, even debug, makes the response an event stream. For the example above, a client that sends:
POST /mcp
Content-Type: application/json
Accept: application/json, text/event-stream
{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "importCatalog", "arguments": {"pages": 2}, "_meta": {"progressToken": "import"}}}receives a text/event-stream response with these events:
data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"import","progress":1.0,"total":2.0,"message":"Imported page 1"}}
data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"import","progress":2.0,"total":2.0,"message":"Imported page 2"}}
data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","logger":"catalog","data":"Imported 2 pages"}}
data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"done"}],"isError":false}}A request that sends no notification is answered with JSON, and so is a client that only accepts JSON, whose notifications are dropped. On the blocking server, so that the response can become a stream while the method runs, a request for a primitive that declares an McpRequestContext, from a client that accepts both, runs the method on another thread of the blocking executor.
Once the response is an event stream, its HTTP status is 200 OK, even when the request fails: the error arrives as a JSON-RPC response with an error member in the last event. Check that member, not the HTTP status. A request that fails before its first notification is answered with JSON and the usual error status.
|
Note
|
Only requests for a primitive that declares an McpRequestContext parameter may become an event stream. A client that accepts text/event-stream with a quality of 0 is answered with JSON. If a slow client lets more than 256 events, or notifications of more than about a million characters, pile up, further notifications are dropped, but the result is always sent.
|
Deploying a server that streams
An event stream stays open while the method runs, so the components between the client and the server must let it through as it is written:
-
The server sends no keep-alive while a method is silent. If the method pauses between notifications for longer than an idle timeout on the path, the connection is closed and the client never receives the result. Raise
micronaut.server.idle-timeout,micronaut.server.read-idle-timeout,micronaut.server.write-idle-timeoutand the read timeout of any reverse proxy or load balancer above the longest pause, or have a long-running method send a log message or progress regularly. -
The event stream has the headers
Cache-Control: no-cache, no-transformandX-Accel-Buffering: no, which nginx honours. Turn off response buffering for the MCP endpoint in any other reverse proxy, or the events arrive at once when the method returns, and a client that goes away is not noticed. -
A request that fails after its first notification still has the HTTP status
200 OK, so access logs and proxy error rates do not count it; the server logs an unexpected error at theERRORlevel. -
A client that does not read keeps up to 256 notifications, of about a million characters at most, in memory for each request. Put a public endpoint behind authentication and a connection or rate limit.
Client disconnects
Once the HTTP response has become an event stream, isClientDisconnected() reports whether the server has observed the connection close. A disconnect stops event delivery. The primitive continues running and can finish any work already in progress. Over STDIO or with a plain JSON response the method returns false.
The supported MCP protocol revisions distinguish a transport disconnect from an explicit notifications/cancelled notification. This context does not handle protocol cancellation.
Elicitation and sampling
elicit and sample send requests to the client, which only the STDIO transport supports: over the stateless HTTP transport they throw UnsupportedOperationException.
They wait for the answer of the client. On a reactive STDIO server (micronaut.mcp.server.reactive set to true), a method without an executor runs on the thread that reads the messages of the client, which could then never read the answer, so elicit and sample fail there with an IllegalStateException. Annotate a method that calls them with @ExecuteOn(TaskExecutors.BLOCKING).
The server records metrics for its operations; it does not create tracing spans. HTTP metrics and traces of the MCP endpoint come from Micronaut Micrometer and Micronaut Tracing as usual, but they group every MCP operation under one URI. The timer described here splits them by method and primitive.
To record metrics, add Micronaut Micrometer and a meter registry, for example Prometheus:
implementation("io.micronaut.micrometer:micronaut-micrometer-core")implementation("io.micronaut.micrometer:micronaut-micrometer-registry-prometheus")To expose the metrics at /prometheus, as the Micronaut Micrometer guide describes, also add Micronaut Management:
implementation("io.micronaut:micronaut-management")|
Warning
|
The metrics name every tool, prompt and resource of the server and show how often each is used and fails. Micronaut Management serves them at /prometheus and also at /metrics, which is not sensitive by default, and opens /health too. The MCP endpoint is reachable by remote clients, and management endpoints share its port by default, so do not leave the metrics readable without authentication on that port.
|
Either keep both endpoints sensitive and have the scraper authenticate (with Micronaut Security, a sensitive endpoint requires an authenticated request):
endpoints.metrics.sensitive=true
# or, if only Prometheus reads the metrics:
# endpoints.metrics.enabled=falseOr serve the management endpoints on a separate port that only the monitoring network can reach. Apply both properties together, never endpoints.prometheus.sensitive=false alone. Every management endpoint moves to that port, /health included, so point health probes and load balancer checks at it, and restrict the port with a firewall rule or a network policy:
endpoints.all.port=8081
endpoints.prometheus.sensitive=falseThe server then times these operations with a timer named mcp.server.operation.duration:
-
calls of annotated tools (
tools/call) -
gets of annotated prompts (
prompts/get) -
reads of annotated resources and resource templates (
resources/read) -
annotated completions (
completion/complete)
| Tag | Value |
|---|---|
|
The JSON-RPC method: |
|
The name of the tool or prompt; the URI of the resource; the URI template, as declared, of the resource template, not the URI that was read; or, for a completion, the name of the prompt or the URI of the resource it completes |
|
|
The Prometheus registry renders the timer with Prometheus names, for example:
mcp_server_operation_duration_seconds_count{error_type="none",mcp_method_name="tools/call",mcp_primitive_name="weather"} 12For example, the rate of failed calls of each tool is:
sum by (mcp_primitive_name) (rate(mcp_server_operation_duration_seconds_count{mcp_method_name="tools/call",error_type!="none"}[5m]))Primitives added at runtime through the MCP Java SDK server (see Adding Primitives at Runtime), and requests the SDK rejects before dispatching them, for example a call of an unknown tool, are not timed.
The timer is based on the OpenTelemetry semantic conventions for MCP, which are still in development, with these differences:
-
The conventions name the primitive with
gen_ai.tool.name,gen_ai.prompt.nameor the opt-inmcp.resource.uri, depending on the operation. The timer always usesmcp.primitive.name, a tag Micronaut MCP defines, not the conventions, because the Prometheus registry requires every timer of a name to have the same tag keys. -
The conventions leave
error.typeout on success. The timer sets it tonone, for the same reason. -
The conventions do not count some JSON-RPC error codes as errors, for example
-32602(invalid params). The timer records every reserved code inerror.type, so that a dashboard can tell them apart from successes. -
The conventions time a request from when it is received until its response is sent. The timer covers only the method of the primitive: from when the server invokes it, including any wait for the executor of
@ExecuteOn, until its result is mapped. The JSON-RPC parsing, the input validation of the SDK and the serialization of the response are not included.
With a meter registry that accepts different tag keys for one meter name, a Micrometer MeterFilter bean can map mcp.primitive.name to the attribute names of the conventions.
The timer publishes no histogram buckets by default, so Prometheus cannot compute percentiles such as the 95th. To publish them, register a MeterFilter bean whose configure method, for the meter named mcp.server.operation.duration, merges service level objectives into the distribution statistics, for example the bucket boundaries the conventions recommend: 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120 and 300 seconds.
The timer is on by default whenever a MeterRegistry bean exists. Disable it with micronaut.mcp.server.metrics.enabled=false; your own observers still run. Disabling Micrometer itself with micronaut.metrics.enabled=false disables it too.
To observe operations, register a bean of type McpServerObserver. The server calls start() for each operation and calls stop() once on the returned observation. On a reactive server, start() runs on the subscribing thread, before any switch to the primitive’s @ExecuteOn executor. The thread delivering the result, completion, error or cancellation calls stop(). Keep per-operation state in the returned observation so it is available across threads. Either callback can run on an event loop and must return promptly.
The server logs observer failures and continues the operation. The interface is experimental and may change, for example to give observers the request context.
Protect the HTTP endpoint of an MCP server against DNS rebinding attacks, and require clients to authenticate.
The HTTP endpoint validates two request headers, as the Streamable HTTP transport requires:
-
Origin, to prevent DNS rebinding attacks. A request whoseOriginis not allowed is answered with403 Forbidden. Requests without anOriginare allowed: browsers always send one, and other clients do not need one. Loopback origins (localhost,127.0.0.1and[::1], withhttporhttpsand any port) are allowed by default, so that local tools such as the MCP Inspector can connect. Other loopback forms, such as127.0.0.2or[::ffff:127.0.0.1], and other schemes, such as thecapacitor://localhostof web view shells, are rejected unless listed. Allow the origins of browser-based clients withallowed-origins, orfor any origin. Each entry is an origin,scheme://host[:port], without a path, as browsers send it; the default port ofhttpandhttpscan be left out. An entry that is not an origin, such asapp.example.com,https://app.example.com/ui,https://app.example.com//or one with a port outside 1 to 65535, could never match, so it fails the startup. Wildcard subdomains, such ashttps://.example.com, are not supported. Clients that sendOrigin: null, such asfile://pages and sandboxed iframes, are rejected; only*allows them. -
MCP-Protocol-Version. A request with a version the server does not support is answered with400 Bad Request.
A request with more than one Origin header is answered with 403 Forbidden, and one with more than one MCP-Protocol-Version header with 400 Bad Request, so that a second value cannot pass for the one that is checked. The checks apply to every request routed to the MCP endpoint, whatever the shape of micronaut.mcp.server.endpoint and the context path; a request with a method the endpoint does not serve is answered with 405 Method Not Allowed.
The headers are checked by a filter on the MCP endpoint, before the request body is read. It runs after the CORS filter, so that a browser can read the rejection, and before authentication, so that a request from a foreign origin is answered with 403 rather than 401. Turn on DEBUG logging for io.micronaut.mcp.server.stateless to see why a request was rejected.
Validation is enabled by default, as the specification requires servers to validate the Origin header. It can be disabled with enabled: false (only the value false disables it), for example when a gateway in front of the server validates the Origin. Disabling it turns off both checks, including the MCP-Protocol-Version check, which gateways usually do not perform. The transport security properties are read at startup: changing them, for example through a refresh of the configuration, takes effect after a restart.
micronaut.mcp.server.transport-security.allowed-origins[0]=https://app.example.com
micronaut.mcp.server.transport-security.allow-loopback-origins=false|
Warning
|
With the default allow-loopback-origins, a page served by any other application on the user’s machine, on any port, passes the Origin check. Micronaut also listens on all network interfaces by default. As the specification advises, bind a server meant for local use to the loopback interface with micronaut.server.host: 127.0.0.1. To allow only known local tools, set allow-loopback-origins to false and list them with their ports in allowed-origins, for example http://localhost:6274. Do the same on a server reachable from other hosts.
|
|
Note
|
A browser-based client on another origin also needs CORS to be enabled for that origin. Its MCP requests are POST requests with a JSON body, and usually an Authorization and an MCP-Protocol-Version header, so the browser first sends a preflight OPTIONS request, which the Micronaut CORS configuration must allow, including those headers. The allowed origins of the MCP endpoint do not configure CORS, and CORS does not configure them: an origin allowed by CORS but not listed in allowed-origins gets 403 Forbidden. With Authorization, the client also reads the WWW-Authenticate header of a 401 Unauthorized response, which names the protected resource metadata, and browsers only let JavaScript read it when CORS exposes it:
|
micronaut.server.cors.enabled=true
micronaut.server.cors.configurations.web.allowed-origins[0]=https://app.example.com
micronaut.server.cors.configurations.web.allowed-headers[0]=Content-Type
micronaut.server.cors.configurations.web.allowed-headers[1]=Authorization
micronaut.server.cors.configurations.web.allowed-headers[2]=MCP-Protocol-Version
micronaut.server.cors.configurations.web.exposed-headers[0]=WWW-AuthenticateAllow the same browser origin to fetch the protected resource metadata URL advertised in the challenge.
Secure the MCP endpoint with Micronaut Security. MCP clients authenticate with OAuth 2.1 bearer tokens, so add micronaut-security-jwt to validate the tokens:
implementation("io.micronaut.security:micronaut-security-jwt")and micronaut-security-oauth2 (Micronaut Security 5; this recipe is tested with 5.5.2), which implements the authorization discovery the specification requires:
implementation("io.micronaut.security:micronaut-security-oauth2")-
an unauthenticated request is answered with
401 Unauthorizedand aWWW-Authenticate: Bearer resource_metadata="…"challenge; -
the OAuth 2.0 Protected Resource Metadata of the endpoint is served at
/.well-known/oauth-protected-resource/mcp, naming the authorization servers of the configured OpenID clients.
micronaut.security.token.jwt.claims-validators.audience=https://mcp.example.com/mcp
micronaut.security.token.jwt.claims-validators.issuer=https://idp.example.com
micronaut.security.token.jwt.claims-validators.not-before=true
micronaut.security.token.jwt.signatures.jwks.idp.url=https://idp.example.com/.well-known/jwks.json
micronaut.security.oauth2.clients.idp.openid.issuer=https://idp.example.com
micronaut.security.intercept-url-map[0].pattern=/mcp
micronaut.security.intercept-url-map[0].access[0]=isAuthenticated()
micronaut.server.host-resolution.allowed-hosts[0]=https://mcp[.]example[.]comThe specification requires the server to accept only tokens issued for it, so that a token issued for another service cannot be used against the MCP server. Set the audience to the canonical URL of your MCP endpoint. Validate the issuer too, so that a token of another issuer that shares the provider’s keys, such as another tenant, is rejected, and the not-before time.
Micronaut Security accepts a token without an expiration (exp). If your provider can issue such tokens, register a GenericJwtClaimsValidator bean whose validate method returns claims.contains(Claims.EXPIRATION_TIME), so that a leaked token cannot be used forever.
Serve the endpoint over HTTPS only, with micronaut.server.ssl or behind a proxy that terminates TLS, as the bearer tokens are sent with every request.
The WWW-Authenticate challenge and the resource of the protected resource metadata are built from the host the request names, in its Host or forwarded headers. List the hosts of the server in micronaut.server.host-resolution.allowed-hosts, regular expressions matched against scheme://host[:port], so that a forged host, for example in a cached response, cannot send clients to another authorization server. A request whose host matches none of them is resolved to http://localhost, so clients would look for the metadata on their own machine. With the allowed hosts set, the resource is the canonical URL of the endpoint, the audience above.
Behind a proxy that terminates TLS, the server sees plain HTTP. Name the headers the proxy sets, so that the resolved host is the https one the clients use. Once they are configured, only those headers are read, and the proxy must replace any copies the client sent:
micronaut.server.host-resolution.protocol-header=X-Forwarded-Proto
micronaut.server.host-resolution.host-header=X-Forwarded-Host
micronaut.server.host-resolution.allowed-hosts[0]=https://mcp[.]example[.]comUse host-header: Host if the proxy keeps the Host header instead of setting X-Forwarded-Host.
If you change micronaut.mcp.server.endpoint, update the intercept-url-map pattern and the JWT audience to match the new path. Publish a single canonical endpoint URL without a trailing slash. Micronaut’s router accepts a trailing-slash alias, but the stock challenge uses the request path and the metadata may omit the slash from its resource. Clients following RFC 9728 reject that mismatch. If you expose the alias, configure your proxy or an application request filter to return a 308 Permanent Redirect to the canonical path before authentication. A 308 preserves the POST method and body.
If you set micronaut.server.context-path, the stock metadata controller is mounted under that context path. The public metadata URL in the challenge still starts at the origin root, so configure your proxy to forward it to the controller. For example, with a context path of /ctx and an endpoint of /mcp, use these mappings:
| Public request path | Proxy action |
|---|---|
|
Return a 308 redirect to |
|
Forward to |
|
Forward to |
Keep /ctx/mcp after oauth-protected-resource in the upstream path. The metadata controller uses that suffix to construct the resource. Set the audience to https://mcp.example.com/ctx/mcp. Keep /mcp in intercept-url-map because Micronaut Security prepends the context path by default.
Tools, prompts and resources receive the authenticated principal through the transport context:
imports
import io.micronaut.mcp.annotations.Tool;
import io.micronaut.mcp.server.context.MicronautMcpTransportContext;
import jakarta.inject.Singleton;
import java.security.Principal;@Singleton
class WhoAmITools {
@Tool(description = "Says who the authenticated user is")
String whoami(MicronautMcpTransportContext context) {
Principal principal = context.principal();
return principal != null ? principal.getName() : "anonymous";
}
}Tools: Executable functions that allow models to perform actions or retrieve information
If you need to expose a Search Tool in your MCP Server, you can do it easily defining a bean of type SearchTool
@Singleton
class MicronautModulesSearch implements SearchTool {
@Override
public SearchResponse search(SearchRequest request, McpTransportContext transportContext) {
return new SearchResponse(List.of(SearchResult.builder()
.id("micronaut-security")
.title("Micronaut Security")
.url("https://micronaut-projects.github.io/micronaut-security/latest/guide")
.build()));
}
}If you need to expose a Fetch Tool in your MCP Server, you can do it easily defining a bean of type FetchTool
@Singleton
class MicronautModulesFetch implements FetchTool {
@Override
public Optional<FetchResponse> fetch(FetchRequest request, McpTransportContext transportContext) {
return Optional.of(FetchResponse.builder()
.id("micronaut-security")
.title("Micronaut Security")
.url("https://micronaut-projects.github.io/micronaut-security/latest/guide")
.text("Built-in security features. Authentication providers and strategies, Token Propagation.")
.build());
}
}The preferred way to declare a tool is using a method annotated with Tool in a @Singleton bean.
imports
package example.micronaut;
import io.micronaut.context.annotation.Requires;
import io.micronaut.mcp.annotations.Tool;
import io.micronaut.mcp.server.context.MicronautMcpTransportContext;
import jakarta.inject.Singleton;@Singleton
class Tools {
@Tool(description = "Evaluate a chess position using a FEN string.")
String fenEvaluation(String fen,
MicronautMcpTransportContext ctx) {
if (fen.equals("r1bqk2r/ppp2ppp/2n5/1BbpP3/3Nn3/8/PPP2PPP/RNBQK2R w KQkq - 1 8")) {
return "+0.12";
}
return "+0.0";
}
}By default, the method name is used as the tool name.
You can override this by setting the name attribute of the @Tool annotation.
|
Note
|
The Python method name is used verbatim, so the tool of the previous example is named fen_evaluation. Set the name attribute of the @Tool annotation to expose a different name.
|
To add icons or _meta, see Icons, Metadata and Resource Hints.
You can use annotation hints to inform the client that a tool is read-only. ChatGPT, for example, informs users whether a tool performs write operations.
@Singleton
class HelloWorldTool {
@Tool(title = "Hello World",
annotations = @Tool.ToolAnnotations(readOnlyHint = true,
title = "Hello World",
destructiveHint = false,
idempotentHint = true,
openWorldHint = false,
returnDirect = true))
String helloWorld() {
return "Hello, World!";
}
}The method parameter names will be automatically used as the tool argument names, unless you use the ToolArg annotation to differentiate the tool argument name from the method parameter name.
imports
package example.micronaut;
import io.micronaut.context.annotation.Requires;
import io.micronaut.mcp.annotations.Tool;
import io.micronaut.mcp.annotations.ToolArg;
import io.modelcontextprotocol.common.McpTransportContext;
import jakarta.inject.Singleton;@Singleton
class Tools {
@Tool(name = "fenEvaluation", description = "Evaluate a chess position using a FEN string.")
String forsythEdwardsNotationEvaluation(@ToolArg(name = "fen") String forsythEdwardsNotation,
McpTransportContext ctx) {
if (forsythEdwardsNotation.equals("r1bqk2r/ppp2ppp/2n5/1BbpP3/3Nn3/8/PPP2PPP/RNBQK2R w KQkq - 1 8")) {
return "+0.12";
}
return "+0.0";
}
}In a method annotated with @Tool you can bind parameters with types:
-
A class or Java record defined as the tool toolsInputJsonSchema.
-
io.modelcontextprotocol.spec.McpSchema.CallToolRequest.
A parameter whose type is defined as the tool input JSON Schema is the whole tool input. Annotate it with ToolArg to make it a named property of the tool input instead. The JSON Schema of its type is then used as the schema of that property.
In a method annotated with @Tool, you can use as a return type:
-
io.modelcontextprotocol.spec.McpSchema.CallToolResult -
String -
A class or Java record which will be serialized to JSON. If the return type is annotated with
@JsonSchemaand it is defined as the tool output it will be used as structured content.
Any of these can also be produced asynchronously, by returning a single value reactive type such as Mono<T>, a Publisher<T> that emits at most one value, or a CompletionStage<T>. Other reactive types, such as RxJava’s Single, are converted with the conversion service. The value it produces is used as if the method had returned it, and the result is chosen from that value rather than from the declared return type. A @JsonSchema type produced this way is still used as the structured output; producing no value is then a tool error.
A method returning a type that may emit several values, such as Flux<T>, fails the startup, unless it is annotated with @SingleResult. A Publisher<T> that emits more than one value fails the call.
The single-value rules also apply to methods annotated with @Prompt, @Resource, @ResourceTemplate, @PromptCompletion and @ResourceCompletion.
A @PromptCompletion or @ResourceCompletion method can also return a Flux<String> of suggestions. The response contains up to 100 suggestions in emission order. If the publisher emits a 101st suggestion, the server cancels the subscription, sets hasMore to true, and omits the unknown total.
How the methods are invoked depends on micronaut.mcp.server.reactive:
-
When it is
false(the default), the HTTP endpoint handles requests on the blocking executor, which uses virtual threads where they are available. Methods run on that thread, can block, and see the current request throughServerRequestContext. The server waits for asynchronous return values. A method annotated with@ExecuteOnruns on the named executor, for example to limit how many calls run concurrently, and the request thread waits for the result. If you configure a fixed-size HTTP blocking executor, use a separate executor for asynchronous work that a request waits for, or enable the reactive server. -
When it is
true, methods run on the thread that received the request, which must not block. Annotate a method with@ExecuteOnto run it on another executor, for example@ExecuteOn(TaskExecutors.BLOCKING).
See Tool Errors for how a tool reports a failure.
The following @Tool methods show how to report expected failures, unexpected failures and protocol errors.
imports
package example.micronaut;
import io.micronaut.context.annotation.Requires;
import io.micronaut.mcp.annotations.Tool;
import io.micronaut.mcp.annotations.ToolArg;
import io.modelcontextprotocol.spec.McpError;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.inject.Singleton;
import java.util.Map;@Singleton
class WeatherTools {
private static final Map<String, Integer> TEMPERATURES = Map.of("Madrid", 21, "London", 14);
@Tool(description = "Returns the temperature of a city in degrees Celsius")
McpSchema.CallToolResult temperature(@ToolArg(description = "Madrid or London") String city) {
Integer temperature = TEMPERATURES.get(city);
if (temperature == null) {
return McpSchema.CallToolResult.builder()
.addTextContent("Unknown city " + city + ", use Madrid or London")
.isError(true)
.build();
}
return McpSchema.CallToolResult.builder()
.addTextContent(String.valueOf(temperature))
.build();
}
@Tool(description = "Returns the forecast of a city")
String forecast(@ToolArg String city) {
throw new IllegalStateException("The forecast service is not available");
}
@Tool(description = "Returns the weather alerts of a city")
String alerts(@ToolArg String city) {
throw McpError.builder(McpSchema.ErrorCodes.INTERNAL_ERROR)
.message("Weather alerts are disabled on this server")
.build();
}
}-
For an expected failure, return a
CallToolResultwithisErrorset totrueand a message that helps the caller correct the request. For example,temperaturelists the supported cities. Returning an error result does not generate a server log entry. -
If a tool throws an unmapped exception, the client receives a tool execution error with a generic message, such as
Tool forecast failed. The server logs the exception details and stack trace atWARN. If the server cannot serialize a tool result, the client receives a message identifying the tool and the serialization failure. -
To report a JSON-RPC protocol error, throw an
io.modelcontextprotocol.spec.McpErrorwith a code and a client-safe message, asalertsdoes.
Clients decide what to show the model. The MCP specification recommends that clients forward tool execution errors and allows them to forward protocol errors too. Use client-safe text in explicit results and in the message and data of a protocol error.
Arguments that cannot be bound or fail bean validation produce tool execution errors with the validation message, for example date: must be a date in the past or in the present. The registry logs these errors at DEBUG.
An application io.micronaut.mcp.server.exceptions.McpErrorExceptionMapper can turn an exception into a protocol error. A mapper that matches every RuntimeException also matches an McpError thrown by a tool and can replace its code and message. The built-in argument mappers send their messages as tool execution errors. They match by exception type, including when a tool body throws an exception such as a SerdeException while reading an upstream response. Handle such an exception inside the tool if its message contains private details.
The registry unwraps exceptions from reactive types and CompletionStage before choosing a mapper. The same rules apply to synchronous and reactive servers. Prompts, resources and completions report failures as protocol errors.
With a reactive server, a tool without @ExecuteOn can fail on the event loop. A synchronous appender writes the log on that thread. An asynchronous appender such as Logback’s AsyncAppender can offload that work. The registry renders unexpected tool exceptions, including their causes and suppressed exceptions, on one log line.
A tool definition includes an input JSON Schema.
You can leverage Micronaut JSON Schema to generate a JSON Schema at compilation and use it as your tool input JSON Schema.
For example, you can use a Java record to define your tool input:
For example, you can use a dataclass to define your tool input (the attribute docstrings become the property descriptions of the JSON schema):
imports
import io.micronaut.jsonschema.JsonSchema;
import io.micronaut.serde.annotation.Serdeable;/**
*
* @param fen A Chess position in Forsyth–Edwards Notation
*/
@JsonSchema
@Serdeable
public record FenEvaluationRequest(String fen) {
}Then, just use the Java record as the method parameter:
Then, just use the dataclass as the method parameter:
imports
package example.micronaut;
import io.micronaut.context.annotation.Requires;
import io.micronaut.mcp.annotations.Tool;
import io.micronaut.mcp.server.context.MicronautMcpTransportContext;
import jakarta.inject.Singleton;@Singleton
class Tools {
@Tool(description = "Evaluate a chess position using a FEN string.")
String fenEvaluation(FenEvaluationRequest req,
MicronautMcpTransportContext ctx) {
if (req.fen().equals("r1bqk2r/ppp2ppp/2n5/1BbpP3/3Nn3/8/PPP2PPP/RNBQK2R w KQkq - 1 8")) {
return "+0.12";
}
return "+0.0";
}
}A tool definition includes an input JSON Schema.
You can leverage Micronaut JSON Schema to generate a JSON Schema at compilation and use it as your tool output JSON Schema.
For example, you can use a Java record to define your tool output:
For example, you can use a dataclass to define your tool output:
imports
import io.micronaut.jsonschema.JsonSchema;
import io.micronaut.serde.annotation.Serdeable;
import jakarta.validation.constraints.NotBlank;
import org.jspecify.annotations.NonNull;@Serdeable
@JsonSchema
public record FenEvaluationResponse(
@NonNull @NotBlank String fen,
@NonNull @NotBlank String evaluation
) {
}Then, use the Java record as the method return type:
Then, use the dataclass as the method return type:
imports
package example.micronaut;
import io.micronaut.context.annotation.Requires;
import io.micronaut.mcp.annotations.Tool;
import io.micronaut.mcp.docs.tools.jsonschema.FenEvaluationRequest;
import io.micronaut.mcp.server.context.MicronautMcpTransportContext;
import jakarta.inject.Singleton;@Singleton
class Tools {
@Tool(description = "Evaluate a chess position using a FEN string.")
FenEvaluationResponse fenEvaluation(FenEvaluationRequest req,
MicronautMcpTransportContext ctx) {
String fen = req.fen();
if (fen.equals("r1bqk2r/ppp2ppp/2n5/1BbpP3/3Nn3/8/PPP2PPP/RNBQK2R w KQkq - 1 8")) {
return new FenEvaluationResponse(fen, "+0.12");
}
return new FenEvaluationResponse(fen, "+0.0");
}
}If a tool with an output JSON Schema returns null, or a value that cannot be serialized, the client receives a tool result with isError: true, and the server logs the cause.
The object a tool returns is validated against the output JSON Schema and then serialized in the response, so do not modify it once the tool has returned it, for example by returning an object that other threads update.
Alternatively, you can define tools by registering beans (typically in a bean factory).
|
Note
|
The following example assumes you set SYNC as your server type. Because of that, the following example creates defining tools with the class McpStatelessServerFeatures.SyncToolSpecification. If you used a different server type, you should use a different class.
|
imports
package example.micronaut;
import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Requires;
import io.modelcontextprotocol.server.McpStatelessServerFeatures;
import io.modelcontextprotocol.common.McpTransportContext;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.inject.Singleton;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;@Factory
class ToolsFactory {
@Singleton
McpStatelessServerFeatures.SyncToolSpecification fenEvaluationTool() {
return McpStatelessServerFeatures.SyncToolSpecification.builder()
.tool(tool())
.callHandler(callHandler())
.build();
}
private McpSchema.Tool tool() {
return McpSchema.Tool.builder()
.name("fenEvaluation")
.description("Evaluate a chess position using a FEN string.")
.inputSchema(inputSchema())
.build();
}
private McpSchema.JsonSchema inputSchema() {
McpSchema.JsonSchema fenSchema = new McpSchema.JsonSchema("string", null, null, null, null, null);
return new McpSchema.JsonSchema("object", Map.of("fen", fenSchema), List.of("fen"), null, null, null);
}
private BiFunction<McpTransportContext, McpSchema.CallToolRequest, McpSchema.CallToolResult> callHandler() {
return (ctx, req) -> {
String content = evaluation(req.arguments().get("fen").toString());
return McpSchema.CallToolResult.builder().addTextContent(content).isError(false).build();
};
}
private String evaluation(String fen) {
if (fen.equals("r1bqk2r/ppp2ppp/2n5/1BbpP3/3Nn3/8/PPP2PPP/RNBQK2R w KQkq - 1 8")) {
return "+0.12";
}
return "+0.0";
}
}Prompts: Pre-defined templates or instructions that guide language model interactions
It is possible to define prompts by placing a text file in the classpath and defining the prompt attributes and path via configuration:
micronaut.mcp.classpath-prompts.introspection-testing.name=introspection-testing
micronaut.mcp.classpath-prompts.introspection-testing.title=Introspection-Testing
micronaut.mcp.classpath-prompts.introspection-testing.description=Test whether a class is introspected in a Micronaut application
micronaut.mcp.classpath-prompts.introspection-testing.path=prompts/introspection-testing.md
micronaut.mcp.classpath-prompts.introspection-testing.arguments[0].name=className
micronaut.mcp.classpath-prompts.introspection-testing.arguments[0].description=The class for which you want to test introspection
micronaut.mcp.classpath-prompts.dev-default-environment.name=dev-default-environment
micronaut.mcp.classpath-prompts.dev-default-environment.title=Development-Default-Environment
micronaut.mcp.classpath-prompts.dev-default-environment.description=Modify a Micronaut application to set dev as the default environment
micronaut.mcp.classpath-prompts.dev-default-environment.path=prompts/dev-default-environment.mdYou can define the prompt content with argument interpolation in a text file.
Please, write a test to verify introspection for ${className}
The following tests shows how to test if a class is introspected. The following test verifies if the `CreateGame` class is annotated with `@Introspected`.
```java
@Test
void isAnnotatedWithIntrospected() {
assertDoesNotThrow(() -> BeanIntrospection.getIntrospection(CreateGame.class));
}
```The preferred way to define prompts is to annotate a method with Prompt in a @Singleton bean.
imports
import io.micronaut.mcp.annotations.Prompt;
import io.micronaut.mcp.annotations.PromptArg;
import jakarta.inject.Singleton;@Singleton
class Prompts {
/**
*
* @return Chess statistics
*/
@Prompt(name = "chess-statistics", description = "Displays statistics for chess games")
String prompt(@PromptArg(description = "Player Name") String name) {
return String.format("You generate chess statistics for %s ....", name);
}
}To add icons or _meta, see Icons, Metadata and Resource Hints.
In a method annotated with @Prompt you can bind parameters with types:
-
io.modelcontextprotocol.spec.McpSchema.GetPromptRequest
In a method annotated with @Prompt, you can use as a return type:
-
io.modelcontextprotocol.spec.McpSchema.GetPromptResult -
String
Alternatively, you define prompts registering beans (typically in a bean factory) using the low-level MCP SDK API.
|
Note
|
The following example assumes you set SYNC as your server type. Because of that, the following example creates defining Prompts with the class McpStatelessServerFeatures.SyncPromptSpecification. If you used a different server type, you should use a different class.
|
imports
package example.micronaut;
import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Requires;
import io.modelcontextprotocol.server.McpStatelessServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.inject.Singleton;
import java.util.List;@Factory
class PromptsFactory {
@Singleton
McpStatelessServerFeatures.SyncPromptSpecification prompt() {
return new McpStatelessServerFeatures.SyncPromptSpecification(
new McpSchema.Prompt("chess-statistics", "Displays statistics for chess games",
List.of(new McpSchema.PromptArgument("name", "Player Name", true))), (ctx, req) -> {
Object playerNameObj = req.arguments().get("name");
String playerName = playerNameObj != null ? playerNameObj.toString() : "";
McpSchema.TextContent assistantContent = new McpSchema.TextContent(String.format("""
You generate chess statistics for %s ....""", playerName));
McpSchema.PromptMessage assistantMessage = new McpSchema.PromptMessage(McpSchema.Role.ASSISTANT, assistantContent);
return new McpSchema.GetPromptResult("Chess statistics", List.of(assistantMessage), null);
});
}
}Resources: Structured data or content that provides additional context to the model
The preferred way to declare a resource is using a method annotated with Resource in a @Singleton bean.
imports
package example.micronaut;
import io.micronaut.mcp.annotations.Resource;
import jakarta.inject.Singleton;@Singleton
class Resources {
@Resource(
uri = "example://hello",
name = "hello",
title = "Hello",
description = "Hello text",
mimeType = "text/plain"
)
String hello() {
return "Hello World";
}
}Notes:
-
The
uriattribute is required and must be unique for the resource. -
By default, the method name is used as the resource
name. You can override this by setting thenameattribute of the@Resourceannotation. -
You can optionally provide
title,descriptionandmimeType(defaults totext/plain).
To add icons, _meta, an audience, a priority or a size, see Icons, Metadata and Resource Hints.
In a method annotated with @Resource you can bind parameters with types:
-
io.modelcontextprotocol.spec.McpSchema.ReadResourceRequest
In a method annotated with @Resource, you can use as a return type:
-
io.modelcontextprotocol.spec.McpSchema.ReadResourceResult -
String. If the method returns aString, the server responds with a single text resource content using the providedmimeType.
Alternatively, you define resources registering beans (typically in a bean factory).
|
Note
|
The following example assumes you set SYNC as your server type. Because of that, the following example creates defining resources with the class McpStatelessServerFeatures.SyncResourceSpecification. If you used a different server type, you should use a different class.
|
imports
package example.micronaut;
import io.micronaut.context.annotation.Context;
import io.micronaut.context.annotation.EachBean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Requires;
import io.micronaut.context.exceptions.ConfigurationException;
import io.micronaut.core.io.ResourceLoader;
import io.modelcontextprotocol.server.McpStatelessServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.inject.Singleton;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;@Context
@Factory
class ResourcesFactory {
public static final String PGN_MIME_TYPE = "application/x-chess-pgn";
private final PgnLoader pgnLoader;
private final ResourceLoader resourceLoader;
ResourcesFactory(ResourceLoader resourceLoader, PgnLoader pgnLoader) {
this.resourceLoader = resourceLoader;
this.pgnLoader = pgnLoader;
}
@EachBean(PgnFile.class)
@Singleton
McpStatelessServerFeatures.SyncResourceSpecification createPgnSyncResourceSpecification(PgnFile pgnFile) throws IOException {
McpSchema.Resource resource = getResource(pgnFile);
return new McpStatelessServerFeatures.SyncResourceSpecification(resource,
(mcpTransportContext, readResourceRequest) -> readResourceResult(readResourceRequest.uri(), pgnLoader));
}
private static Integer round(String uri) {
int lastSlash = uri.lastIndexOf('/');
String roundStr = uri.substring(lastSlash + 1);
return Integer.parseInt(roundStr);
}
static McpSchema.ReadResourceResult readResourceResult(String uri, PgnLoader pgnLoader) {
Integer round = round(uri);
List<McpSchema.ResourceContents> contents = new ArrayList<>();
pgnLoader.loadPgn(round).ifPresent(text ->
contents.add(new McpSchema.TextResourceContents(uri, PGN_MIME_TYPE, text)));
return new McpSchema.ReadResourceResult(contents);
}
private McpSchema.Resource getResource(PgnFile pgnFile) throws IOException {
return size(pgnFile.getPath())
.map(size -> {
Integer round = pgnFile.getRound();
String uri = "pgn://round/" + round;
String name = "round" + round + "PgnFideWCC2024";
String title = "PGN of the Round " + round + " game of the World Chess Championship";
String description = title + " between Ding Liren and Gukesh Dommaraju";
return new McpSchema.Resource(uri, name, title, description, PGN_MIME_TYPE, size, null, null);
}).orElseThrow(() -> new ConfigurationException("unable find resource for path " + pgnFile.getPath()));
}
private Optional<Long> size(String path) throws IOException {
Optional<InputStream> inputStreamOptional = resourceLoader.getResourceAsStream(path);
if (inputStreamOptional.isPresent()) {
try (InputStream inputStream = inputStreamOptional.get()) {
return Optional.of((long) inputStream.readAllBytes().length);
}
}
return Optional.empty();
}
}Resource templates allow servers to expose parameterized resources using URI templates
The preferred way to declare a resource is using a method annotated with ResourceTemplate in a @Singleton bean.
@Singleton
class MyResourcesTemplates {
private static final String PGN_MIME_TYPE = "application/x-chess-pgn";
private final PgnLoader pgnLoader;
MyResourcesTemplates(PgnLoader pgnLoader) {
this.pgnLoader = pgnLoader;
}
@ResourceTemplate(uriTemplate = "pgn://round/{round}",
mimeType = PGN_MIME_TYPE,
name = "2024ChessChampionshipRoundPgn",
title = "PGN of a round World Chess Championship 2024",
description = "Given a round, it returns a PGN of the World Chess Championship 2024 between Ding Liren and Gukesh Dommaraju")
String pgn(Integer round) {
return pgnLoader.loadPgn(round)
.orElseThrow(() -> new McpError(new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.RESOURCE_NOT_FOUND, "resource for round not found", null)));
}
}Specify uriTemplate on every @ResourceTemplate handler.
To add icons, _meta, an audience, a priority, see Icons, Metadata and Resource Hints.
In a method annotated with @ResourceTemplate you can bind parameters with types:
-
io.modelcontextprotocol.spec.McpSchema.ReadResourceRequest
Additionally, you can add method parameter matching the uri template variable as show in the previous example.
Variable values are percent-decoded before they are bound, see Resource Template Variable Decoding.
In a method annotated with @ResourceTemplate, you can use as a return type:
-
io.modelcontextprotocol.spec.McpSchema.ReadResourceResult -
String. If the method returns aString, the server responds with a single text resource content using the providedmimeType.
Variable values are percent-decoded as UTF-8 before they are bound. This is URI decoding, not form decoding: a + is never turned into a space, so clients must send a space as %20.
The table shows what a method parameter receives for a request to book://book/…, with the template book://book/{title} (a simple variable) or book://book/{+title} (a reserved variable):
| The client sends | Micronaut MCP binds |
{+title} binds |
|---|---|---|
|
|
|
|
|
|
|
invalid params error |
|
|
invalid params error |
|
|
resource not found error |
resource not found error |
|
invalid params error |
invalid params error |
-
A simple variable matches a single segment, and a value that contains an encoded
/(%2F) is rejected, so that it cannot smuggle path segments such as..%2F..%2Fetcinto the value. A value that may contain/needs a reserved variable, such as{+title}, and clients must send the/encoded, as%2F. -
A literal
/in a variable value is never routed to the method, whatever the operator or the pattern of the variable: the MCP SDK answers with a resource not found error. A regular expression such as{path:.*}does not help, since an encoded/is still rejected in it. -
A simple variable does not match a literal
+,;,&,!,(or), and such a request is answered with an invalid params error. Clients must percent-encode these characters, for example+as%2B. -
The query is ignored when binding path variables. For
book://book/Micronaut MCP, a request forbook://book/a?edition=firstbindsa. Clients send%3Fto include a?in the value itself. -
A malformed escape, such as
%zz, escaped bytes that are not valid UTF-8, such as%FF, and a value that contains an unpaired surrogate, which a JSON string can carry, are answered with an invalid params error.
|
Warning
|
Rejecting an encoded / does not make a value safe to use as a path. Decoded values may still be .., contain \ (%5C), control characters such as %00 and a CR LF line break (%0D%0A), which can forge lines in a log, and Unicode look-alikes of /, such as %E2%88%95 (∕), and the values of reserved variables may also contain /. Validate every value before you use it, for example to resolve a file or to build a query.
|
|
Warning
|
Several URIs bind the same value: book://book/secret, book://book/%73ecret and book://book/secret?x all bind secret for the template book://book/{title}. Authorize, rate limit and cache on the bound value, never on the URI of the request.
|
Alternatively, you define resources registering beans (typically in a bean factory).
|
Note
|
The following example assumes you set SYNC as your server type. Because of that, the following example creates defining resources with the class McpStatelessServerFeatures.SyncResourceTemplateSpecification. If you used a different server type, you should use a different class.
|
imports
package example.micronaut;
import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Requires;
import io.modelcontextprotocol.server.McpStatelessServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.inject.Singleton;
import static io.micronaut.mcp.docs.resources.ResourcesFactory.PGN_MIME_TYPE;
import static io.micronaut.mcp.docs.resources.ResourcesFactory.readResourceResult;@Factory
class ResourcesTemplatesFactory {
private final PgnLoader pgnLoader;
ResourcesTemplatesFactory(PgnLoader pgnLoader) {
this.pgnLoader = pgnLoader;
}
@Singleton
McpStatelessServerFeatures.SyncResourceTemplateSpecification pgnResourceTemplateSpecification() {
McpSchema.ResourceTemplate resourceTemplate = createPgnResourceTemplate();
return new McpStatelessServerFeatures.SyncResourceTemplateSpecification(resourceTemplate,
(mcpTransportContext, readResourceRequest) -> readResourceResult(readResourceRequest.uri(), pgnLoader));
}
McpSchema.ResourceTemplate createPgnResourceTemplate() {
String uriTemplate = "pgn://round/{round}";
String name = "2024ChessChampionshipRoundPgn";
String title = "PGN of a round World Chess Championship 2024";
String description = "Given a round, it returns a PGN of the World Chess Championship 2024 between Ding Liren and Gukesh Dommaraju";
return new McpSchema.ResourceTemplate(uriTemplate, name, title, description, PGN_MIME_TYPE, null, null);
}
}Methods annotated with @Tool, @Prompt, @Resource or @ResourceTemplate can declare icons with @Icon and _meta entries with @Meta. Both annotations are repeatable, for example to offer an icon for each theme, and both are ignored on a method that is not one of these primitives:
imports
import io.micronaut.mcp.annotations.Icon;
import io.micronaut.mcp.annotations.Meta;
import io.micronaut.mcp.annotations.Tool;
import jakarta.inject.Singleton;@Singleton
class WeatherTools {
@Tool
@Icon(src = "https://example.com/sun-light.svg", mimeType = "image/svg+xml", sizes = "any", theme = "light")
@Icon(src = "https://example.com/sun-dark.svg", mimeType = "image/svg+xml", sizes = "any", theme = "dark")
@Meta(key = "com.example/category", value = "weather")
String forecast(String city) {
return "sunny";
}
}Every @Icon requires a src that is an HTTPS URL or a data:image/… URI (an HTTP URL is accepted, for example for local development) without a user name or password, and its theme, when set, must be light or dark in lowercase. An image data URI needs an image media type and a non-empty payload separated by a comma. An invalid icon causes startup to fail.
|
Tip
|
Icons are repeated in every list response that includes their primitive. When many primitives share an icon, prefer an HTTPS URL over a data: URI to keep the responses small. Clients should treat icons, SVG ones in particular, as untrusted content.
|
A @Meta key must be non-empty and follow the MCP key format. For example, com.example/display-name has the prefix com.example/ and the name display-name. MCP reserves prefixes whose second label is modelcontextprotocol or mcp, such as io.modelcontextprotocol/.
Repeating the same key and value on a method produces one metadata entry. A malformed key or conflicting values for the same key cause startup to fail.
The values of @Meta are always strings. For numbers, booleans or objects, define the primitive with a factory instead (see Tools with a Factory, Prompts with a Factory and Resources with a Factory) and set its _meta there.
@Resource and @ResourceTemplate also accept hints that tell the client how to use the resource (the specification calls these annotations): the intended audience (Audience.USER, Audience.ASSISTANT), a priority between 0 and 1 and, for @Resource, the size of the content in bytes. Leave priority out to send no priority; a value outside 0 to 1 makes the server fail to start.
imports
import io.micronaut.mcp.annotations.Audience;
import io.micronaut.mcp.annotations.Resource;
import jakarta.inject.Singleton;@Singleton
class WeatherResources {
@Resource(uri = "weather://stations", size = 4, audience = Audience.ASSISTANT, priority = 0.5)
String stations() {
return "KSEA";
}
}Tools, prompts, resources and resource templates can also be added and removed while the server runs, through the MCP Java SDK server bean of the configured transport and micronaut.mcp.server.reactive setting, listed in Server Instance. Each bean takes the specification classes listed in Primitive types per Transport. Completions cannot be added at runtime.
A server that starts without tools, prompts or resources advertises the matching capability only when its list-changed property is true, so set it to add them at runtime. For example, for an HTTP server that adds tools:
micronaut.mcp.server.transport=HTTP
micronaut.mcp.server.tools.list-changed=trueimports
import io.modelcontextprotocol.server.McpStatelessServerFeatures;
import io.modelcontextprotocol.server.McpStatelessSyncServer;
import io.modelcontextprotocol.spec.McpSchema;
import jakarta.inject.Singleton;
import java.util.Map;@Singleton
class Plugins {
private final McpStatelessSyncServer server;
Plugins(McpStatelessSyncServer server) {
this.server = server;
}
void install(String name) {
server.addTool(McpStatelessServerFeatures.SyncToolSpecification.builder()
.tool(McpSchema.Tool.builder().name(name).inputSchema(Map.of("type", "object")).build())
.callHandler((context, request) -> McpSchema.CallToolResult.builder().addTextContent("installed").build())
.build());
}
void uninstall(String name) {
server.removeTool(name);
}
}Without it, addTool, addPrompt, addResource and addResourceTemplate fail with IllegalStateException, for example Server must be configured with tool capabilities. resources.list-changed also covers resource templates, and resources.subscribe alone does not advertise the resources capability.
On McpAsyncServer and McpStatelessAsyncServer, addTool, removeTool and the other methods return a Mono that does nothing until it is subscribed to. Subscribe to it, or return it from a reactive method (return server.addTool(spec);), or the primitive is neither added nor removed.
Over STDIO, when micronaut.mcp.server.tools.list-changed (or the prompts or resources equivalent) is true, the server notifies the client that the list changed. Otherwise, clients are not told that the list changed: they see a change only if they call tools/list (or prompts/list, resources/list) again, which many clients do only when they reconnect or start a new session. The HTTP transport cannot send notifications outside the response to a request, so it never advertises list changes or resource subscriptions, whatever the configuration, and its clients are never told. If clients must see changes right away, use the STDIO transport with list-changed set to true.
Adding a primitive with an existing name or URI replaces the current registration. You can also replace or remove primitives declared with annotations, so use trusted names and URIs for these operations.
When multiple callers can register a tool under the same name, serialize their addTool calls. The SDK removes the old tool and adds its replacement in separate steps. Overlapping calls can leave duplicate entries in tools/list. On a reactive server, wait for each registration’s Mono to complete before starting the next registration for that name.
|
Note
|
A primitive added at runtime is an MCP Java SDK specification, so its handler receives the SDK request as is. The features of the annotated primitives, such as argument binding, validation, the MCP Request Context and exception mapping, do not apply to it. Only the tool’s inputSchema constrains its arguments, so validate them in the handler or with a strict inputSchema, and keep sensitive details out of exception messages: the client receives the message of an exception the handler throws.
|
The Model Context Protocol (MCP) provides a standardized way for servers to offer argument autocompletion suggestions for prompts and resource URIs.
The preferred way to declare a prompt completion is using a method annotated with PromptCompletion in a @Singleton bean.
@Singleton
class MyPromptsCompletions {
@PromptCompletion(name = "code_review")
List<String> languages(String language) {
if (language != null && language.startsWith("py")) {
return List.of("python", "pytorch", "pyside");
}
return Collections.emptyList();
}
}|
Note
|
You need a prompt with the same name as the completion prompt. Moreover, the name of the prompt completion argument must match the name of the prompt argument. |
|
Warning
|
Defining a prompt completion via an annotation currently does not work with eager initialization of singletons. |
In a method annotated with @PromptCompletion you can bind parameters with types:
-
io.modelcontextprotocol.spec.McpSchema.CompleteRequest -
io.modelcontextprotocol.spec.McpSchema.CompleteRequest.CompleteArgument
You can also bind the completion argument’s name as a method parameter, as illustrated in the code listing above.
In a method annotated with @PromptCompletion, you can use as a return type:
-
io.modelcontextprotocol.spec.McpSchema.CompleteResult -
List<String>
The preferred way to declare a resource completion is using a method annotated with ResourceCompletion in a @Singleton bean.
@Singleton
class MyResourceCompletions {
@ResourceCompletion(uri = "file:///home/user/documents/{fileName}")
List<String> resourcesCompletions(String fileName) {
return List.of(
"report.pdf",
"data.csv",
"notes.txt"
).stream()
.filter(name -> name.startsWith(fileName))
.toList();
}
}You can use resource completions, for example, in combination with Resource templates (see the uri for both the resource template and resource completion match):
@Singleton
class MyResourceTemplates {
@ResourceTemplate(
uriTemplate = "file:///home/user/documents/{fileName}",
name = "userDocument",
title = "User Document"
)
String ref(String fileName) {
if (fileName.equals("report.pdf")) {
return "Report PDF";
} else if (fileName.equals("data.csv")) {
return "Data CSV";
} else if (fileName.equals("notes.txt")) {
return "Notes TXT";
}
return "";
}
}In a method annotated with @ResourceCompletion you can bind parameters with types:
-
io.modelcontextprotocol.spec.McpSchema.CompleteRequest -
io.modelcontextprotocol.spec.McpSchema.CompleteRequest.CompleteArgument
You can also bind the completion argument’s name as a method parameter, as illustrated in the code listing above.
In a method annotated with @ResourceCompletion, you can use as a return type:
-
io.modelcontextprotocol.spec.McpSchema.CompleteResult -
List<String>
You can configure multiple clients via configuration:
To use MCP Clients powered by the MCP Java SDK, use the following dependency:
implementation("io.micronaut.mcp:micronaut-mcp-client-java-sdk")Declare a named connection for each MCP server under micronaut.mcp.client.http or micronaut.mcp.client.stdio, as for the LangChain4j client. For each connection there is an io.modelcontextprotocol.client.McpSyncClient and an io.modelcontextprotocol.client.McpAsyncClient bean, qualified by the name of the connection.
For an HTTP connection, set url to the full MCP endpoint, including its path and any query parameters. A URL with no path uses /mcp. The client sends the configured headers to that endpoint.
|
Important
|
Use either the synchronous or the asynchronous client of a connection, not both. Each client opens its own session over its own transport, which for STDIO would start a second server process, so creating the second client of a connection fails. McpClientTools uses the synchronous client.
|
A configured client starts its initialization handshake when Micronaut creates the bean. On a blocking thread, creation waits for the handshake. On an event loop, initialization continues in the background and client operations await readiness. If the handshake fails, Micronaut closes the client and its transport and removes the failed singleton. Inject a qualified BeanProvider to resolve a fresh client on a later attempt. When the application stops, the clients are closed gracefully, waiting up to 10 seconds for their transport to close.
Declare beans of these types to answer the requests of servers and receive their notifications. Each method receives the name of the connection: The asynchronous client calls them on the blocking executor, so they may block.
| Bean type | Purpose |
|---|---|
|
Answers sampling requests; the clients then advertise the sampling capability |
|
Answers elicitation requests; the clients then advertise the elicitation capability |
|
Receives log messages |
|
Receives progress notifications for requests sent with a progress token |
|
Notified when a server changes its tools, prompts or resources |
To offer server tools to a model without depending on an AI framework, inject io.micronaut.mcp.client.javasdk.McpClientTools. The primary bean lists tools from all connections concurrently in the caller’s Micronaut context and skips unreachable servers. A bean qualified by connection name lists only that server’s tools. Each McpClientTool can be called. Connections with dynamic HTTP headers fetch the catalog on every lookup. Other connections cache it until the server notifies the client of a change. Declare McpClientToolFilter and McpClientToolNameMapper beans to select and name the tools.
If you are building an MCP Server, you can test it by injecting a bean of type io.modelcontextprotocol.client.McpSyncClient or io.modelcontextprotocol.client.McpAsyncClient in your tests. The MCP Client pointing to your MCP Server has a name qualifier with value embeddedServer.
The authorization of the HTTP connections applies to both clients. Read its warnings about passing tokens through and sharing a session between users before enabling propagate-authorization. The asynchronous client computes the headers in the context its subscriber propagates, such as the request a reactive controller is handling. To supply the headers of a request of the asynchronous client yourself, add them to the Reactor context of the request with io.micronaut.mcp.client.javasdk.McpClientTransportHeaders.withHeaders, in contextWrite.
Applications can also supply an McpClient.SyncSpec or McpClient.AsyncSpec bean directly. Without a matching connection configuration, the resulting client inherits the spec’s qualifier and uses the SDK’s lazy initialization.
To customize client creation further, define
BeanCreatedEventListeners
for HttpClientStreamableHttpTransport.Builder, McpClient.SyncSpec, or McpClient.AsyncSpec.
To use an MCP Client powered by LangChain4j, use the following dependency:
implementation("io.micronaut.mcp:micronaut-mcp-client-langchain4j")Connections
Declare a named connection for each MCP server, over Streamable HTTP or STDIO. Connections of both transports can be used together:
micronaut.mcp.client.http.weather.url=https://weather.example.com/mcp
micronaut.mcp.client.http.weather.headers.Authorization=Bearer ${WEATHER_TOKEN}
micronaut.mcp.client.http.weather.request-timeout=30s
micronaut.mcp.client.stdio.files.command[0]=npx
micronaut.mcp.client.stdio.files.command[1]=-y
micronaut.mcp.client.stdio.files.command[2]=@modelcontextprotocol/server-filesystem@<version>
micronaut.mcp.client.stdio.files.command[3]=/tmp
micronaut.mcp.client.stdio.files.environment.DEBUG=false
micronaut.mcp.client.stdio.files.initialization-timeout=2m
micronaut.mcp.client.stdio.files.auto-health-check=falseThe name of a connection declared in configuration is normalized to kebab case: micronaut.mcp.client.http.internalAdmin declares the connection internal-admin, which is also the key of its client. The embeddedServer connection keeps its name.
Each connection needs a name that is unique across micronaut.mcp.client.http and micronaut.mcp.client.stdio. The application fails to start when two connections have the same name, when an HTTP connection has no url, or when a STDIO connection has no command.
| Setting | Transport | Description | Default |
|---|---|---|---|
|
HTTP |
The URL of the MCP endpoint of the server. Required. |
|
|
HTTP |
The headers sent with every request, such as |
|
|
HTTP |
The timeout of the HTTP calls of the transport. |
|
|
HTTP |
Whether to log the HTTP requests and responses. |
|
|
STDIO |
The command that starts the server, and its arguments. Required. |
|
|
STDIO |
The environment variables of the server process, in addition to those of the application. |
|
|
STDIO |
Whether to log the messages exchanged with the server. |
|
|
Both |
How long to wait for the server to answer the initialization. |
|
|
Both |
How long to wait for the server to answer an MCP request, such as a tool call or a ping. |
|
|
Both |
Whether the client checks periodically that its server is reachable, and reconnects when it is not. |
|
|
Note
|
Keys of headers and environment keep their case when set in a configuration file. When they are set with environment variables, such as MICRONAUT_MCP_CLIENT_STDIO_FILES_ENVIRONMENT_DEBUG, they are lower-cased, so the server process receives debug rather than DEBUG. Set keys whose case matters in a configuration file.
|
|
Note
|
The process of a STDIO connection inherits the environment of the application, in addition to its environment. Applications that keep secrets in their environment make them available to that process, so only start servers you trust, pin their version, for example @modelcontextprotocol/server-filesystem@<version> rather than the latest release that npx would download, and consider starting them with a cleared environment, for example command: [env, -i, "PATH=/usr/bin:/bin", npx, …]. Pass secrets to a server in its environment rather than in its command, as the command is logged at debug level.
|
For STDIO connections, a reconnection by auto-health-check starts a new server process, so consider disabling it for servers that are slow to start, such as those started with npx, or that cannot run twice.
Using the tools
For each connection there is a dev.langchain4j.mcp.client.McpClient bean, qualified by the name of the connection, which is also the key of the client (client.key()).
A dev.langchain4j.mcp.McpToolProvider bean provides the tools of every connection to LangChain4j AI services. A McpToolProvider bean qualified by the name of a connection provides only the tools of that connection. The primary provider also includes tools from application-defined McpClient beans. If your application supplies an McpTransport bean, Micronaut creates its DefaultMcpClient.Builder and McpClient beans with the same qualifier.
|
Warning
|
LangChain4j rejects two tools with the same name, and the primary McpToolProvider gives the tools of every connection under their own names. When two servers have a tool with the same name, every call that uses the primary provider fails, and a server can cause it at any time by renaming or adding a tool. Unless you trust every server, prefix the tools with the name of their connection with an McpToolNameMapper, as shown below, or use the provider of each connection.
|
|
Warning
|
The primary McpToolProvider gives the model the tools, and the tool descriptions, of every connection at once. A server you do not fully trust can use its descriptions to steer the model into calling the tools of another connection. Give an AI service the McpToolProvider qualified by the name of the connection it needs, or restrict the tools with an McpToolFilter, rather than the primary provider.
|
Customizing the tools
Declare one bean of each of these types to customize the tools of all the tool providers. Use the key of the client, the normalized name of its connection, to treat connections differently. Prefer a filter that lists the connections it allows to one that lists those it rejects, so that a name that does not match hides tools rather than exposes them:
-
io.micronaut.mcp.client.langchain4j.McpToolFilterselects the tools that the tool providers provide. -
io.micronaut.mcp.client.langchain4j.McpToolNameMappernames them.
For example, the following beans prefix every tool with the name of its connection, so that the tools of different servers cannot clash, and only provide the tools of the connections they list, which leaves out, for example, the embeddedServer connection of an application that is itself an MCP server:
@Factory
class McpToolsFactory {
@Singleton
McpToolNameMapper prefixWithConnection() {
return (client, tool) -> client.key() + "__" + tool.name();
}
@Singleton
McpToolFilter onlyListedConnections() {
return (client, tool) -> Set.of("weather", "files").contains(client.key());
}
}Every dev.langchain4j.mcp.client.McpClientListener bean, and a dev.langchain4j.mcp.client.logging.McpLogMessageHandler bean, are registered with every client.
To customize client creation further, define a
BeanCreatedEventListener
for DefaultMcpClient.Builder, StreamableHttpMcpTransport.Builder or StdioMcpTransport.Builder. A BeanCreatedEventListener for McpToolProvider.Builder customizes the tool providers, both the provider of every connection and the provider of each connection.
Unreachable servers
A client is created when it is first used, which initializes the connection to its server, and starts the process of a STDIO server. The McpToolProvider beans skip the servers that cannot be reached, so an unreachable server does not prevent the application from starting. Creating a client that failed is attempted again the next time the tools are provided. A warning names the connection when its client cannot be created, and an information message when it is created again; the failures in between are logged at debug level.
Only one attempt to create the client of a connection runs at a time. The requests made while it runs do not wait for it: they get no tools from that server. The request that makes an attempt waits up to twice the initialization-timeout of the connection, as the client tries two versions of the protocol, once for each connection whose server cannot be reached, so set a short initialization-timeout for servers that may be unavailable. Each attempt to create the client of a STDIO connection starts a new server process.
By default, each client checks its server periodically with a thread of its own, see auto-health-check.
Health
With Micronaut Management, the mcp health indicator pings every server concurrently, and reports each connection whose server cannot be reached, or whose client cannot be created, as down. The servers that do not answer within endpoints.health.mcp.timeout (default 10s) are reported down. Disable the indicator with endpoints.health.mcp.enabled=false.
The first health check creates the clients that are not created yet, so it starts the processes of the STDIO servers, for example an npx download. While a request is creating the client of a connection, the health check reports that connection down without waiting.
|
Warning
|
Health checks are not authenticated by default, so anyone who can reach the health endpoint can make the indicator attempt to create the clients that failed, which starts the process of a STDIO server again. Require authentication with endpoints.health.sensitive=true, or serve the management endpoints on a separate port with endpoints.all.port, when the health endpoint is reachable from untrusted networks.
|
|
Warning
|
When any server cannot be reached, the mcp indicator is down, so the /health and /health/readiness endpoints answer 503 Service Unavailable; /health/liveness is not affected. A readiness probe on these endpoints takes the application out of service when a server that it can do without is down. The indicator also pings the embeddedServer connection of an application that is itself an MCP server, without credentials, so it is down when that endpoint requires authentication. In these cases, disable the indicator.
|
Migrating from 2.1
The micronaut.mcp.client.transport property is deprecated and no longer selects the transport: the transport of a connection is set by where it is declared, and connections of both transports can be used together. Its only remaining effect is described below. In particular, micronaut.mcp.client.transport: STDIO no longer removes the embeddedServer connection of an application that is itself an HTTP MCP server, so the tool providers provide the application’s own tools; leave them out with an McpToolFilter, as shown above.
The langchain4j.mcp.client.transport.stdio.commands property is deprecated: as in 2.1, it declares a STDIO connection named stdio only when micronaut.mcp.client.transport is STDIO, and it is ignored otherwise. Declare the connection under micronaut.mcp.client.stdio instead, and note that the property there is command, not commands:
# Before
micronaut.mcp.client.transport: STDIO
langchain4j.mcp.client.transport.stdio.commands: [npx, -y, "@modelcontextprotocol/server-filesystem@<version>", /tmp]
# After
micronaut.mcp.client.stdio.stdio.command: [npx, -y, "@modelcontextprotocol/server-filesystem@<version>", /tmp]The application logs a warning when it uses either deprecated property. See also the breaking changes.
Authorization
To call MCP servers on behalf of the user, set propagate-authorization on an HTTP connection: the Authorization header of the HTTP request the application is handling, such as the user’s bearer token, is sent to the MCP server. Only bearer tokens are propagated; set propagate-any-authorization-scheme to also propagate other schemes, such as Basic credentials.
micronaut.mcp.client.http.weather.url=https://weather.example.com/mcp
micronaut.mcp.client.http.weather.propagate-authorization=trueTo compute headers for each request otherwise, for example to send an OAuth access token that is refreshed, declare a bean of type io.micronaut.mcp.conf.client.McpClientHeadersProvider. Both apply to the LangChain4j and the Java SDK clients, and are evaluated on the thread that calls the client: call it from the thread handling the request for the Authorization header to be propagated. The asynchronous Java SDK client evaluates them in the context its subscriber propagates, such as the request a reactive controller is handling.
A headers provider is asked for every connection, unless it overrides supports(McpClientHttpConfiguration): check the connection, so that a token meant for one MCP server is not sent to the others.
Provider headers override static headers even when the names use different capitalization. Connections that propagate authorization or use a headers provider fetch tool, resource, and prompt catalogs on each lookup so the server can select the entries visible to the current caller.
|
Warning
|
The MCP authorization specification forbids passing through a token whose audience is not the MCP server: a server that follows it rejects the token, and one that skips the audience check becomes a confused deputy. Only propagate the Authorization header to MCP servers that accept the tokens issued for the application, for example servers of the same organization behind the same authorization server. Otherwise exchange the user’s token for one whose audience is the MCP server, for example with OAuth 2.0 Token Exchange, in a custom McpClientHeadersProvider.
|
|
Important
|
The client of a connection, and so its MCP session, is shared by every user of the application: the session is created for the first user, and the propagated Authorization header applies to each request, not to the session. An MCP server that binds its sessions to the user that initialized them, as the specification recommends, rejects or mixes up the calls of other users. Connections that propagate authorization need a server without user-bound sessions, or a connection for each user.
|
Initialization, pings, reconnections, and replies to server requests can all run outside a user request. If the MCP server requires authentication for those operations, configure a headers provider that can supply application credentials when the current request is absent, for example a client credentials token.
Micronaut HTTP Client
By default the clients send their requests with the JDK HTTP client. Set http-client to MICRONAUT on an HTTP connection to use the Micronaut HTTP client instead, with the micronaut-http-client dependency: the client filters of the application apply, and service-id names the micronaut.http.services entry that configures the client, for example its SSL, proxy or timeouts. The service ID selects filters such as @ClientFilter(serviceId = "weather") even when the service entry omits url. In that case, the connection URL supplies the host. With either HTTP client, a URL without a path uses / for LangChain4j and /mcp for the MCP Java SDK. Without service-id, the default client configuration applies, with the request-timeout of the connection, or its timeout, as the read timeout.
micronaut.mcp.client.http.weather.url=https://weather.example.com/mcp
micronaut.mcp.client.http.weather.http-client=MICRONAUT
micronaut.mcp.client.http.weather.service-id=weather
micronaut.http.services.weather.read-timeout=60s
micronaut.http.services.weather.follow-redirects=falseThis applies to the LangChain4j and the Java SDK clients. Responses streamed as server-sent events are read as they arrive. A message of the server larger than max-message-size (default 16MB), counted in bytes, fails the request. When the server closes the stream of a response before it sends the response, the client resumes it from its last event, after the retry delay the server sets. The Java SDK client listens to the stream of the messages the server sends on its own, such as the notifications that its tools changed, reconnecting when it ends; as the LangChain4j HTTP transport, the LangChain4j client does not.
The request-timeout or timeout of a connection becomes the read-timeout of its client, and redirects are not followed, since MCP does not use them and following one could send the token of a user to another server. With service-id the micronaut.http.services entry configures the client instead: set its read-timeout and follow-redirects: false there. The read-idle-timeout of the client (default 5m) still applies: it closes the stream of a server that stays quiet that long, and the Java SDK client then reconnects.
|
Warning
|
The client filters of the application apply to the requests sent to MCP servers, including third-party ones. Restrict the filters that add credentials, for example with @ClientFilter(serviceId = …) or path patterns, so that they do not reach MCP servers they are not meant for.
|
|
Warning
|
The responses are read on the event loop of the Micronaut HTTP client, which by default is shared with the HTTP server. Never call a blocking client API, such as the LangChain4j client or the Java SDK McpSyncClient, on an event loop: it would wait for a response that the blocked event loop cannot read. Call them from a thread that may block, for example with @ExecuteOn(TaskExecutors.BLOCKING), or use the asynchronous Java SDK client. The messages are parsed, and the handlers called, on the blocking executor.
|
Testing an MCP server
If you are building an MCP Server, you can test it by injecting a bean of type dev.langchain4j.mcp.client.McpClient in your tests.
The MCP Client pointing to your MCP Server has a name qualifier with value embeddedServer.
You can find the source code of this project in this repository: