001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.mcp.v20260728;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022import java.nio.charset.StandardCharsets;
023import java.security.*;
024import java.util.*;
025import java.util.concurrent.Flow;
026import java.util.logging.Level;
027import java.util.logging.Logger;
028
029import org.apache.juneau.bean.jsonrpc.*;
030import org.apache.juneau.bean.mcp.v20260728.*;
031import org.apache.juneau.commons.concurrent.*;
032import org.apache.juneau.commons.inject.*;
033import org.apache.juneau.commons.utils.JsonValueSafety;
034import org.apache.juneau.http.tracing.TraceContextCarrier;
035import org.apache.juneau.marshall.collections.*;
036import org.apache.juneau.marshall.sse.SseEvent;
037import org.apache.juneau.rest.server.RestRequest;
038import org.apache.juneau.rest.server.tracing.*;
039import org.apache.juneau.marshall.jcs.JcsSerializer;
040import org.apache.juneau.marshall.json.JsonParser;
041import org.apache.juneau.marshall.marshaller.Jcs;
042import org.apache.juneau.marshall.marshaller.Json;
043import org.apache.juneau.marshall.serializer.SerializeException;
044import org.apache.juneau.rest.server.mcp.McpCompletionRef;
045import org.apache.juneau.rest.server.mcp.McpCompletionRequest;
046import org.apache.juneau.rest.server.mcp.McpCompletionResult;
047import org.apache.juneau.rest.server.mcp.McpCursor;
048import org.apache.juneau.rest.server.mcp.McpDispatchResult;
049import org.apache.juneau.rest.server.mcp.McpErrorKind;
050import org.apache.juneau.rest.server.mcp.McpExchange;
051import org.apache.juneau.rest.server.mcp.McpParamUtils;
052import org.apache.juneau.rest.server.mcp.McpPromptHandler;
053import org.apache.juneau.rest.server.mcp.McpResourceHandler;
054import org.apache.juneau.rest.server.mcp.McpResourceTemplateHandler;
055import org.apache.juneau.rest.server.mcp.McpResponseResult;
056import org.apache.juneau.rest.server.mcp.McpServerConfig;
057import org.apache.juneau.rest.server.mcp.McpStreamResult;
058import org.apache.juneau.rest.server.mcp.McpSubscriptionBroker;
059import org.apache.juneau.rest.server.mcp.McpToolHandler;
060import org.apache.juneau.rest.server.mcp.McpToolOutcome;
061
062/**
063 * {@link org.apache.juneau.rest.server.mcp.McpRevision} implementation for MCP revision {@code 2026-07-28}.
064 *
065 * <p>
066 * Owns this revision's stateless JSON-RPC method table, per-request {@code _meta} negotiation,
067 * SEP-2243 {@code Mcp-Method}/{@code Mcp-Name} header agreement checks, {@code server/discover}
068 * dispatch, and error-code table. Every request is independently negotiated from its own
069 * {@code _meta}; no handshake, session, or prior-request state exists.
070 *
071 * <p>
072 * <b>Constructed per binding, not shared as a singleton.</b> The bound servlet or mixin builds a
073 * fresh instance on every {@code revision()} call, passing its {@link McpOptions#getCapabilities()}
074 * result and its published {@link McpCacheConfig} into the constructor — see {@link McpRestServlet}
075 * and {@link McpEndpoint}. A {@code null} capabilities override auto-derives {@code server/discover}
076 * capabilities from the registered tool/prompt/resource/resource-template lists; a non-{@code null}
077 * override is advertised as-is. The cache config is binding-owned: it is supplied once at
078 * construction, is never {@code null}, and is treated as static and request-independent for the
079 * lifetime of this instance — every page of a given list method resolves to identical cache values.
080 * The instance retains no request-derived state.
081 */
082@SuppressWarnings({
083   "java:S2176", // Settled, intentional name shadow against the neutral org.apache.juneau.rest.server.mcp.McpRevision SPI
084                 // (renaming this to e.g. AbstractMcpRevision was evaluated and rejected): every dated adapter binding
085                 // class is deliberately de-versioned to plain "McpRevision" and differentiated from its siblings only by
086                 // package, matching the revision-string-free naming already used throughout each vNNNNNNNN module.
087   "resource" // The McpSubscription (AutoCloseable) returned by registerIfUnder is handed to the streaming publisher, which closes it
088})
089public final class McpRevision implements org.apache.juneau.rest.server.mcp.McpRevision {
090
091   private final ServerCapabilities capabilities;
092   private final McpCacheConfig cacheConfig;
093   private final String instructions;
094   private final McpMrtrConfig mrtrConfig;
095
096   /**
097    * Constructor. Uses an empty {@link McpCacheConfig} (no cache hints emitted on any result) and no
098    * discovery instructions.
099    *
100    * @param capabilities Explicit capabilities to advertise on {@code server/discover}, or <jk>null</jk>
101    *    to auto-derive from the registered tool/prompt/resource lists.
102    */
103   public McpRevision(ServerCapabilities capabilities) {
104      this(capabilities, new McpCacheConfig());
105   }
106
107   /**
108    * Constructor. Advertises no discovery instructions.
109    *
110    * @param capabilities Explicit capabilities to advertise on {@code server/discover}, or <jk>null</jk>
111    *    to auto-derive from the registered tool/prompt/resource lists.
112    * @param cacheConfig Binding-owned cache configuration. Must not be <jk>null</jk>.
113    */
114   public McpRevision(ServerCapabilities capabilities, McpCacheConfig cacheConfig) {
115      this(capabilities, cacheConfig, null);
116   }
117
118   /**
119    * Constructor. Uses a default {@link McpMrtrConfig} (AES-GCM ephemeral codec, 5-minute
120    * {@code requestState} TTL, 10-round cap).
121    *
122    * @param capabilities Explicit capabilities to advertise on {@code server/discover}, or <jk>null</jk>
123    *    to auto-derive from the registered tool/prompt/resource lists.
124    * @param cacheConfig Binding-owned cache configuration. Must not be <jk>null</jk>.
125    * @param instructions Optional free-form {@code server/discover} usage instructions, or <jk>null</jk>
126    *    to omit them.
127    */
128   public McpRevision(ServerCapabilities capabilities, McpCacheConfig cacheConfig, String instructions) {
129      this(capabilities, cacheConfig, instructions, new McpMrtrConfig());
130   }
131
132   /**
133    * Constructor.
134    *
135    * @param capabilities Explicit capabilities to advertise on {@code server/discover}, or <jk>null</jk>
136    *    to auto-derive from the registered tool/prompt/resource lists.
137    * @param cacheConfig Binding-owned cache configuration. Must not be <jk>null</jk>.
138    * @param instructions Optional free-form {@code server/discover} usage instructions, or <jk>null</jk>
139    *    to omit them.
140    * @param mrtrConfig Binding-owned MRTR (Multi-Round-Trip Request) configuration. Must not be <jk>null</jk>.
141    */
142   public McpRevision(ServerCapabilities capabilities, McpCacheConfig cacheConfig, String instructions, McpMrtrConfig mrtrConfig) {
143      this.capabilities = capabilities;
144      this.cacheConfig = Objects.requireNonNull(cacheConfig, "cacheConfig");
145      this.instructions = instructions;
146      this.mrtrConfig = Objects.requireNonNull(mrtrConfig, "mrtrConfig");
147   }
148
149   /** JSON-RPC error code: parse error. Never reported by this revision (see {@link McpErrorKind#PARSE_ERROR}). */
150   public static final int CODE_PARSE_ERROR = -32700;
151
152   /** JSON-RPC error code: invalid request. */
153   public static final int CODE_INVALID_REQUEST = -32600;
154
155   /** JSON-RPC error code: method not found. */
156   public static final int CODE_METHOD_NOT_FOUND = -32601;
157
158   /** JSON-RPC error code: invalid params. */
159   public static final int CODE_INVALID_PARAMS = -32602;
160
161   /** JSON-RPC error code: internal error. */
162   public static final int CODE_INTERNAL_ERROR = -32603;
163
164   /**
165    * SEP-2322 error code: the client did not advertise a capability ({@code elicitation}) required to receive an
166    * {@code input_required} result. Pinned directly by the SEP-2322 schema (spec Open item #3).
167    */
168   public static final int CODE_MISSING_REQUIRED_CLIENT_CAPABILITY = -32021;
169
170   /**
171    * MRTR error code: the echoed {@code requestState} has expired (past its sealed {@code expiresAtMs}). This
172    * plan's own pin, chosen from the JSON-RPC-reserved {@code -32000}..{@code -32099} server-error range adjacent
173    * to the schema-pinned {@code -32021}; not a SEP-2322-sourced value.
174    */
175   public static final int CODE_REQUEST_STATE_EXPIRED = -32022;
176
177   /**
178    * MRTR error code: the echoed {@code requestState}'s embedded round counter is at or above the configured
179    * max-rounds cap. This plan's own pin (same range/rationale as {@link #CODE_REQUEST_STATE_EXPIRED}).
180    */
181   public static final int CODE_MAX_ROUNDS_EXCEEDED = -32023;
182
183   /**
184    * C8 error code: the server already has {@code maxConcurrentSubscriptions} live {@code
185    * subscriptions/listen} streams. This plan's own pin (same {@code -32000}..{@code -32099}
186    * server-error range and rationale as {@link #CODE_REQUEST_STATE_EXPIRED} / {@link #CODE_MAX_ROUNDS_EXCEEDED});
187    * not sourced from SEP-2575.
188    */
189   public static final int CODE_TOO_MANY_SUBSCRIPTIONS = -32024;
190
191   /**
192    * MRTR error code: an operator-configured {@link ReplayCache} reports that the echoed {@code requestState}
193    * has already been consumed once before. Only ever thrown when {@link McpMrtrConfig#getReplayCache()} is
194    * non-<jk>null</jk> &mdash; replay rejection is opt-in (same range/rationale as
195    * {@link #CODE_REQUEST_STATE_EXPIRED}).
196    */
197   public static final int CODE_REQUEST_STATE_REPLAYED = -32025;
198
199   /**
200    * MRTR error code: the current request's {@code arguments} do not hash to the same value as the arguments
201    * sealed at PAUSE time &mdash; the client has resumed with a different argument set than the one the paused
202    * operation originally authorized. Always checked, unlike {@link #CODE_REQUEST_STATE_REPLAYED} (same
203    * range/rationale as {@link #CODE_REQUEST_STATE_EXPIRED}).
204    */
205   public static final int CODE_REQUEST_STATE_ARGUMENTS_MISMATCH = -32026;
206
207   /** Default server name reported by {@code server/discover} when the config supplies no server identity. */
208   public static final String DEFAULT_SERVER_NAME = "juneau-rest-server-mcp";
209
210   private static final String META_KEY = "_meta";
211   private static final String PARAM_ARGUMENTS = "arguments";
212
213   private static final String INTERNAL_ERROR_MESSAGE = "Internal error";
214
215   private static final Logger LOG = Logger.getLogger(McpRevision.class.getName());
216
217   // 16 random bytes -> 22 base64url chars (unpadded): matches EphemeralKeyProvider's keyId minting pattern,
218   // sized generously since a jti only ever travels inside the AEAD-sealed plaintext, never on its own.
219   private static final int JTI_BYTES = 16;
220   private static final SecureRandom JTI_RANDOM = new SecureRandom();
221   private static final Base64.Encoder B64URL = Base64.getUrlEncoder().withoutPadding();
222   private static final Base64.Decoder B64URL_DECODER = Base64.getUrlDecoder();
223
224   // RFC 8785 canonicalizer for the argument hash, deliberately configured for UNBOUNDED depth with recursion
225   // detection: JcsSerializer's inherited depth-limit default of 100 SILENTLY truncates over-depth nodes to
226   // null, which would let two argument sets differing only below the limit hash identically while the handler
227   // still received the divergent subtree. Configuring an unbounded max-depth here makes the hash cover the
228   // full subtree, and enabling recursion detection fails fast, rather than looping, on a pathological cyclic
229   // structure. The complementary JSON value-safety check performed as part of the arguments-hash step is what
230   // actually bounds attacker-controlled depth, size, and CPU: this canonicalizer only guarantees that whatever
231   // passes that guard is hashed in full.
232   private static final Jcs JCS = new Jcs(
233      JcsSerializer.create().maxDepth(Integer.MAX_VALUE).detectRecursions().build(), JsonParser.DEFAULT);
234
235   /**
236    * This revision instance's binding-owned MRTR (Multi-Round-Trip Request) configuration, as supplied at
237    * construction time.
238    *
239    * <p>
240    * Package-visible so tests can confirm the binding-level memoization contract documented on
241    * {@link McpRestServlet#getMcpOptions()} / {@link McpEndpoint#getMcpOptions()}: two {@link McpRevision}
242    * instances built from the same binding must share the same {@link McpMrtrConfig} (and therefore the
243    * same {@link RequestStateCodec}), even though each dispatched request constructs its own
244    * {@link McpRevision}.
245    *
246    * @return The MRTR configuration. Never <jk>null</jk>.
247    */
248   McpMrtrConfig mrtrConfig() {
249      return mrtrConfig;
250   }
251
252   @Override /* McpRevision */
253   public String protocolVersion() {
254      return McpProtocol.VERSION_2026_07_28;
255   }
256
257   @Override /* McpRevision */
258   public int errorCode(McpErrorKind kind) {
259      return switch (kind) {
260         case INVALID_REQUEST -> CODE_INVALID_REQUEST;
261         case UNKNOWN_METHOD -> CODE_METHOD_NOT_FOUND;
262         case TOOL_NOT_FOUND, PROMPT_NOT_FOUND, RESOURCE_NOT_FOUND, INVALID_PARAMS -> CODE_INVALID_PARAMS;
263         case INTERNAL_ERROR -> CODE_INTERNAL_ERROR;
264         case PARSE_ERROR -> CODE_PARSE_ERROR;
265      };
266   }
267
268   @Override /* McpRevision */
269   @SuppressWarnings({
270      "java:S3776" // Cognitive complexity acceptable for the single JSON-RPC dispatch entry point; splitting the notification/response/stream branching and the McpException/Exception recovery paths would fragment one cohesive request-to-result routine without real clarity gain.
271   })
272   public McpDispatchResult dispatch(McpExchange exchange, McpServerConfig config, BeanStore ctx) {
273      reqnn("exchange", exchange);
274      reqnn("config", config);
275      reqnn("ctx", ctx);
276
277      var req = exchange.request();
278      if (req == null)
279         return new McpResponseResult(reportError(ctx, null, errorCode(McpErrorKind.INVALID_REQUEST), "Request envelope is null"));
280
281      var id = req.getId();
282      var method = req.getMethod();
283
284      if (isEmpty(method))
285         return JsonRpcResponse.notification(id) ? null
286            : new McpResponseResult(reportError(ctx, id, errorCode(McpErrorKind.INVALID_REQUEST), "Missing method"));
287
288      // SEP-2350 per-operation step-up enforcement at the POST-parse point (method now known).  Deliberately OUTSIDE
289      // the try below: an insufficient-scope 403 (with its WWW-Authenticate step-up challenge) must propagate as a real
290      // HTTP 403 through the response processors, not be caught and folded into a JSON-RPC error over HTTP 200.
291      enforceStepUpScopes(method, req.getParams(), ctx);
292
293      try {
294         validateHeaders(exchange, req);
295         validateMeta(req.getParams());
296         if (McpMethods.SUBSCRIPTIONS_LISTEN.equals(method))
297            return JsonRpcResponse.notification(id) ? null
298               : new McpStreamResult(dispatchSubscriptionsListen(exchange, id, req.getParams(), config, ctx));
299         var result = finalizeResult(invoke(method, req.getParams(), config, ctx), config, ctx);
300         return JsonRpcResponse.notification(id) ? null : new McpResponseResult(JsonRpcResponse.ok(id, result));
301      } catch (McpException e) {
302         if (JsonRpcResponse.notification(id))
303            return null;
304         recordRpcError(ctx, e.getCode(), e.getMessage());
305         return new McpResponseResult(new JsonRpcResponse()
306            .setJsonrpc(McpProtocol.JSON_RPC_2_0)
307            .setId(id)
308            .setError(e.toJsonRpcError()));
309      } catch (Exception e) {
310         if (JsonRpcResponse.notification(id))
311            return null;
312         LOG.log(Level.WARNING, e, () -> "MCP request failed with an internal error.");
313         var code = errorCode(McpErrorKind.INTERNAL_ERROR);
314         recordRpcError(ctx, code, INTERNAL_ERROR_MESSAGE);
315         return new McpResponseResult(JsonRpcResponse.errorResponse(id, code, INTERNAL_ERROR_MESSAGE));
316      }
317   }
318
319   /**
320    * Enforces SEP-2350 per-operation step-up scopes for a dispatched request (the POST-parse enforcement point).
321    *
322    * <p>
323    * A no-op unless an {@link McpOptions} bean is bound and its {@link McpResourceServerConfig} is
324    * {@link McpResourceServerConfig#isEnabled() enabled} with a per-operation scope configured for this operation.  The
325    * MCP method &mdash; and thus the operation identity ({@link McpRoutingNames#routingName routing name}) &mdash; is
326    * known here (unlike the pre-parse {@code @RestStartCall} bearer gate), so a scoped {@code 403 insufficient_scope}
327    * step-up challenge naming exactly this operation's required scopes can be emitted.  Delegates the actual
328    * granted-vs-required comparison and challenge construction to {@link McpResourceServerSupport#enforceOperationScopes}.
329    *
330    * @param method The resolved JSON-RPC method.  Never <jk>null</jk>/empty at the call site.
331    * @param params The raw JSON-RPC request params (used to derive the operation name and passed through verbatim as
332    *    the {@link McpOperationContext#params() resolver seam}).
333    * @param ctx The per-request bean store (carries the bound {@link McpOptions} and {@link RestRequest}).
334    */
335   private static void enforceStepUpScopes(String method, Object params, BeanStore ctx) {
336      var opt = ctx.getBean(McpOptions.class).orElse(null);
337      if (opt == null)
338         return;
339      var cfg = opt.getResourceServer();
340      if (!cfg.isEnabled())
341         return;
342      var granted = McpResourceServerSupport.grantedScopes(
343         ctx.getBean(RestRequest.class).map(RestRequest::getHttpServletRequest).orElse(null));
344      var rn = McpRoutingNames.routingName(method, params);
345      var name = isEmpty(rn) ? null : rn;
346      var rawParams = params instanceof Map<?,?> m ? castParams(m) : Map.<String,Object>of();
347      McpResourceServerSupport.enforceOperationScopes(cfg, granted, new McpOperationContext(method, name, rawParams));
348   }
349
350   @SuppressWarnings({
351      "unchecked" // castParams narrows the wildcard JSON-RPC params map to Map<String,Object>; JSON object keys are always strings
352   })
353   private static Map<String,Object> castParams(Map<?,?> m) {
354      return (Map<String,Object>)m;
355   }
356
357   /**
358    * Capability-gates, limit-checks, registers, and constructs the streaming publisher for {@code
359    * subscriptions/listen}. Bypasses {@link #finalizeResult} / {@link JsonRpcResponse#ok}: the successful
360    * result is a {@code Flow.Publisher<SseEvent>}, not a JSON-RPC envelope. A thrown {@link McpException}
361    * (for example the over-limit case) is caught by {@link #dispatch}'s existing {@code McpException}
362    * handler, which builds the normal JSON-RPC error envelope.
363    *
364    * @param exchange The transport-neutral request/header accessor, used to enforce the SSE {@code Accept}
365    *    gate below before any broker registration happens.
366    * @param id The JSON-RPC request id. Never <jk>null</jk> (this method is never called for a notification).
367    * @param params The opaque request params. Must decode to a {@code SubscriptionsListenRequest}.
368    * @param config The neutral handler registry, used to auto-derive capabilities when none were set explicitly.
369    * @param ctx The per-request bean store, expected to carry a bound {@link McpSubscriptionBroker}
370    *    and a bound {@link McpOptions}. In production the options bean is normally present —
371    *    {@code McpRestServlet#getMcpOptions()} / {@code McpEndpoint#mcpOptionsBean()} publish it into
372    *    the {@code RestContext} bean store that this request-scoped {@code ctx} wraps as its parent, since the
373    *    neutral core cannot add it directly ({@code McpOptions} is a v2 type). The
374    *    {@code orElseGet(McpSubscriptionsConfig::new)} fallback below is defense-in-depth only (e.g. a
375    *    hand-built {@code ctx} in a direct-dispatch test that omits it).
376    * <p>
377    * <b>SSE negotiation gate (checked first, before any broker registration):</b> every MCP servlet binding
378    * defaults an unqualified request to {@code Accept: application/json}. A {@code subscriptions/listen}
379    * call that never negotiated {@code text/event-stream} would still register with the broker and hand
380    * back a real {@code Flow.Publisher}, but {@code ReactiveResponseProcessor} would then render it in its
381    * BUFFER shape (unbounded {@code request(Long.MAX_VALUE)} demand, collected into a list that is only
382    * flushed once the publisher completes — which, for a live subscription, is never, until the connection
383    * itself drops). Because this dead-client cleanup is write-failure-driven (see the class javadoc), a
384    * BUFFER-shape stream never even attempts a write, so the broker slot, the pump thread, and the
385    * heartbeat executor all leak permanently, and any caller can trigger this for free. Checking {@code
386    * exchange.header("Accept")} here, before {@link McpSubscriptionBroker#registerIfUnder} is ever called,
387    * closes that hole at zero cost to a well-behaved caller (see {@code McpClient#listen} /
388    * {@code AbstractMcpClient#openEventStream}, which already always negotiate SSE on this call).
389    *
390    * <p>
391    * {@code maxConcurrentSubscriptions} is enforced as a hard cap, not an advisory one: the admission check
392    * and the registration are one atomic step via {@link McpSubscriptionBroker#registerIfUnder}, so
393    * concurrent {@code subscriptions/listen} calls against the same broker (e.g. a custom broker explicitly
394    * shared across multiple bindings via {@link McpOptions#setSubscriptionBroker}) cannot all observe room
395    * under the cap and all register, which a separate {@code activeCount()} check followed by a separate
396    * {@code register(...)} call would allow.
397    *
398    * <p>
399    * The broker registers under a fresh {@link UUID}, never under the client-supplied JSON-RPC request
400    * {@code id}: the broker's registry is process-wide (see {@link McpEndpoint#subscriptionBroker()}), so
401    * two unrelated concurrent listens that happen to share the same client id would otherwise evict each
402    * other's stream (the second {@code register(...)} call under a shared key closes whichever
403    * subscription is already registered there). The client's original {@code id} is passed to
404    * {@link SubscriptionsListenPublisher} unchanged and is still what every ack/notification frame on that
405    * client's own stream carries as its {@code _meta.subscriptionId} — this only decouples the *internal*
406    * registry key from the *wire* id, which stays exactly as the spec expects.
407    *
408    * @return The {@code Flow.Publisher<SseEvent>} for the newly registered subscription.
409    * @throws McpException If the caller never negotiated {@code text/event-stream}, the broker bean is
410    *    missing, or {@code maxConcurrentSubscriptions} is reached.
411    */
412   private Flow.Publisher<SseEvent> dispatchSubscriptionsListen(McpExchange exchange, Object id, Object params, McpServerConfig config, BeanStore ctx) {
413      requireEventStreamAccept(exchange);
414      var request = Json.to(Json.of(params), SubscriptionsListenRequest.class);
415      var caps = discoverCapabilities(config);
416      var honoredFilter = SubscriptionCapabilityGate.honor(request.getNotifications(), caps);
417
418      var broker = ctx.getBean(McpSubscriptionBroker.class)
419         .orElseThrow(() -> new McpException(CODE_INTERNAL_ERROR, "McpSubscriptionBroker not bound in BeanStore"));
420      var subscriptionsConfig = ctx.getBean(McpOptions.class).map(McpOptions::getSubscriptions).orElseGet(McpSubscriptionsConfig::new);
421      // registerIfUnder admission-checks and registers as one atomic step (hard cap, not advisory) — a
422      // separate activeCount() check followed by a separate register() call would leave a TOCTOU window
423      // open for concurrent listen requests racing the same per-binding broker (see
424      // McpOptions#resolveSubscriptionBroker()). The registry key is a server-minted UUID, deliberately
425      // NOT String.valueOf(id): see the javadoc above.
426      var subscription = broker.registerIfUnder(subscriptionsConfig.getMaxConcurrentSubscriptions(), UUID.randomUUID().toString(), honoredFilter)
427         .orElseThrow(() -> new McpException(CODE_TOO_MANY_SUBSCRIPTIONS, "Maximum concurrent subscriptions exceeded"));
428      var honoredWireFilter = SubscriptionCapabilityGate.toWireFilter(honoredFilter);
429      return new SubscriptionsListenPublisher(id, honoredWireFilter, subscription, subscriptionsConfig.getHeartbeatIntervalMs(), subscriptionsConfig.getIdleTimeoutMs());
430   }
431
432   /**
433    * C1: rejects a {@code subscriptions/listen} call that never negotiated {@code text/event-stream},
434    * before any broker registration happens (see {@link #dispatchSubscriptionsListen}'s javadoc).
435    *
436    * <p>
437    * A bare {@code Accept: * / *} (every media type acceptable) is rejected exactly like an absent
438    * {@code Accept} header: this endpoint requires the caller to have explicitly negotiated
439    * {@code text/event-stream}, not merely to be willing to accept it among everything else. Without this,
440    * a wildcard-accepting request would fall into {@code ReactiveResponseProcessor}'s non-streaming BUFFER
441    * shape (the same permanent-leak hole C1 closes for a missing header), rather than the STREAM shape
442    * this method exists to require. A well-behaved caller is unaffected: both {@code McpClient#listen} and
443    * the underlying {@code AbstractMcpClient#openEventStream} already always send the explicit
444    * {@code text/event-stream} value on this call.
445    *
446    * @param exchange The transport-neutral request/header accessor. Must not be <jk>null</jk>.
447    * @throws McpException If the {@code Accept} header is absent or does not contain {@code text/event-stream}
448    *    (case-insensitive, substring match — a real client's {@code Accept} header is commonly a
449    *    comma-separated list of media-type ranges, not the bare value alone).
450    */
451   private static void requireEventStreamAccept(McpExchange exchange) {
452      var accept = exchange.header("Accept");
453      if (accept == null || ! accept.toLowerCase(Locale.ROOT).contains("text/event-stream"))
454         throw new McpException(CODE_INVALID_REQUEST, "subscriptions/listen requires Accept: text/event-stream");
455   }
456
457   /**
458    * Builds a JSON-RPC error response, first giving an active request-scoped tracing observation a
459    * chance to record the outcome via {@link #recordRpcError(BeanStore, int, String)} &mdash; every
460    * dated dispatch returns JSON-RPC errors over HTTP {@code 200}, so this is the only place such an
461    * outcome reaches an active span.
462    *
463    * @param ctx The request-scoped bean store. Must not be <jk>null</jk>.
464    * @param id The JSON-RPC request id, or <jk>null</jk> when the envelope itself could not be read.
465    * @param code The JSON-RPC error code.
466    * @param message The JSON-RPC error message.
467    * @return The error response. Never <jk>null</jk>.
468    */
469   private static JsonRpcResponse reportError(BeanStore ctx, Object id, int code, String message) {
470      recordRpcError(ctx, code, message);
471      return JsonRpcResponse.errorResponse(id, code, message);
472   }
473
474   /**
475    * Records a JSON-RPC error outcome on the active request-scoped {@link Scope}, if any.
476    *
477    * <p>
478    * A neutral no-op &mdash; no OpenTelemetry import involved &mdash; when no tracer is active for
479    * this request (no {@link Scope} was stashed under {@link TraceContextResponseProcessor#ATTR_SCOPE}
480    * by {@code RestOpInvoker}) or when the request-scoped {@link RestRequest} itself is unavailable
481    * (for example, a unit test dispatching directly against a bare {@link BeanStore}).
482    *
483    * @param ctx The request-scoped bean store. Must not be <jk>null</jk>.
484    * @param code The JSON-RPC error code.
485    * @param message The JSON-RPC error message.
486    */
487   private static void recordRpcError(BeanStore ctx, int code, String message) {
488      ctx.getBean(RestRequest.class).ifPresent(request -> {
489         var scope = request.getAttribute(TraceContextResponseProcessor.ATTR_SCOPE).as(Scope.class).orElse(null);
490         if (scope != null)
491            scope.recordRpcError(code, message);
492      });
493   }
494
495   // --- SEP-2243 header/body agreement -----------------------------------------------------
496
497   private static void validateHeaders(McpExchange exchange, JsonRpcRequest req) {
498      var headerMethod = exchange.header("Mcp-Method");
499      if (headerMethod == null)
500         throw new McpException(CODE_INVALID_REQUEST, "Missing required header: Mcp-Method");
501      var headerName = exchange.header("Mcp-Name");
502      if (headerName == null)
503         throw new McpException(CODE_INVALID_REQUEST, "Missing required header: Mcp-Name");
504      var method = req.getMethod();
505      if (! headerMethod.equals(method))
506         throw new McpException(CODE_INVALID_REQUEST, "Mcp-Method header '" + headerMethod + "' does not match request method '" + method + "'");
507      var name = McpRoutingNames.routingName(method, req.getParams());
508      if (! headerName.equals(name))
509         throw new McpException(CODE_INVALID_REQUEST, "Mcp-Name header '" + headerName + "' does not match request name '" + name + "'");
510   }
511
512   // --- per-request params._meta negotiation -----------------------------------------------
513
514   /**
515    * Validates the opaque {@code params._meta} shape directly.
516    *
517    * <p>
518    * The parsed {@link RequestMeta} bean cannot distinguish a malformed {@code clientCapabilities} (a
519    * scalar/array) from an absent one — parsing either into {@code ClientCapabilities} raises a
520    * generic parse error rather than a validation failure — so metadata shape is checked against
521    * the opaque map to produce the exact per-field {@code -32600} messages naming the exact wire path.
522    *
523    * @param params The opaque request params (the JSON-RPC {@code params} member). Can be <jk>null</jk>.
524    */
525   private static void validateMeta(Object params) {
526      if (! (params instanceof Map<?,?> p))
527         throw new McpException(CODE_INVALID_REQUEST, "Request params must be an object");
528      var meta = p.get(META_KEY);
529      if (! (meta instanceof Map<?,?> m))
530         throw new McpException(CODE_INVALID_REQUEST, "Request params._meta must be an object");
531      var protocolVersion = str(m.get(RequestMeta.KEY_PROTOCOL_VERSION));
532      if (isEmpty(protocolVersion))
533         throw new McpException(CODE_INVALID_REQUEST, "Missing required params._meta." + RequestMeta.KEY_PROTOCOL_VERSION);
534      if (! McpProtocol.VERSION_2026_07_28.equals(protocolVersion))
535         throw new McpException(CODE_INVALID_REQUEST, "Unsupported protocol version: " + protocolVersion);
536      var clientInfo = m.get(RequestMeta.KEY_CLIENT_INFO);
537      if (clientInfo != null && (! (clientInfo instanceof Map<?,?> ci) || isEmpty(str(ci.get("name"))) || isEmpty(str(ci.get("version")))))
538         throw new McpException(CODE_INVALID_REQUEST, "Malformed params._meta." + RequestMeta.KEY_CLIENT_INFO);
539      if (! m.containsKey(RequestMeta.KEY_CLIENT_CAPABILITIES) || m.get(RequestMeta.KEY_CLIENT_CAPABILITIES) == null)
540         throw new McpException(CODE_INVALID_REQUEST, "Missing required params._meta." + RequestMeta.KEY_CLIENT_CAPABILITIES);
541      if (! (m.get(RequestMeta.KEY_CLIENT_CAPABILITIES) instanceof Map<?,?>))
542         throw new McpException(CODE_INVALID_REQUEST, "params._meta." + RequestMeta.KEY_CLIENT_CAPABILITIES + " must be an object");
543   }
544
545   private static String str(Object value) {
546      return value == null ? null : value.toString();
547   }
548
549   /**
550    * Attaches the common success-result finalization to every dispatched result: a {@code "complete"}
551    * {@code resultType} (already the {@link Result} default) and {@link ResultMeta#getServerInfo() server
552    * identity} under {@code _meta}, without disturbing cache hints or payload fields a method already set.
553    *
554    * @param result The neutral-to-wire result returned by {@link #invoke}. Can be any wire result type.
555    * @param config The server configuration supplying server identity.
556    * @return The same {@code result} instance, finalized in place.
557    */
558   private static Object finalizeResult(Object result, McpServerConfig config, BeanStore ctx) {
559      if (result instanceof Result<?> r) {
560         var meta = r.getMeta();
561         if (meta == null)
562            meta = new ResultMeta();
563         meta.setServerInfo(McpWire.serverInfo(config));
564         echoTraceContext(meta, ctx);
565         r.setMeta(meta);
566      }
567      return result;
568   }
569
570   /**
571    * Echoes the request-scoped W3C trace context into a successful result's {@code _meta}.
572    *
573    * <p>
574    * At span-start time, an active {@code TracerHook} bridge (for example {@code OtelTracerHook})
575    * stashes the rendered {@code traceparent} / {@code tracestate} / {@code baggage} values as
576    * {@link RestRequest} attributes under {@link TraceContextResponseProcessor#ATTR_TRACEPARENT} /
577    * {@code ATTR_TRACESTATE} / {@code ATTR_BAGGAGE}. This copies those same values &mdash; already
578    * neutral strings, read here with no OpenTelemetry import &mdash; into <c>meta</c> so a caller can
579    * read the server-started trace identifiers off the JSON-RPC result body, in addition to the HTTP
580    * response headers {@link TraceContextResponseProcessor} emits from the same captured values.
581    *
582    * <p>
583    * A no-op &mdash; no trace keys added &mdash; when no tracer is active (no {@code ATTR_TRACEPARENT}
584    * was stashed) or when the request-scoped {@link RestRequest} itself is unavailable.
585    *
586    * @param meta The result metadata to enrich in place. Must not be <jk>null</jk>.
587    * @param ctx The request-scoped bean store. Must not be <jk>null</jk>.
588    */
589   private static void echoTraceContext(ResultMeta meta, BeanStore ctx) {
590      ctx.getBean(RestRequest.class).ifPresent(request -> {
591         var traceparent = request.getAttribute(TraceContextResponseProcessor.ATTR_TRACEPARENT).as(String.class).orElse(null);
592         if (isEmpty(traceparent))
593            return;
594         meta.setTraceparent(traceparent);
595         var tracestate = request.getAttribute(TraceContextResponseProcessor.ATTR_TRACESTATE).as(String.class).orElse(null);
596         if (! isEmpty(tracestate))
597            meta.setTracestate(tracestate);
598         var baggage = request.getAttribute(TraceContextResponseProcessor.ATTR_BAGGAGE).as(String.class).orElse(null);
599         if (! isEmpty(baggage))
600            meta.setBaggage(baggage);
601      });
602   }
603
604   // --- method table -----------------------------------------------------------------------
605
606   private Object invoke(String method, Object params, McpServerConfig config, BeanStore ctx) {
607      return switch (method) {
608         case McpMethods.SERVER_DISCOVER -> discover(config);
609         case McpMethods.PING -> new PingResult();
610         case McpMethods.TOOLS_LIST -> listTools(config, params, ctx);
611         case McpMethods.TOOLS_CALL -> callTool(config, params, ctx);
612         case McpMethods.PROMPTS_LIST -> listPrompts(config, params, ctx);
613         case McpMethods.PROMPTS_GET -> getPrompt(config, params, ctx);
614         case McpMethods.RESOURCES_LIST -> listResources(config, params, ctx);
615         case McpMethods.RESOURCES_READ -> readResource(config, params, ctx);
616         case McpMethods.RESOURCES_TEMPLATES_LIST -> listResourceTemplates(config, params, ctx);
617         case McpMethods.COMPLETION_COMPLETE -> complete(config, params, ctx);
618         default -> throw new McpException(errorCode(McpErrorKind.UNKNOWN_METHOD), "Method not found: " + method);
619      };
620   }
621
622   // --- cache-hint precedence ---------------------------------------------------------------
623
624   private static McpCacheHint first(McpCacheHint... values) {
625      for (var value : values)
626         if (value != null)
627            return value;
628      return null;
629   }
630
631   private static <T extends CacheableResult<T>> T applyCache(T result, McpCacheHint hint) {
632      if (hint != null) {
633         result.setTtlMs(hint.getTtlMs());
634         result.setCacheScope(hint.getCacheScope());
635      }
636      return result;
637   }
638
639   private McpCacheHint readHint(String uri) {
640      return first(cacheConfig.getResourceReadOverrides().get(uri),
641         cacheConfig.getResourcesRead(), cacheConfig.getDefaultHint());
642   }
643
644   private ServerDiscoverResult discover(McpServerConfig config) {
645      var result = McpWire.discover(discoverCapabilities(config), protocolVersion(), instructions);
646      return applyCache(result, first(cacheConfig.getServerDiscover(), cacheConfig.getDefaultHint()));
647   }
648
649   private ServerCapabilities discoverCapabilities(McpServerConfig config) {
650      var caps = this.capabilities;
651      if (caps == null) {
652         caps = new ServerCapabilities();
653         if (! config.getTools().isEmpty())
654            caps.setTools(new ToolCapability());
655         if (! config.getPrompts().isEmpty())
656            caps.setPrompts(new PromptCapability());
657         if (! config.getResources().isEmpty() || ! config.getResourceTemplates().isEmpty())
658            caps.setResources(new ResourceCapability());
659         if (config.hasAnyCompleter())
660            caps.setCompletions(new CompletionCapability());
661      }
662      return caps;
663   }
664
665   private ListToolsResult listTools(McpServerConfig config, Object params, BeanStore ctx) {
666      var descriptors = config.getTools().stream().map(McpToolHandler::descriptor).toList();
667      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
668      return applyCache(new ListToolsResult()
669         .setTools(page.items().stream().map(McpWire::toWire).toList())
670         .setNextCursor(page.nextCursor()),
671         first(cacheConfig.getToolsList(), cacheConfig.getDefaultHint()));
672   }
673
674   private Object callTool(McpServerConfig config, Object params, BeanStore ctx) {
675      var p = McpParamUtils.asMap(params);
676      var name = McpParamUtils.strParam(p, "name");
677      if (name == null)
678         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing tool name");
679      var handler = config.getTools().stream()
680         .filter(h -> name.equals(h.descriptor().getName()))
681         .findFirst()
682         .orElseThrow(() -> new McpException(errorCode(McpErrorKind.TOOL_NOT_FOUND), "Tool not found: " + name));
683      var args = McpParamUtils.mapParam(p, PARAM_ARGUMENTS);
684      McpSchemaSafety.validateInput(handler.descriptor().getInputSchema(), args);
685      var mrtr = resolveMrtrContext(McpMethods.TOOLS_CALL, p, ctx);
686      try (var store = mrtr.store()) {
687         var outcome = handler.call(args, store);
688         validateStructuredOutput(outcome);
689         return McpWire.toWire(outcome);
690      } catch (McpInputRequiredSignal signal) {
691         return pause(signal, McpMethods.TOOLS_CALL, p, mrtr.currentRound(), mrtr.argumentsHash(), mrtr.target(), ctx);
692      }
693   }
694
695   private static void validateStructuredOutput(McpToolOutcome outcome) {
696      if (outcome == null || outcome.getStructuredContent() == null)
697         return;
698      try {
699         // No deadline: the node bound caps the walk, and a slow host must not fail a valid result.
700         JsonValueSafety.check(outcome.getStructuredContent(), "Tool structuredContent", JsonValueSafety.NO_DEADLINE);
701      } catch (IllegalArgumentException e) {
702         throw new McpException(CODE_INTERNAL_ERROR, e.getMessage());
703      }
704   }
705
706   private ListPromptsResult listPrompts(McpServerConfig config, Object params, BeanStore ctx) {
707      var descriptors = config.getPrompts().stream().map(McpPromptHandler::descriptor).toList();
708      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
709      return applyCache(new ListPromptsResult()
710         .setPrompts(page.items().stream().map(McpWire::toWire).toList())
711         .setNextCursor(page.nextCursor()),
712         first(cacheConfig.getPromptsList(), cacheConfig.getDefaultHint()));
713   }
714
715   private Object getPrompt(McpServerConfig config, Object params, BeanStore ctx) {
716      var p = McpParamUtils.asMap(params);
717      var name = McpParamUtils.strParam(p, "name");
718      if (name == null)
719         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing prompt name");
720      var handler = config.getPrompts().stream()
721         .filter(h -> name.equals(h.descriptor().getName()))
722         .findFirst()
723         .orElseThrow(() -> new McpException(errorCode(McpErrorKind.PROMPT_NOT_FOUND), "Prompt not found: " + name));
724      var args = McpParamUtils.mapParam(p, PARAM_ARGUMENTS);
725      var mrtr = resolveMrtrContext(McpMethods.PROMPTS_GET, p, ctx);
726      try (var store = mrtr.store()) {
727         return McpWire.toWire(handler.get(args, store));
728      } catch (McpInputRequiredSignal signal) {
729         return pause(signal, McpMethods.PROMPTS_GET, p, mrtr.currentRound(), mrtr.argumentsHash(), mrtr.target(), ctx);
730      }
731   }
732
733   private ListResourcesResult listResources(McpServerConfig config, Object params, BeanStore ctx) {
734      var descriptors = config.getResources().stream().map(McpResourceHandler::descriptor).toList();
735      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
736      return applyCache(new ListResourcesResult()
737         .setResources(page.items().stream().map(McpWire::toWire).toList())
738         .setNextCursor(page.nextCursor()),
739         first(cacheConfig.getResourcesList(), cacheConfig.getDefaultHint()));
740   }
741
742   private Object readResource(McpServerConfig config, Object params, BeanStore ctx) {
743      var p = McpParamUtils.asMap(params);
744      var uri = McpParamUtils.strParam(p, "uri");
745      if (uri == null)
746         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing resource uri");
747      var exact = config.getResources().stream()
748         .filter(h -> uri.equals(h.descriptor().getUri()))
749         .findFirst();
750      if (exact.isPresent()) {
751         // MRTR PAUSE/RESUME applies only to the exact-resource path; C4's resource-template branch below is
752         // untouched (spec rule 5). A PAUSE returns before applyCache(...), so a pending result never gets a
753         // cache hint.
754         var mrtr = resolveMrtrContext(McpMethods.RESOURCES_READ, p, ctx);
755         try (var store = mrtr.store()) {
756            return applyCache(McpWire.toWire(exact.get().read(uri, store)), readHint(uri));
757         } catch (McpInputRequiredSignal signal) {
758            return pause(signal, McpMethods.RESOURCES_READ, p, mrtr.currentRound(), mrtr.argumentsHash(), mrtr.target(), ctx);
759         }
760      }
761      var match = config.resolveResourceTemplate(uri);
762      var outcome = match == null ? null : match.handler().read(uri, match.variables(), ctx);
763      if (outcome == null)
764         throw new McpException(errorCode(McpErrorKind.RESOURCE_NOT_FOUND), "Resource not found: " + uri);
765      return applyCache(McpWire.toWire(outcome), readHint(uri));
766   }
767
768   private ListResourceTemplatesResult listResourceTemplates(McpServerConfig config, Object params, BeanStore ctx) {
769      var descriptors = config.getResourceTemplates().stream().map(McpResourceTemplateHandler::descriptor).toList();
770      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
771      return applyCache(new ListResourceTemplatesResult()
772         .setResourceTemplates(page.items().stream().map(McpWire::toWire).toList())
773         .setNextCursor(page.nextCursor()),
774         first(cacheConfig.getResourceTemplatesList(), cacheConfig.getDefaultHint()));
775   }
776
777   private CompleteResult complete(McpServerConfig config, Object params, BeanStore ctx) {
778      var p = McpParamUtils.asMap(params);
779      var ref = completionRef(McpParamUtils.mapParam(p, "ref"));
780      var argument = McpParamUtils.mapParam(p, "argument");
781      var argumentName = McpParamUtils.strParam(argument, "name");
782      if (isEmpty(argumentName))
783         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing argument.name");
784      var value = McpParamUtils.strictStrParam(argument, "value");
785      if (value == null)
786         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing or non-string argument.value");
787      var contextArguments = McpParamUtils.strictStrMapParam(McpParamUtils.mapParam(p, "context"), PARAM_ARGUMENTS);
788
789      var completer = config.completer(ref, argumentName);
790      McpCompletionResult raw;
791      if (completer == null) {
792         raw = McpCompletionResult.empty();
793      } else {
794         var request = new McpCompletionRequest()
795            .setRef(ref)
796            .setArgumentName(argumentName)
797            .setValue(value)
798            .setContextArguments(contextArguments);
799         raw = completer.complete(request, ctx);
800      }
801      return McpWire.toWire(McpCompletionResult.normalize(raw));
802   }
803
804   private McpCompletionRef completionRef(Map<String,Object> refMap) {
805      var type = McpParamUtils.strParam(refMap, "type");
806      if (eq(type, "ref/prompt")) {
807         var name = McpParamUtils.strParam(refMap, "name");
808         if (isEmpty(name))
809            throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing ref.name for ref/prompt");
810         return McpCompletionRef.prompt(name);
811      }
812      if (eq(type, "ref/resource")) {
813         var uri = McpParamUtils.strParam(refMap, "uri");
814         if (isEmpty(uri))
815            throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing ref.uri for ref/resource");
816         return McpCompletionRef.resource(uri);
817      }
818      throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Invalid or missing ref.type: " + type);
819   }
820
821   // --- MRTR (Multi-Round-Trip Request) pause/resume ---------------------------------------
822
823   /**
824    * The per-request MRTR resolution result: the {@link WritableBeanStore} a handler is invoked with (always
825    * carrying {@link McpMrtrCapabilityContext}, and on a RESUME also {@link McpMrtrResumeContext}) plus the
826    * current round decoded from the echoed {@code requestState} (0 on a first-round call), threaded to
827    * {@link #pause} so it can increment without a second unseal.
828    *
829    * <p>
830    * {@code store} is typed {@link WritableBeanStore} (rather than the narrower {@link BeanStore}) specifically
831    * so call sites can close it in a try-with-resources block: any bean a handler resolves through it is tracked
832    * for {@code @PreDestroy} cleanup on <i>this</i> store, not the caller-owned {@code ctx} it wraps (see
833    * {@link BasicBeanStore#close()}), so it must be closed once the handler invocation completes.
834    *
835    * <p>
836    * {@code argumentsHash} is the canonical hash of the current request's {@code arguments} (see
837    * {@link #argumentsHash(Map)}), computed <i>once</i> here &mdash; before the handler runs &mdash; and threaded
838    * to {@link #pause} so the next token seals the hash of what the client actually sent, not a hash recomputed
839    * from the live {@code arguments} map after a handler may have mutated it in place.
840    *
841    * <p>
842    * {@code target} is the operation target resolved by {@link #mrtrTarget(String, Map)} (the tool/prompt
843    * {@code name} or resource {@code uri}), captured at the same pre-handler point as {@code argumentsHash} and
844    * for the same reason: {@link #pause} seals it into the next token's {@link #aad(String, String) AAD}
845    * unchanged, so a handler that mutates the live {@code params} map in place cannot shift which
846    * tool/prompt/resource the next token is bound to.
847    */
848   private record MrtrContext(WritableBeanStore store, int currentRound, String argumentsHash, String target) {}
849
850   /**
851    * Builds the {@link BeanStore} an in-scope handler receives and, on a RESUME, validates the echoed
852    * {@code requestState} before the handler runs.
853    *
854    * <p>
855    * Always wraps {@code ctx} with a {@link McpMrtrCapabilityContext} so a handler can pre-check the client's
856    * advertised {@code elicitation} capability. When the request carries a {@code requestState}
857    * (a RESUME), it is unsealed under the canonical AAD and validated for integrity, method agreement, expiry,
858    * the max-rounds cap, argument-hash agreement (always; see {@link #argumentsHash(Map)}), and replay (only when
859    * {@link McpMrtrConfig#getReplayCache()} is configured; see {@link #checkReplay(ReplayCache, String, long)})
860    * &mdash; any failure raises the mapped {@link McpException} <i>before</i> the handler is re-invoked &mdash;
861    * then the decoded continuation and the client's {@code inputResponses} are exposed via
862    * {@link McpMrtrResumeContext}.
863    *
864    * <p>
865    * <b>Check ordering is deliberate.</b> The stateless argument-hash comparison runs <i>before</i> the
866    * (stateful) replay {@code checkAndRecord}, so a submission carrying the wrong {@code arguments} is rejected
867    * without ever consuming the token's {@code jti} &mdash; an attacker holding only a leaked token (but not the
868    * arguments) cannot burn a victim's in-flight resume, and an honest client that sends slightly-wrong arguments
869    * does not destroy its own token. The argument hash is also computed <i>once</i> here, before the handler
870    * runs, and threaded to {@link #pause} (see {@link MrtrContext}).
871    *
872    * @param method The in-scope JSON-RPC method. Must not be <jk>null</jk>.
873    * @param params The request params map. Must not be <jk>null</jk>.
874    * @param ctx The request-scoped bean store to wrap. Must not be <jk>null</jk>.
875    * @return The resolved MRTR context. Never <jk>null</jk>.
876    */
877   private MrtrContext resolveMrtrContext(String method, Map<String,Object> params, BeanStore ctx) {
878      // Computed once, up front, from the CURRENT request's arguments: reused both for the RESUME-time
879      // comparison below and (threaded through MrtrContext) for the hash pause(...) seals into the next token,
880      // so a handler that mutates the live arguments map in place cannot make the next token seal a hash the
881      // client can no longer reproduce. Also applies the bounded-traversal + canonicalization guards (see
882      // argumentsHash), so structurally-hostile arguments become a -32602 here on both first-round and RESUME.
883      var argumentsHash = argumentsHash(McpParamUtils.mapParam(params, PARAM_ARGUMENTS));
884      // Captured once, up front, alongside argumentsHash and for the same reason: threaded through MrtrContext
885      // to pause(...) so the AAD sealed into the next token binds the target actually resolved for THIS
886      // request, immune to a handler mutating params in place before pause(...) runs (see MrtrContext's
887      // javadoc above).
888      var target = mrtrTarget(method, params);
889      var requestState = McpParamUtils.strParam(params, "requestState");
890      if (requestState == null) {
891         var wrapped = new BasicBeanStore(ctx)
892            .addBean(McpMrtrCapabilityContext.class, new McpMrtrCapabilityContext(clientElicitationSupported(params)));
893         return new MrtrContext(wrapped, 0, argumentsHash, target);
894      }
895      // Validate the echoed requestState before constructing the BasicBeanStore below: every failure here
896      // throws, and a BasicBeanStore built earlier would never reach a caller's try-with-resources to be
897      // closed (java:S2095). Deferring construction until validation succeeds means no path leaks it.
898      var sealed = mrtrConfig.getCodec().unseal(requestState, aad(method, target), principal(ctx))
899         .orElseThrow(() -> new McpException(CODE_INVALID_PARAMS, "Invalid or tampered requestState"));
900      if (! method.equals(sealed.method()))
901         throw new McpException(CODE_INVALID_PARAMS, "requestState method mismatch");
902      if (sealed.expiresAtMs() <= mrtrConfig.getClock().millis())
903         throw new McpException(CODE_REQUEST_STATE_EXPIRED, "requestState has expired");
904      if (sealed.round() >= mrtrConfig.getMaxRounds())
905         // Client-facing message deliberately omits the configured cap value so server config is not leaked.
906         throw new McpException(CODE_MAX_ROUNDS_EXCEEDED, "Max MRTR rounds exceeded");
907      // Stateless argument-hash agreement BEFORE the stateful replay record (see the ordering note above). A
908      // null sealed hash (e.g. a custom codec that dropped the field) fails closed as an ordinary mismatch
909      // here; a malformed (non-base64url) sealed hash is a codec-contract violation and argumentsMatch itself
910      // throws CODE_INVALID_PARAMS for it (mirroring the null-jti fail-closed check below), rather than
911      // reaching this mismatch branch.
912      if (! argumentsMatch(argumentsHash, sealed.argumentsHash()))
913         throw new McpException(CODE_REQUEST_STATE_ARGUMENTS_MISMATCH, "resumed arguments do not match the original request");
914      var replayCache = mrtrConfig.getReplayCache();
915      if (replayCache != null) {
916         // A null/empty jti reaching the cache is a codec/contract violation (a custom RequestStateCodec that
917         // dropped the field, or a pre-jti in-flight token during a rolling deploy), NOT a store outage: fail
918         // CLOSED here rather than letting a downstream NPE be swallowed by checkReplay's fail-OPEN catch,
919         // which would silently disable replay protection.
920         if (isEmpty(sealed.jti()))
921            throw new McpException(CODE_INVALID_PARAMS, "Invalid or tampered requestState");
922         if (! checkReplay(replayCache, sealed.jti(), sealed.expiresAtMs()))
923            // Client-facing message deliberately omits any cache/backend detail, mirroring the max-rounds
924            // message's "don't leak server config" caution above.
925            throw new McpException(CODE_REQUEST_STATE_REPLAYED, "requestState has already been used");
926      }
927      var inputResponses = McpParamUtils.mapParam(params, "inputResponses");
928      var wrapped = new BasicBeanStore(ctx)
929         .addBean(McpMrtrCapabilityContext.class, new McpMrtrCapabilityContext(clientElicitationSupported(params)))
930         .addBean(McpMrtrResumeContext.class, new McpMrtrResumeContext(sealed.continuation(), inputResponses));
931      return new MrtrContext(wrapped, sealed.round(), argumentsHash, target);
932   }
933
934   /**
935    * Turns a caught {@link McpInputRequiredSignal} into a wire {@link InputRequiredResult}: capability-gates the
936    * client, seals a fresh {@code requestState} carrying the incremented round counter, a fresh {@code jti} (see
937    * {@link #mintJti()}), and the {@code argumentsHash} of the current request's {@code arguments} (see
938    * {@link #argumentsHash(Map)}), and assembles the requested-inputs map.
939    *
940    * <p>
941    * The capability gate runs <i>before</i> any token is minted &mdash; a client that never advertised
942    * {@code elicitation} causes no seal at all, only a {@link #CODE_MISSING_REQUIRED_CLIENT_CAPABILITY} error.
943    *
944    * @param signal The signal thrown by the handler. Must not be <jk>null</jk>.
945    * @param method The in-scope JSON-RPC method this pause is for. Must not be <jk>null</jk>.
946    * @param params The request params map, used only for {@link #clientElicitationSupported(Map)} here &mdash;
947    *    the AAD's operation target is the caller-supplied {@code target}, below, not re-derived from this map.
948    * @param currentRound The round decoded on RESUME (0 on a first-round pause), incremented into the new token.
949    * @param argumentsHash The hash of the current request's {@code arguments}, computed by
950    *    {@link #resolveMrtrContext} <i>before</i> the handler ran and threaded here (see {@link MrtrContext}), so a
951    *    handler that mutated the live {@code arguments} map cannot make this token seal an unreproducible hash.
952    * @param target The operation target sealed into the next token's {@link #aad(String, String) AAD}, resolved
953    *    by {@link #resolveMrtrContext} <i>before</i> the handler ran and threaded here (see {@link MrtrContext}),
954    *    so a handler that mutated the live {@code params} map cannot shift which tool/prompt/resource the next
955    *    token is bound to.
956    * @param ctx The per-request bean store, used to resolve the authenticated {@link #principal(BeanStore)} threaded
957    *    into the codec's {@link RequestStateCodec#seal seal}. Must not be <jk>null</jk>.
958    * @return The assembled, validated {@code input_required} result. Never <jk>null</jk>.
959    */
960   private InputRequiredResult pause(McpInputRequiredSignal signal, String method, Map<String,Object> params, int currentRound, String argumentsHash, String target, BeanStore ctx) {
961      if (! clientElicitationSupported(params))
962         throw new McpException(CODE_MISSING_REQUIRED_CLIENT_CAPABILITY,
963            "Client does not advertise the elicitation capability required for input_required");
964      var state = new McpRequestState(signal.getContinuation(), method, currentRound + 1, mrtrConfig.getClock().millis() + mrtrConfig.getTtlMs(),
965         mintJti(), argumentsHash);
966      var result = new InputRequiredResult().setRequestState(mrtrConfig.getCodec().seal(state, aad(method, target), principal(ctx)));
967      // Each inputRequests value is carried to the wire byte-for-byte as a raw sub-request object (see
968      // McpInputRequiredSignal). The pinned schema models every value as an object; a non-map handler value is a
969      // programming error that surfaces (as a ClassCastException here) via dispatch's -32603 fail-safe.
970      signal.getInputRequests().forEach((id, raw) -> result.putInputRequest(id, new JsonMap((Map<?,?>) raw)));
971      result.validate();
972      return result;
973   }
974
975   /**
976    * The canonical MRTR AAD binding a sealed {@code requestState} to the request that produced it:
977    * {@code method + '\u0000' + protocolVersion + '\u0000' + target} (NUL-separated; see
978    * {@link RequestStateCodec}).
979    *
980    * <p>
981    * <b>The operation {@code target} is folded in so a token is bound to the specific tool/prompt/resource it
982    * paused against, not merely the method.</b> Without it, a token paused for tool A could be resumed against
983    * tool B (or resource {@code uri} A against {@code uri} B) &mdash; both are {@code tools/call} (or
984    * {@code resources/read}), so the method-only AAD verified identically. The {@code target} is the tool
985    * {@code name} for {@code tools/call}, the prompt {@code name} for {@code prompts/get}, and the {@code uri}
986    * for {@code resources/read} (see {@link #mrtrTarget(String, Map)}); a mismatch now fails the GCM tag check,
987    * surfacing as the existing "invalid or tampered requestState" {@link #CODE_INVALID_PARAMS}. Neither
988    * {@code method} nor {@code protocolVersion} can contain a NUL, and {@code target} is the terminal field, so
989    * the three-field NUL join is unambiguous (distinct {@code (method, version, target)} tuples never collide)
990    * &mdash; the same injectivity property the two-field form relied on, extended by one trailing field. The
991    * codec treats this whole string as one opaque AAD field, framing it against {@code keyId}/principal with its
992    * own length-prefixed join (see {@link AeadRequestStateCodec#lengthPrefixJoin}).
993    *
994    * @param method The in-scope JSON-RPC method. Must not be <jk>null</jk>.
995    * @param target The operation target (tool/prompt {@code name} or resource {@code uri}); coalesced to empty
996    *    when <jk>null</jk> (only the three MRTR-wired methods reach here, and each has already validated its
997    *    target as non-null at the call site).
998    * @return The AAD string. Never <jk>null</jk>.
999    */
1000   private String aad(String method, String target) {
1001      return method + '\u0000' + protocolVersion() + '\u0000' + ein(target);
1002   }
1003
1004   /**
1005    * Derives the operation target folded into the {@link #aad(String, String) AAD}: the tool {@code name} for
1006    * {@code tools/call}, the prompt {@code name} for {@code prompts/get}, and the resource {@code uri} for
1007    * {@code resources/read}. Any other method (none of which reach the MRTR pause/resume path) yields
1008    * <jk>null</jk>.
1009    *
1010    * @param method The in-scope JSON-RPC method. Must not be <jk>null</jk>.
1011    * @param params The request params map. Must not be <jk>null</jk>.
1012    * @return The operation target, or <jk>null</jk> for a non-MRTR method.
1013    */
1014   private static String mrtrTarget(String method, Map<String,Object> params) {
1015      return switch (method) {
1016         case McpMethods.TOOLS_CALL, McpMethods.PROMPTS_GET -> McpParamUtils.strParam(params, "name");
1017         case McpMethods.RESOURCES_READ -> McpParamUtils.strParam(params, "uri");
1018         default -> null;
1019      };
1020   }
1021
1022   /**
1023    * Mints a fresh, per-token random {@code jti} for a newly-sealed {@code requestState}, used only to detect
1024    * replay of this exact token (see {@link #checkReplay(ReplayCache, String, long)}).
1025    *
1026    * <p>
1027    * 16 random bytes, base64url-encoded &mdash; the same minting pattern {@link EphemeralKeyProvider} already
1028    * uses for its own {@code keyId}. Collision probability is negligible (128 bits of entropy) and, in any
1029    * case, is not a security property this identifier depends on: it rides inside the AEAD-sealed plaintext, so
1030    * a client can neither forge nor read it without first breaking the GCM tag.
1031    *
1032    * @return A fresh {@code jti}. Never <jk>null</jk>.
1033    */
1034   private static String mintJti() {
1035      var bytes = new byte[JTI_BYTES];
1036      JTI_RANDOM.nextBytes(bytes);
1037      return B64URL.encodeToString(bytes);
1038   }
1039
1040   /**
1041    * Computes the canonical hash of a request's {@code arguments}, sealed at PAUSE time and re-verified at
1042    * RESUME time (see {@code McpRequestState#argumentsHash()}).
1043    *
1044    * <p>
1045    * First runs the module's shared bounded-traversal guard ({@link JsonValueSafety#check(Object, String)}:
1046    * {@code MAX_DEPTH=64}, {@code MAX_NODES}, a traversal-time deadline) so structurally-hostile {@code arguments}
1047    * (excessive depth or node count &mdash; reachable via {@code prompts/get}, which has no other input-shape
1048    * guard, and schemaless {@code tools/call}) become a deterministic {@link #CODE_INVALID_PARAMS} rejection on
1049    * BOTH PAUSE and RESUME, rather than a silent hash collision (the JCS canonicalizer's inherited depth limit
1050    * would otherwise truncate over-depth nodes to {@code null}). It then canonicalizes {@code arguments} per RFC
1051    * 8785 (JSON Canonicalization Scheme) using an <b>unbounded-depth</b> serializer (see {@link #JCS}), SHA-256s
1052    * the canonical UTF-8 bytes, and base64url-encodes the digest (mirroring {@link EphemeralKeyProvider}'s
1053    * existing {@code keyId} encoding convention). An absent or empty {@code arguments} map canonicalizes to the
1054    * empty JSON object {@code "{}"}, giving a single, consistent sentinel hash for calls that take no arguments
1055    * (for example {@code resources/read}'s exact-path branch), so PAUSE and RESUME agree even when there is
1056    * nothing to hash.
1057    *
1058    * <p>
1059    * By design, RFC 8785 canonical equivalences are treated as equal &mdash; for example {@code 1} and
1060    * {@code 1.0} canonicalize identically, so they hash the same and a resume switching between them is not a
1061    * mismatch. A canonicalization failure on a hostile-but-syntactically-legal value (a non-finite number such
1062    * as {@code 1e999}, a lone UTF-16 surrogate, or a {@code BigDecimal}/{@code BigInteger} outside IEEE-754
1063    * range) is mapped to {@link #CODE_INVALID_PARAMS} rather than surfacing as a generic internal error.
1064    *
1065    * <p>
1066    * Package-visible so tests can construct {@link McpRequestState} fixtures whose {@code argumentsHash} agrees
1067    * with a given (or absent) {@code arguments} map without duplicating this derivation.
1068    *
1069    * @param arguments The request's {@code arguments} map, as returned by
1070    *    {@code McpParamUtils.mapParam(params, "arguments")}. Never <jk>null</jk> (empty when absent).
1071    * @return The canonical hash. Never <jk>null</jk>.
1072    * @throws McpException ({@link #CODE_INVALID_PARAMS}) if {@code arguments} violates the structural safety
1073    *    limits or cannot be canonicalized.
1074    */
1075   static String argumentsHash(Map<String,Object> arguments) {
1076      try {
1077         JsonValueSafety.check(arguments, PARAM_ARGUMENTS, JsonValueSafety.NO_DEADLINE); // Node-bounded; no wall clock.
1078      } catch (IllegalArgumentException e) {
1079         throw new McpException(CODE_INVALID_PARAMS, e.getMessage());
1080      }
1081      String canonical;
1082      try {
1083         canonical = JCS.write(arguments);
1084      } catch (SerializeException e) {
1085         // Message deliberately generic (no echo of the offending value), mirroring the other MRTR "don't leak"
1086         // messages: a hostile-but-legal input (non-finite number, lone surrogate, out-of-IEEE BigDecimal) must
1087         // not surface as a -32603 internal error.
1088         throw new McpException(CODE_INVALID_PARAMS, "Invalid arguments: not canonicalizable");
1089      }
1090      return B64URL.encodeToString(sha256(canonical.getBytes(StandardCharsets.UTF_8)));
1091   }
1092
1093   /**
1094    * Constant-time comparison of the current request's {@code argumentsHash} against the one sealed into the
1095    * echoed token. Both operands are base64url of a SHA-256 digest; they are decoded to their raw digest bytes
1096    * and compared with {@link MessageDigest#isEqual(byte[], byte[])}. A <jk>null</jk> sealed hash (for example a
1097    * custom codec that dropped the field) fails closed (returns <jk>false</jk>, surfacing as the ordinary
1098    * {@link #CODE_REQUEST_STATE_ARGUMENTS_MISMATCH} at the call site).
1099    *
1100    * <p>
1101    * A non-<jk>null</jk> sealed hash that is not valid base64url (for example a custom codec that computed
1102    * {@code argumentsHash} some other way) is a codec-contract violation rather than an ordinary mismatch, and
1103    * fails closed the same way the null-{@code jti} codec-contract violation does at the call site: a thrown
1104    * {@link McpException} ({@link #CODE_INVALID_PARAMS}), not a propagated {@link IllegalArgumentException}
1105    * from {@link Base64.Decoder#decode(String)} surfacing as a generic {@link #CODE_INTERNAL_ERROR}.
1106    *
1107    * @param currentHash The hash recomputed from the current request's {@code arguments}. Never <jk>null</jk>.
1108    * @param sealedHash The hash sealed into the echoed token, or <jk>null</jk>.
1109    * @return <jk>true</jk> if the two hashes match.
1110    * @throws McpException ({@link #CODE_INVALID_PARAMS}) if {@code sealedHash} is non-<jk>null</jk> but not
1111    *    valid base64url.
1112    */
1113   private static boolean argumentsMatch(String currentHash, String sealedHash) {
1114      if (sealedHash == null)
1115         return false;
1116      byte[] sealedBytes;
1117      try {
1118         sealedBytes = B64URL_DECODER.decode(sealedHash);
1119      } catch (IllegalArgumentException e) {
1120         // Same fail-closed contract as the null-jti check below: an untrusted or misbehaving codec must
1121         // never turn into a raw exception bubbling up as -32603 (see resolveMrtrContext's ordering note
1122         // on why this stateless check runs before the stateful replay record).
1123         throw new McpException(CODE_INVALID_PARAMS, "Invalid or tampered requestState");
1124      }
1125      return MessageDigest.isEqual(B64URL_DECODER.decode(currentHash), sealedBytes);
1126   }
1127
1128   private static byte[] sha256(byte[] input) {
1129      try {
1130         return MessageDigest.getInstance("SHA-256").digest(input);
1131      } catch (NoSuchAlgorithmException e) { // HTT every JDK guarantees SHA-256 via the standard JCE provider
1132         throw rex(e, "SHA-256 not available");
1133      }
1134   }
1135
1136   /**
1137    * Invokes an operator-configured {@link ReplayCache}, applying the fail-open policy documented on that SPI:
1138    * a thrown exception is logged and treated as first-seen, so a store outage degrades to today's
1139    * already-documented multi-use-tolerant behavior rather than rejecting all MRTR resume traffic.
1140    *
1141    * <p>
1142    * An operator who wants fail-closed-on-store-outage instead must implement that themselves by returning
1143    * <jk>false</jk> from their own {@link ReplayCache#checkAndRecord(String, long)} rather than throwing (see
1144    * the SPI's own Javadoc) &mdash; this method applies no policy beyond "don't let an unexpected exception take
1145    * down resume traffic".
1146    *
1147    * @param replayCache The configured replay cache. Must not be <jk>null</jk> (callers only invoke this when
1148    *    {@link McpMrtrConfig#getReplayCache()} is non-<jk>null</jk>).
1149    * @param jti The token identifier to check. Must not be <jk>null</jk>.
1150    * @param expiresAtMs The sealed token's own absolute expiry, passed through unchanged.
1151    * @return <jk>true</jk> if the cache reports first-seen (or itself failed, fail-open); <jk>false</jk> only
1152    *    when the cache affirmatively reports a replay.
1153    */
1154   private static boolean checkReplay(ReplayCache replayCache, String jti, long expiresAtMs) {
1155      // MCP deliberately opts into fail-open: a thrown failure is logged and treated as first-seen, degrading a
1156      // transient store outage to the same multi-use-tolerant behavior seen when no ReplayCache is wired at all.
1157      return replayCache.checkAndRecord(jti, expiresAtMs, ReplayCache.FailMode.FAIL_OPEN,
1158         e -> LOG.log(Level.WARNING, e, () -> "ReplayCache.checkAndRecord failed; treating requestState as first-seen (fail-open)."));
1159   }
1160
1161   /**
1162    * Resolves the authenticated caller {@link Principal} for the current request, threaded into the
1163    * {@link RequestStateCodec} at seal and unseal so a hardened codec can bind the {@code requestState} to who
1164    * requested it (enables principal-bound AAD).
1165    *
1166    * <p>
1167    * Reads the resource-server principal via {@link McpResourceServerSupport#principal} &mdash; the same
1168    * {@code RestRequest -> HttpServletRequest} lookup {@link #enforceStepUpScopes} uses for granted scopes, so the
1169    * two stay in lock-step. Returns <jk>null</jk> when there is no bound {@link RestRequest} (a direct-dispatch unit
1170    * test), when RS auth is disabled, or when the caller is anonymous &mdash; the codec must seal/unseal cleanly in
1171    * that case.
1172    *
1173    * @param ctx The per-request bean store. Must not be <jk>null</jk>.
1174    * @return The authenticated principal, or <jk>null</jk> when none is available.
1175    */
1176   private static Principal principal(BeanStore ctx) {
1177      return ctx.getBean(RestRequest.class)
1178         .map(RestRequest::getHttpServletRequest)
1179         .map(McpResourceServerSupport::principal)
1180         .orElse(null);
1181   }
1182
1183   /**
1184    * Reads whether the request advertised the client {@code elicitation} capability, from the opaque
1185    * {@code _meta.clientCapabilities} map directly (mirroring {@link #validateMeta}'s opaque-map style rather than
1186    * re-parsing a full {@code RequestMeta}/{@code ClientCapabilities} bean for one key).
1187    *
1188    * @param params The request params map. Must not be <jk>null</jk>.
1189    * <p>
1190    * {@link #validateMeta} has already run for every dispatched request and rejects a missing or non-{@code Map}
1191    * {@code clientCapabilities} with {@link #CODE_INVALID_REQUEST}, so {@code caps} is always a non-<jk>null</jk>
1192    * {@code Map} here &mdash; no defensive type guard is needed.
1193    *
1194    * @return <jk>true</jk> if {@code _meta.clientCapabilities.elicitation} is present and non-<jk>null</jk>.
1195    */
1196   private static boolean clientElicitationSupported(Map<String,Object> params) {
1197      var caps = (Map<?,?>) McpWire.metaMapOrEmpty(params).get(RequestMeta.KEY_CLIENT_CAPABILITIES);
1198      return caps.get("elicitation") != null;
1199   }
1200
1201   // --- trace-context extraction (Part B / trace-context propagation) ----------------------
1202
1203   /**
1204    * This revision's stable, stateless {@link TraceContextExtractor}, published as a {@code @Bean} by
1205    * both {@link McpRestServlet} and {@link McpEndpoint} so an active {@code TracerHook} can recognize
1206    * this revision's resolved {@link JsonRpcRequest} argument and its {@code params._meta} carrier
1207    * before span creation.
1208    *
1209    * <p>
1210    * Imports only the neutral {@code juneau-rest-server} tracing seam ({@link TraceContextExtractor},
1211    * {@link TraceContextCarrier}, {@link TraceOperation}) &mdash; never OpenTelemetry.
1212    */
1213   static final TraceContextExtractor TRACE_CONTEXT_EXTRACTOR = new V2TraceContextExtractor();
1214
1215   /**
1216    * {@link TraceContextExtractor} implementation for revision {@code 2026-07-28}.
1217    *
1218    * <p>
1219    * Recognizes the resolved {@link JsonRpcRequest} among {@code @RestOp}-resolved arguments, reads
1220    * its opaque {@code params._meta} (via {@link McpWire#metaMapOrEmpty(Object)}, since extraction
1221    * runs before {@link #validateMeta(Object)} enforces the per-request contract on a request that
1222    * has not yet been validated), and derives a composite carrier plus a low-cardinality
1223    * {@link TraceOperation}.
1224    */
1225   private static final class V2TraceContextExtractor implements TraceContextExtractor {
1226
1227      @Override /* TraceContextExtractor */
1228      public Optional<TraceContextCarrier> extract(RestRequest request, Object[] resolvedArguments) {
1229         var req = findRequest(resolvedArguments);
1230         if (req == null)
1231            return Optional.empty();
1232         var meta = new LinkedHashMap<>(McpWire.metaMapOrEmpty(req.getParams()));
1233         return Optional.of(new MetaCarrier(meta, request));
1234      }
1235
1236      @Override /* TraceContextExtractor */
1237      public TraceOperation operation(RestRequest request, Object[] resolvedArguments) {
1238         var req = findRequest(resolvedArguments);
1239         return req == null ? TraceOperation.DEFAULT : buildOperation(req);
1240      }
1241
1242      private static JsonRpcRequest findRequest(Object[] resolvedArguments) {
1243         for (var arg : resolvedArguments)
1244            if (arg instanceof JsonRpcRequest r)
1245               return r;
1246         return null;
1247      }
1248
1249      /**
1250       * Derives method, protocol version, request id, and tool/prompt/resource target into a
1251       * {@link TraceOperation}, following the exact pinned MCP/GenAI attribute and span-name mapping:
1252       * {@code "tools/call "+name}, {@code "prompts/get "+name}, bare {@code "resources/read"} (the
1253       * URI stays an attribute, never a span-name suffix), or the exact method name otherwise.
1254       */
1255      private static TraceOperation buildOperation(JsonRpcRequest req) {
1256         var method = req.getMethod();
1257         if (isEmpty(method))
1258            return TraceOperation.DEFAULT;
1259         var meta = McpWire.metaMapOrEmpty(req.getParams());
1260         var attrs = new LinkedHashMap<String,String>();
1261         attrs.put(TraceOperation.ATTR_MCP_METHOD_NAME, method);
1262         var protocolVersion = str(meta.get(RequestMeta.KEY_PROTOCOL_VERSION));
1263         if (! isEmpty(protocolVersion))
1264            attrs.put(TraceOperation.ATTR_MCP_PROTOCOL_VERSION, protocolVersion);
1265         if (nn(req.getId()))
1266            attrs.put(TraceOperation.ATTR_JSONRPC_REQUEST_ID, String.valueOf(req.getId()));
1267
1268         var spanName = method;
1269         switch (method) {
1270            case McpMethods.TOOLS_CALL -> {
1271               var name = McpRoutingNames.routingName(method, req.getParams());
1272               if (! isEmpty(name)) {
1273                  attrs.put(TraceOperation.ATTR_GEN_AI_TOOL_NAME, name);
1274                  spanName = method + " " + name;
1275               }
1276               attrs.put(TraceOperation.ATTR_GEN_AI_OPERATION_NAME, "execute_tool");
1277            }
1278            case McpMethods.PROMPTS_GET -> {
1279               var name = McpRoutingNames.routingName(method, req.getParams());
1280               if (! isEmpty(name)) {
1281                  attrs.put(TraceOperation.ATTR_GEN_AI_PROMPT_NAME, name);
1282                  spanName = method + " " + name;
1283               }
1284            }
1285            case McpMethods.RESOURCES_READ -> {
1286               var uri = McpRoutingNames.routingName(method, req.getParams());
1287               if (! isEmpty(uri))
1288                  attrs.put(TraceOperation.ATTR_MCP_RESOURCE_URI, uri);
1289            }
1290            default -> {
1291               // Exact method name; no method-specific attributes.
1292            }
1293         }
1294         return TraceOperation.of(spanName, attrs);
1295      }
1296   }
1297
1298   /**
1299    * Composite, per-request {@link TraceContextCarrier} giving an explicit {@code params._meta} value
1300    * precedence over the equivalent HTTP header, for any key &mdash; in practice the bare W3C
1301    * {@code traceparent} / {@code tracestate} / {@code baggage} keys, since those are the only names
1302    * both sides share: {@code lookup(key) = params._meta[key] if present, otherwise the HTTP header of
1303    * the same name}.
1304    */
1305   private static final class MetaCarrier implements TraceContextCarrier {
1306      private final Map<String,Object> meta;
1307      private final RestRequest request;
1308
1309      MetaCarrier(Map<String,Object> meta, RestRequest request) {
1310         this.meta = meta;
1311         this.request = request;
1312      }
1313
1314      @Override /* TraceContextCarrier */
1315      public String get(String key) {
1316         var value = meta.get(key);
1317         if (nn(value))
1318            return value.toString();
1319         return request.getHeaderParam(key).orElse(null);
1320      }
1321
1322      @Override /* TraceContextCarrier */
1323      public Iterable<String> keys() {
1324         var result = new LinkedHashSet<String>(meta.keySet());
1325         result.addAll(request.getHeaders().getNames());
1326         return result;
1327      }
1328
1329      @Override /* TraceContextCarrier */
1330      public void set(String key, String value) {
1331         meta.put(key, value);
1332      }
1333   }
1334}