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.v20250618;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022import java.lang.reflect.*;
023import java.util.*;
024import java.util.logging.Level;
025import java.util.logging.Logger;
026
027import org.apache.juneau.bean.jsonrpc.*;
028import org.apache.juneau.bean.mcp.v20250618.*;
029import org.apache.juneau.commons.inject.*;
030import org.apache.juneau.commons.utils.JsonValueSafety;
031import org.apache.juneau.marshall.collections.*;
032import org.apache.juneau.rest.server.mcp.McpCompletionRef;
033import org.apache.juneau.rest.server.mcp.McpCompletionRequest;
034import org.apache.juneau.rest.server.mcp.McpCompletionResult;
035import org.apache.juneau.rest.server.mcp.McpCursor;
036import org.apache.juneau.rest.server.mcp.McpDispatchResult;
037import org.apache.juneau.rest.server.mcp.McpErrorKind;
038import org.apache.juneau.rest.server.mcp.McpExchange;
039import org.apache.juneau.rest.server.mcp.McpParamUtils;
040import org.apache.juneau.rest.server.mcp.McpPromptHandler;
041import org.apache.juneau.rest.server.mcp.McpResourceHandler;
042import org.apache.juneau.rest.server.mcp.McpResourceTemplateHandler;
043import org.apache.juneau.rest.server.mcp.McpResponseResult;
044import org.apache.juneau.rest.server.mcp.McpSchema;
045import org.apache.juneau.rest.server.mcp.McpServerConfig;
046import org.apache.juneau.rest.server.mcp.McpToolHandler;
047import org.apache.juneau.rest.server.mcp.McpToolOutcome;
048
049/**
050 * {@link McpRevision} implementation for MCP revision {@code 2025-06-18}.
051 *
052 * <p>
053 * Owns this revision's JSON-RPC method table and error-code table. Note the error-code table
054 * deliberately reproduces a known-wrong mapping: {@link McpErrorKind#UNKNOWN_METHOD},
055 * {@link McpErrorKind#TOOL_NOT_FOUND} and {@link McpErrorKind#PROMPT_NOT_FOUND} all report
056 * {@code -32601}, which is only actually correct for the first. Preserving that is intentional —
057 * the corrective fix for those two is tracked separately and is not part of this re-layering.
058 * {@link McpErrorKind#RESOURCE_NOT_FOUND} is not part of that known-wrong grouping: it correctly
059 * reports {@code -32002}, the {@code 2025-06-18} spec's dedicated missing-resource error code.
060 *
061 * <p>
062 * <b>Constructed per binding, not shared as a singleton (Correction C8).</b> The bound servlet or
063 * mixin builds a fresh instance on every {@code revision()} call, passing its own
064 * {@code capabilities()} hook result into the constructor — see {@link McpRestServlet} and
065 * {@link McpEndpoint}. That is how this revision learns which explicit capabilities (if any)
066 * to advertise, with no channel back into core: this class is otherwise entirely stateless, so
067 * constructing a new one per call costs nothing.
068 */
069@SuppressWarnings({
070   "java:S2176" // Settled, intentional name shadow against the neutral org.apache.juneau.rest.server.mcp.McpRevision SPI
071                // (evaluated and rejected renaming this to e.g. AbstractMcpRevision): every dated adapter binding
072                // class is deliberately de-versioned to plain "McpRevision" and differentiated from its siblings only by
073                // package, matching the revision-string-free naming already used throughout each vNNNNNNNN module.
074})
075public final class McpRevision implements org.apache.juneau.rest.server.mcp.McpRevision {
076
077   private final ServerCapabilities capabilities;
078
079   /**
080    * Constructor.
081    *
082    * @param capabilities Explicit capabilities to advertise on {@code initialize}, or <jk>null</jk>
083    *    to auto-derive from the registered tool/prompt/resource lists (today's default behavior).
084    */
085   public McpRevision(ServerCapabilities capabilities) {
086      this.capabilities = capabilities;
087   }
088
089   /** JSON-RPC error code: parse error. Never reported by this revision (see {@link McpErrorKind#PARSE_ERROR}). */
090   public static final int CODE_PARSE_ERROR = -32700;
091
092   /** JSON-RPC error code: invalid request. */
093   public static final int CODE_INVALID_REQUEST = -32600;
094
095   /** JSON-RPC error code: method not found. */
096   public static final int CODE_METHOD_NOT_FOUND = -32601;
097
098   /** JSON-RPC error code: invalid params. */
099   public static final int CODE_INVALID_PARAMS = -32602;
100
101   /** JSON-RPC error code: internal error. */
102   public static final int CODE_INTERNAL_ERROR = -32603;
103
104   /** JSON-RPC error code: resource not found (MCP-specific, per the {@code 2025-06-18} spec). */
105   public static final int CODE_RESOURCE_NOT_FOUND = -32002;
106
107   /** Default server name reported by {@code initialize} when the config supplies no server identity. */
108   public static final String DEFAULT_SERVER_NAME = "juneau-rest-server-mcp";
109
110   private static final String PARAM_ARGUMENTS = "arguments";
111
112   private static final String INTERNAL_ERROR_MESSAGE = "Internal error";
113
114   private static final Logger LOG = Logger.getLogger(McpRevision.class.getName());
115
116   private static final Set<String> SUPPORTED_SCHEMA_KEYWORDS =
117      Set.of("type", "properties", "required", "additionalProperties", "items", "$defs");
118
119   private static final Set<McpServerConfig> VALIDATED =
120      Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>()));
121
122   /**
123    * Verifies that every registered tool's input <em>and</em> output schema is expressible in this
124    * revision's wire schema type.
125    *
126    * <p>
127    * The neutral {@link McpSchema} is an unconstrained JSON object carrier, but this revision's
128    * {@code JsonSchema} bean supports exactly six keywords and models only object schemas. Each
129    * schema role is therefore checked twice: its root must declare {@code "type":"object"}, and the
130    * complete graph reachable from that root may use only this revision's six keywords. Rather than
131    * silently dropping an unsupported keyword — or an incompatible root shape — on the wire, a config
132    * carrying one is rejected, naming the tool, the offending role ({@code inputSchema} /
133    * {@code outputSchema}), and the offending shape or keyword.
134    *
135    * <p>
136    * Before walking, each schema is passed through {@link JsonValueSafety} to bound nesting depth,
137    * node count, and cyclic/shared references, so a pathological config cannot stall or exhaust the
138    * walk. The wall-clock deadline is not applied: the schemas are server-authored and the node bound
139    * already limits the work, so a slow walk (a loaded CI host, a GC pause) must not reject a valid
140    * config.
141    *
142    * <p>
143    * Note this cannot be a complete guarantee against every possible wire shape: {@code JsonSchema}
144    * is {@code public} and non-{@code final}, and Juneau's reflection-based marshalling will
145    * serialize a getter added by a subclass. No such subclass exists in this codebase, and none can
146    * be constructed through the public MCP API, but the check covers what a caller can express
147    * through {@link McpSchema}, not what reflection can reach.
148    *
149    * @param config The config to validate. Never {@code null}.
150    * @throws IllegalArgumentException If any tool's input or output schema has a non-object root or uses an unsupported keyword.
151    */
152   public static void validateSchemas(McpServerConfig config) {
153      config.getTools().forEach(handler -> {
154         var spec = handler.descriptor();
155         if (spec != null) {
156            validateSchema(spec.getName(), "inputSchema", spec.getInputSchema());
157            validateSchema(spec.getName(), "outputSchema", spec.getOutputSchema());
158         }
159      });
160   }
161
162   private static void validateSchema(String toolName, String role, McpSchema schema) {
163      if (schema == null)
164         return;
165      var raw = schema.toJsonMap();
166      // No deadline: a server-authored schema must not fail validation because the host is slow.
167      JsonValueSafety.check(raw, "Tool '" + toolName + "' " + role + " for MCP revision 2025-06-18", JsonValueSafety.NO_DEADLINE);
168      if (neq(raw.get("type"), "object"))
169         throw iaex("Tool ''%s'' %s root type ''%s'' is not object; MCP revision 2025-06-18 requires object schemas.",
170            toolName, role, raw.get("type"));
171      checkKeywords(toolName, role, raw);
172   }
173
174   @SuppressWarnings({
175      "java:S3776" // Cognitive complexity acceptable for an explicit-stack JSON-schema tree walk; splitting the per-shape branches would fragment a single cohesive traversal.
176   })
177   private static void checkKeywords(String toolName, String role, Object root) {
178      var seen = Collections.newSetFromMap(new IdentityHashMap<Object,Boolean>());
179      var stack = new ArrayDeque<SchemaValue>();
180      stack.push(new SchemaValue(root));
181      while (! stack.isEmpty()) {
182         var framed = stack.pop();
183         var value = framed.value();
184         if ((value instanceof Map<?,?> || value instanceof Collection<?> || value != null && value.getClass().isArray())
185            && ! seen.add(value))
186            continue;
187         if (value instanceof Map<?,?> value2) {
188            for (var entry : value2.entrySet()) {
189               var keyword = String.valueOf(entry.getKey());
190               if (! SUPPORTED_SCHEMA_KEYWORDS.contains(keyword))
191                  throw iaex("Tool ''%s'' %s declares JSON Schema keyword ''%s'', which MCP revision 2025-06-18 cannot represent.",
192                     toolName, role, keyword);
193               var child = entry.getValue();
194               if ((eqa(keyword, "properties", "$defs")) && child instanceof Map<?,?> child2) {
195                  for (var schema : child2.values())
196                     stack.push(new SchemaValue(schema));
197               } else {
198                  stack.push(new SchemaValue(child));
199               }
200            }
201         } else if (value instanceof Collection<?> value2)
202            value2.forEach(child -> stack.push(new SchemaValue(child)));
203         else if (value != null && value.getClass().isArray())
204            for (var i = 0; i < Array.getLength(value); i++)
205               stack.push(new SchemaValue(Array.get(value, i)));
206      }
207   }
208
209   private record SchemaValue(Object value) {}
210
211   @Override /* McpRevision */
212   public String protocolVersion() {
213      return McpProtocol.VERSION_2025_06_18;
214   }
215
216   @Override /* McpRevision */
217   public int errorCode(McpErrorKind kind) {
218      return switch (kind) {
219         case INVALID_REQUEST -> CODE_INVALID_REQUEST;
220         case UNKNOWN_METHOD, TOOL_NOT_FOUND, PROMPT_NOT_FOUND -> CODE_METHOD_NOT_FOUND;
221         case RESOURCE_NOT_FOUND -> CODE_RESOURCE_NOT_FOUND;
222         case INVALID_PARAMS -> CODE_INVALID_PARAMS;
223         case INTERNAL_ERROR -> CODE_INTERNAL_ERROR;
224         case PARSE_ERROR -> CODE_PARSE_ERROR;
225      };
226   }
227
228   @Override /* McpRevision */
229   public McpDispatchResult dispatch(McpExchange exchange, McpServerConfig config, BeanStore ctx) {
230      var response = dispatchResponse(exchange, config, ctx);
231      return response == null ? null : new McpResponseResult(response);
232   }
233
234   /**
235    * Does the actual dispatch work. This revision never streams, so every non-notification outcome is a
236    * single {@link JsonRpcResponse}; {@link #dispatch} wraps it in a {@link McpResponseResult}.
237    */
238   private JsonRpcResponse dispatchResponse(McpExchange exchange, McpServerConfig config, BeanStore ctx) {
239      reqnn("exchange", exchange);
240      reqnn("config", config);
241      reqnn("ctx", ctx);
242
243      if (! VALIDATED.contains(config)) {
244         validateSchemas(config);
245         VALIDATED.add(config); // Only after success, so a bad config keeps failing on every request.
246      }
247
248      var req = exchange.request();
249      if (req == null)
250         return JsonRpcResponse.errorResponse(null, errorCode(McpErrorKind.INVALID_REQUEST), "Request envelope is null");
251
252      var id = req.getId();
253      var method = req.getMethod();
254
255      if (isEmpty(method))
256         return JsonRpcResponse.notification(id) ? null
257            : JsonRpcResponse.errorResponse(id, errorCode(McpErrorKind.INVALID_REQUEST), "Missing method");
258
259      try {
260         var result = invoke(method, req.getParams(), config, ctx);
261         return JsonRpcResponse.notification(id) ? null : JsonRpcResponse.ok(id, result);
262      } catch (McpException e) {
263         return JsonRpcResponse.notification(id) ? null : new JsonRpcResponse()
264            .setJsonrpc(McpProtocol.JSON_RPC_2_0)
265            .setId(id)
266            .setError(e.toJsonRpcError());
267      } catch (Exception e) {
268         if (JsonRpcResponse.notification(id))
269            return null;
270         LOG.log(Level.WARNING, e, () -> "MCP request failed with an internal error.");
271         return JsonRpcResponse.errorResponse(id, errorCode(McpErrorKind.INTERNAL_ERROR), INTERNAL_ERROR_MESSAGE);
272      }
273   }
274
275   private Object invoke(String method, Object params, McpServerConfig config, BeanStore ctx) {
276      switch (method) {
277         case McpMethods.INITIALIZE:
278            return initialize(config);
279         case McpMethods.PING:
280            return new JsonMap();
281         case McpMethods.TOOLS_LIST:
282            return listTools(config, params, ctx);
283         case McpMethods.TOOLS_CALL:
284            return callTool(config, params, ctx);
285         case McpMethods.PROMPTS_LIST:
286            return listPrompts(config, params, ctx);
287         case McpMethods.PROMPTS_GET:
288            return getPrompt(config, params, ctx);
289         case McpMethods.RESOURCES_LIST:
290            return listResources(config, params, ctx);
291         case McpMethods.RESOURCES_READ:
292            return readResource(config, params, ctx);
293         case McpMethods.RESOURCES_TEMPLATES_LIST:
294            return listResourceTemplates(config, params, ctx);
295         case McpMethods.COMPLETION_COMPLETE:
296            return complete(config, params, ctx);
297         default:
298            throw new McpException(errorCode(McpErrorKind.UNKNOWN_METHOD), "Method not found: " + method);
299      }
300   }
301
302   private InitializeResult initialize(McpServerConfig config) {
303      var caps = this.capabilities;
304      if (caps == null) {
305         caps = new ServerCapabilities();
306         if (! config.getTools().isEmpty())
307            caps.setTools(new ToolCapability());
308         if (! config.getPrompts().isEmpty())
309            caps.setPrompts(new PromptCapability());
310         if (! config.getResources().isEmpty() || ! config.getResourceTemplates().isEmpty())
311            caps.setResources(new ResourceCapability());
312         if (config.hasAnyCompleter())
313            caps.setCompletions(new CompletionCapability());
314      }
315      return new InitializeResult()
316         .setProtocolVersion(protocolVersion())
317         .setCapabilities(caps)
318         .setServerInfo(McpWire.serverInfo(config))
319         .setInstructions(config.getInstructions());
320   }
321
322   private static ListToolsResult listTools(McpServerConfig config, Object params, BeanStore ctx) {
323      var descriptors = config.getTools().stream().map(McpToolHandler::descriptor).toList();
324      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
325      return new ListToolsResult()
326         .setTools(page.items().stream().map(McpWire::toWire).toList())
327         .setNextCursor(page.nextCursor());
328   }
329
330   private CallToolResult callTool(McpServerConfig config, Object params, BeanStore ctx) {
331      var p = McpParamUtils.asMap(params);
332      var name = McpParamUtils.strParam(p, "name");
333      if (name == null)
334         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing tool name");
335      var handler = config.getTools().stream()
336         .filter(h -> name.equals(h.descriptor().getName()))
337         .findFirst()
338         .orElseThrow(() -> new McpException(errorCode(McpErrorKind.TOOL_NOT_FOUND), "Tool not found: " + name));
339      var args = McpParamUtils.mapParam(p, PARAM_ARGUMENTS);
340      McpSchemaSafety.validateInput(handler.descriptor().getInputSchema(), args);
341      var outcome = handler.call(args, ctx);
342      validateStructuredOutput(outcome);
343      return McpWire.toWire(outcome);
344   }
345
346   private static void validateStructuredOutput(McpToolOutcome outcome) {
347      if (outcome == null || outcome.getStructuredContent() == null)
348         return;
349      if (! (outcome.getStructuredContent() instanceof Map<?,?>))
350         throw new McpException(CODE_INTERNAL_ERROR,
351            "Tool structuredContent must be a JSON object for MCP revision 2025-06-18");
352      try {
353         // No deadline: the node bound caps the walk, and a slow host must not fail a valid result.
354         JsonValueSafety.check(outcome.getStructuredContent(), "Tool structuredContent", JsonValueSafety.NO_DEADLINE);
355      } catch (IllegalArgumentException e) {
356         throw new McpException(CODE_INTERNAL_ERROR, e.getMessage());
357      }
358   }
359
360   private static ListPromptsResult listPrompts(McpServerConfig config, Object params, BeanStore ctx) {
361      var descriptors = config.getPrompts().stream().map(McpPromptHandler::descriptor).toList();
362      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
363      return new ListPromptsResult()
364         .setPrompts(page.items().stream().map(McpWire::toWire).toList())
365         .setNextCursor(page.nextCursor());
366   }
367
368   private GetPromptResult getPrompt(McpServerConfig config, Object params, BeanStore ctx) {
369      var p = McpParamUtils.asMap(params);
370      var name = McpParamUtils.strParam(p, "name");
371      if (name == null)
372         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing prompt name");
373      var handler = config.getPrompts().stream()
374         .filter(h -> name.equals(h.descriptor().getName()))
375         .findFirst()
376         .orElseThrow(() -> new McpException(errorCode(McpErrorKind.PROMPT_NOT_FOUND), "Prompt not found: " + name));
377      var args = McpParamUtils.mapParam(p, PARAM_ARGUMENTS);
378      return McpWire.toWire(handler.get(args, ctx));
379   }
380
381   private static ListResourcesResult listResources(McpServerConfig config, Object params, BeanStore ctx) {
382      var descriptors = config.getResources().stream().map(McpResourceHandler::descriptor).toList();
383      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
384      return new ListResourcesResult()
385         .setResources(page.items().stream().map(McpWire::toWire).toList())
386         .setNextCursor(page.nextCursor());
387   }
388
389   private ReadResourceResult readResource(McpServerConfig config, Object params, BeanStore ctx) {
390      var p = McpParamUtils.asMap(params);
391      var uri = McpParamUtils.strParam(p, "uri");
392      if (uri == null)
393         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing resource uri");
394      var exact = config.getResources().stream()
395         .filter(h -> uri.equals(h.descriptor().getUri()))
396         .findFirst();
397      if (exact.isPresent())
398         return McpWire.toWire(exact.get().read(uri, ctx));
399      var match = config.resolveResourceTemplate(uri);
400      var outcome = match == null ? null : match.handler().read(uri, match.variables(), ctx);
401      if (outcome == null)
402         throw new McpException(errorCode(McpErrorKind.RESOURCE_NOT_FOUND), "Resource not found: " + uri);
403      return McpWire.toWire(outcome);
404   }
405
406   private static ListResourceTemplatesResult listResourceTemplates(McpServerConfig config, Object params, BeanStore ctx) {
407      var descriptors = config.getResourceTemplates().stream().map(McpResourceTemplateHandler::descriptor).toList();
408      var page = config.getCursor().page(descriptors, McpCursor.cursorOf(params), ctx);
409      return new ListResourceTemplatesResult()
410         .setResourceTemplates(page.items().stream().map(McpWire::toWire).toList())
411         .setNextCursor(page.nextCursor());
412   }
413
414   private CompleteResult complete(McpServerConfig config, Object params, BeanStore ctx) {
415      var p = McpParamUtils.asMap(params);
416      var ref = completionRef(McpParamUtils.mapParam(p, "ref"));
417      var argument = McpParamUtils.mapParam(p, "argument");
418      var argumentName = McpParamUtils.strParam(argument, "name");
419      if (isEmpty(argumentName))
420         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing argument.name");
421      var value = McpParamUtils.strictStrParam(argument, "value");
422      if (value == null)
423         throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing or non-string argument.value");
424      var contextArguments = McpParamUtils.strictStrMapParam(McpParamUtils.mapParam(p, "context"), PARAM_ARGUMENTS);
425
426      var completer = config.completer(ref, argumentName);
427      McpCompletionResult raw;
428      if (completer == null) {
429         raw = McpCompletionResult.empty();
430      } else {
431         var request = new McpCompletionRequest()
432            .setRef(ref)
433            .setArgumentName(argumentName)
434            .setValue(value)
435            .setContextArguments(contextArguments);
436         raw = completer.complete(request, ctx);
437      }
438      return McpWire.toWire(McpCompletionResult.normalize(raw));
439   }
440
441   private McpCompletionRef completionRef(Map<String,Object> refMap) {
442      var type = McpParamUtils.strParam(refMap, "type");
443      if (eq(type, "ref/prompt")) {
444         var name = McpParamUtils.strParam(refMap, "name");
445         if (isEmpty(name))
446            throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing ref.name for ref/prompt");
447         return McpCompletionRef.prompt(name);
448      }
449      if (eq(type, "ref/resource")) {
450         var uri = McpParamUtils.strParam(refMap, "uri");
451         if (isEmpty(uri))
452            throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Missing ref.uri for ref/resource");
453         return McpCompletionRef.resource(uri);
454      }
455      throw new McpException(errorCode(McpErrorKind.INVALID_PARAMS), "Invalid or missing ref.type: " + type);
456   }
457}