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; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.util.*; 022 023import org.apache.juneau.commons.inject.*; 024import org.apache.juneau.rest.server.auth.TokenValidator; 025 026/** 027 * Aggregate configuration consumed by the bound {@link McpRevision}. 028 * 029 * <p> 030 * Applications register a single {@link McpServerConfig} (typically as a bean in their {@code RestContext} 031 * bean store) listing the tools, prompts, resources, and resource templates to expose, plus optional server 032 * metadata and a pagination strategy. 033 * 034 * <p> 035 * This type is revision-neutral: it holds no field typed with any protocol revision's wire beans, and 036 * in particular holds no capabilities field in any form. The protocol version is owned by 037 * {@link McpRevision#protocolVersion()}, and an explicit capabilities advertisement is owned by a 038 * revision-specific hook on that revision's servlet or endpoint mixin. 039 */ 040@SuppressWarnings({ 041 "java:S135", // Handler-validation and completer-lookup loops (validatePrompts, validateResourceTemplates, resolveResourceTemplate, completer*) use independent continue guard clauses 042 "java:S3077", // The volatile fields hold immutable List/Map snapshots that are replaced wholesale when resource templates are published, so volatile only publishes a fully-built reference 043 "java:S3776" // validateResourceTemplates(), resolveResourceTemplate() and the completer lookups each match handlers against several URI/argument rules in one pass 044}) 045public class McpServerConfig { 046 047 private String name; 048 private String version; 049 private String instructions; 050 private List<McpToolHandler> tools = l(); 051 private List<McpPromptHandler> prompts = l(); 052 private List<McpResourceHandler> resources = l(); 053 private List<McpResourceTemplateHandler> resourceTemplates = l(); 054 055 private volatile List<McpResourceTemplateHandler> validatedResourceTemplatesSnapshot = List.of(); 056 private volatile Map<McpResourceTemplateHandler, McpUriTemplateMatcher> compiledResourceTemplateMatchers = Map.of(); 057 private McpCursor cursor = McpCursor.SINGLE_PAGE; 058 private TokenValidator tokenValidator; 059 private boolean allowUnauthenticated; 060 061 /** 062 * Server name reported in {@code initialize}. 063 * 064 * <p> 065 * When both this and {@link #getVersion()} are {@code null}, the bound revision substitutes its 066 * own default server identity. 067 * 068 * @return The name, or {@code null} if not set. 069 */ 070 public String getName() { 071 return name; 072 } 073 074 /** 075 * Sets the server name. 076 * 077 * @param value The new value. Can be <jk>null</jk> to unset the property. 078 * @return This object. 079 */ 080 public McpServerConfig setName(String value) { 081 name = value; 082 return this; 083 } 084 085 /** 086 * Server version reported in {@code initialize}. 087 * 088 * @return The version, or {@code null} if not set. 089 */ 090 public String getVersion() { 091 return version; 092 } 093 094 /** 095 * Sets the server version. 096 * 097 * @param value The new value. Can be <jk>null</jk> to unset the property. 098 * @return This object. 099 */ 100 public McpServerConfig setVersion(String value) { 101 version = value; 102 return this; 103 } 104 105 /** 106 * Optional instructions surfaced via {@code initialize}. 107 * 108 * @return The instructions, or {@code null} if not set. 109 */ 110 public String getInstructions() { 111 return instructions; 112 } 113 114 /** 115 * Sets initialize instructions. 116 * 117 * @param instructions The new value. 118 * @return This object (for method chaining). 119 */ 120 public McpServerConfig setInstructions(String instructions) { 121 this.instructions = instructions; 122 return this; 123 } 124 125 /** 126 * Registered tool handlers. 127 * 128 * @return Mutable list of handlers. Never {@code null}. 129 */ 130 public List<McpToolHandler> getTools() { 131 return tools; 132 } 133 134 /** 135 * Sets the tool handler list. 136 * 137 * @param tools The new value (or {@code null} to clear). 138 * @return This object (for method chaining). 139 */ 140 public McpServerConfig setTools(List<McpToolHandler> tools) { 141 this.tools = tools == null ? l() : new ArrayList<>(tools); 142 return this; 143 } 144 145 /** 146 * Convenience: append one or more tool handlers. 147 * 148 * @param handlers Handlers to add. 149 * @return This object (for method chaining). 150 */ 151 public McpServerConfig addTool(McpToolHandler... handlers) { 152 Collections.addAll(this.tools, handlers); 153 return this; 154 } 155 156 /** 157 * Convenience: adapt and append a single typed tool handler. 158 * 159 * <p> 160 * The handler is bridged into a raw {@link McpToolHandler} via 161 * {@link McpTypedHandlers#adaptTool(McpTypedToolHandler)} before it is stored. This overload is intentionally 162 * singular: a typed varargs overload would make {@code addTool()} ambiguous. To register multiple typed 163 * handlers, use chained {@code addTool(...)} calls, or adapt them explicitly with 164 * {@link McpTypedHandlers#adaptTool(McpTypedToolHandler)} and pass the results to 165 * {@link #addTool(McpToolHandler...)}. 166 * 167 * @param handler The typed handler to adapt and add. 168 * @return This object (for method chaining). 169 */ 170 public McpServerConfig addTool(McpTypedToolHandler<?,?> handler) { 171 tools.add(McpTypedHandlers.adaptTool(handler)); 172 return this; 173 } 174 175 /** 176 * Registered prompt handlers. 177 * 178 * @return Mutable list of handlers. Never {@code null}. 179 */ 180 public List<McpPromptHandler> getPrompts() { 181 return prompts; 182 } 183 184 /** 185 * Sets the prompt handler list. 186 * 187 * <p> 188 * The complete resulting registry is validated before publication; on failure, the previously published 189 * registry is left unchanged. See {@link #addPrompt(McpPromptHandler...)} for the validated conditions. 190 * 191 * @param prompts The new value (or {@code null} to clear). 192 * @return This object (for method chaining). 193 * @throws IllegalArgumentException If the resulting registry would be invalid. 194 */ 195 public McpServerConfig setPrompts(List<McpPromptHandler> prompts) { 196 var candidate = prompts == null ? new ArrayList<McpPromptHandler>() : new ArrayList<>(prompts); 197 validatePrompts(candidate); 198 this.prompts = candidate; 199 return this; 200 } 201 202 /** 203 * Convenience: append one or more prompt handlers. 204 * 205 * <p> 206 * The complete resulting registry - the handlers already registered plus {@code handlers} - is validated 207 * before publication; on failure, the previously published registry is left unchanged. Fails fast with 208 * {@link IllegalArgumentException} for a single prompt whose declared {@link McpPromptArgument} list either: 209 * <ul> 210 * <li>repeats a non-{@code null} argument name; or 211 * <li>attaches a non-{@code null} {@link McpPromptArgument#getCompleter() completer} to a {@code null} or 212 * blank argument name. 213 * </ul> 214 * 215 * @param handlers Handlers to add. 216 * @return This object (for method chaining). 217 * @throws IllegalArgumentException If the resulting registry would be invalid. 218 */ 219 public McpServerConfig addPrompt(McpPromptHandler... handlers) { 220 var candidate = new ArrayList<>(this.prompts); 221 Collections.addAll(candidate, handlers); 222 validatePrompts(candidate); 223 this.prompts = candidate; 224 return this; 225 } 226 227 /** 228 * Validates one candidate prompt registry in full, throwing {@link IllegalArgumentException} on the first 229 * invalid entry, so a misconfigured prompt argument is caught at registration time rather than during 230 * {@code completion/complete} dispatch. See {@link #addPrompt(McpPromptHandler...)} for the validated 231 * conditions. 232 * 233 * <p> 234 * A {@code null} handler, a handler whose {@link McpPromptHandler#descriptor()} returns {@code null}, or a 235 * descriptor with {@code null} {@link McpPromptSpec#getArguments() arguments} carries nothing to validate 236 * here and is silently skipped; those are not this validation's concern. 237 */ 238 private static void validatePrompts(List<McpPromptHandler> candidate) { 239 for (var i = 0; i < candidate.size(); i++) { 240 var handler = candidate.get(i); 241 if (handler == null) 242 continue; 243 var descriptor = handler.descriptor(); 244 if (descriptor == null) 245 continue; 246 var arguments = descriptor.getArguments(); 247 if (arguments == null) 248 continue; 249 var seenNames = new HashSet<String>(); 250 for (var j = 0; j < arguments.size(); j++) { 251 var argument = arguments.get(j); 252 if (argument == null) 253 continue; 254 var name = argument.getName(); 255 if (argument.getCompleter() != null && ib(name)) 256 throw iaex( 257 "Invalid prompt registration at index %s (prompt '%s'), argument index %s: a completer must not be attached to a null or blank argument name", 258 i, descriptor.getName(), j); 259 if (name != null && ! seenNames.add(name)) 260 throw iaex("Invalid prompt registration at index %s (prompt '%s'): duplicate argument name '%s'", 261 i, descriptor.getName(), name); 262 } 263 } 264 } 265 266 /** 267 * Registered resource handlers. 268 * 269 * @return Mutable list of handlers. Never {@code null}. 270 */ 271 public List<McpResourceHandler> getResources() { 272 return resources; 273 } 274 275 /** 276 * Sets the resource handler list. 277 * 278 * @param resources The new value (or {@code null} to clear). 279 * @return This object (for method chaining). 280 */ 281 public McpServerConfig setResources(List<McpResourceHandler> resources) { 282 this.resources = resources == null ? l() : new ArrayList<>(resources); 283 return this; 284 } 285 286 /** 287 * Convenience: append one or more resource handlers. 288 * 289 * @param handlers Handlers to add. 290 * @return This object (for method chaining). 291 */ 292 public McpServerConfig addResource(McpResourceHandler... handlers) { 293 Collections.addAll(this.resources, handlers); 294 return this; 295 } 296 297 /** 298 * Registered resource-template handlers. 299 * 300 * <p> 301 * Every read of this property (re)validates the current registry if the list has been mutated directly 302 * since the last validated {@link #setResourceTemplates(List)}, {@link #addResourceTemplate(McpResourceTemplateHandler...)}, 303 * {@link #addResourceTemplate(McpResourceTemplateSpec...)}, or {@link #setResourceTemplateSpecs(List)} call, 304 * so direct-list corruption is caught on first consumption rather than silently propagating to dispatch. 305 * A registry that has not been mutated since its last successful validation is returned without 306 * recompiling its templates. 307 * 308 * @return Mutable list of handlers. Never {@code null}. 309 * @throws IllegalArgumentException If the list was mutated directly into an invalid state (see 310 * {@link #addResourceTemplate(McpResourceTemplateHandler...)} for the validated conditions). 311 */ 312 public List<McpResourceTemplateHandler> getResourceTemplates() { 313 ensureResourceTemplatesValid(); 314 return resourceTemplates; 315 } 316 317 /** 318 * Sets the resource-template handler list. 319 * 320 * <p> 321 * The complete resulting registry is validated before publication; on failure, the previously published 322 * registry is left unchanged. See {@link #addResourceTemplate(McpResourceTemplateHandler...)} for the 323 * validated conditions. 324 * 325 * @param value The new value (or {@code null} to clear). 326 * @return This object (for method chaining). 327 * @throws IllegalArgumentException If the resulting registry would be invalid. 328 */ 329 public McpServerConfig setResourceTemplates(List<McpResourceTemplateHandler> value) { 330 var candidate = value == null ? new ArrayList<McpResourceTemplateHandler>() : new ArrayList<>(value); 331 publishResourceTemplates(candidate); 332 return this; 333 } 334 335 /** 336 * Sets the resource-template registry from bare descriptors, replacing each with a built-in listing-only 337 * handler equivalent to what {@link #addResourceTemplate(McpResourceTemplateSpec...)} wraps. 338 * 339 * <p> 340 * The complete resulting registry is validated before publication; on failure, the previously published 341 * registry is left unchanged. 342 * 343 * @param value The new descriptor list (or {@code null} to clear). 344 * @return This object (for method chaining). 345 * @throws IllegalArgumentException If the resulting registry would be invalid. 346 */ 347 public McpServerConfig setResourceTemplateSpecs(List<McpResourceTemplateSpec> value) { 348 return setResourceTemplates(value == null ? null : value.stream().map(McpServerConfig::listingOnlyTemplate).toList()); 349 } 350 351 /** 352 * Convenience: append one or more resource-template handlers. 353 * 354 * <p> 355 * The complete resulting registry - the handlers already registered plus {@code values} - is validated 356 * before publication; on failure, the previously published registry is left unchanged. Fails fast with 357 * {@link IllegalArgumentException} naming the offending registration index and template for: 358 * <ul> 359 * <li>a {@code null} handler; 360 * <li>a handler whose {@link McpResourceTemplateHandler#descriptor()} returns {@code null}; 361 * <li>a descriptor with a {@code null} or blank {@code uriTemplate}; 362 * <li>a malformed {@code uriTemplate} (delegated to {@link McpUriTemplateMatcher#compile(String)}); and 363 * <li>an exact-duplicate {@code uriTemplate} string within the resulting registry. 364 * </ul> 365 * A syntactically valid {@code uriTemplate} outside {@link McpUriTemplateMatcher}'s reverse-matchable 366 * subset is a legal registration, not an error. 367 * 368 * @param values Handlers to add. 369 * @return This object (for method chaining). 370 * @throws IllegalArgumentException If the resulting registry would be invalid. 371 */ 372 public McpServerConfig addResourceTemplate(McpResourceTemplateHandler... values) { 373 var candidate = new ArrayList<>(resourceTemplates); 374 Collections.addAll(candidate, values); 375 publishResourceTemplates(candidate); 376 return this; 377 } 378 379 /** 380 * Convenience: append one or more resource-template descriptors as built-in listing-only handlers. 381 * 382 * <p> 383 * Each descriptor is wrapped in a handler whose {@link McpResourceTemplateHandler#descriptor()} returns 384 * that same descriptor instance, whose {@link McpResourceTemplateHandler#read(String, Map, BeanStore) read} 385 * always returns {@code null}, and whose {@link McpResourceTemplateHandler#completer(String) completer} 386 * always returns {@code null}. The resulting registry is validated exactly as in 387 * {@link #addResourceTemplate(McpResourceTemplateHandler...)}. 388 * 389 * @param values Descriptors to add. 390 * @return This object (for method chaining). 391 * @throws IllegalArgumentException If the resulting registry would be invalid. 392 */ 393 public McpServerConfig addResourceTemplate(McpResourceTemplateSpec... values) { 394 var wrapped = new McpResourceTemplateHandler[values.length]; 395 for (var i = 0; i < values.length; i++) 396 wrapped[i] = listingOnlyTemplate(values[i]); 397 return addResourceTemplate(wrapped); 398 } 399 400 private static McpResourceTemplateHandler listingOnlyTemplate(McpResourceTemplateSpec spec) { 401 return new McpResourceTemplateHandler() { 402 @Override public McpResourceTemplateSpec descriptor() { return spec; } 403 @Override public McpResourceOutcome read(String uri, Map<String,String> variables, BeanStore ctx) { return null; } 404 }; 405 } 406 407 /** 408 * Validates {@code candidate} and, on success, publishes it as the current registry and its already-valid 409 * snapshot (so the very next {@link #getResourceTemplates()} call does not repeat the validation just 410 * performed here). On failure the previously published registry is left untouched. 411 */ 412 private void publishResourceTemplates(List<McpResourceTemplateHandler> candidate) { 413 var compiled = validateResourceTemplates(candidate); 414 resourceTemplates = candidate; 415 validatedResourceTemplatesSnapshot = List.copyOf(candidate); 416 compiledResourceTemplateMatchers = compiled; 417 } 418 419 /** 420 * Revalidates the live {@link #resourceTemplates} list if it differs from the last validated snapshot, 421 * catching mutation performed directly through the mutable list returned by {@link #getResourceTemplates()}. 422 * A registry that is unchanged since its last successful validation is left alone: templates are not 423 * recompiled on every call. 424 */ 425 private void ensureResourceTemplatesValid() { 426 var current = resourceTemplates; 427 if (validatedResourceTemplatesSnapshot.equals(current)) 428 return; 429 var compiled = validateResourceTemplates(current); 430 validatedResourceTemplatesSnapshot = List.copyOf(current); 431 compiledResourceTemplateMatchers = compiled; 432 } 433 434 /** 435 * Validates one candidate resource-template registry in full, throwing {@link IllegalArgumentException} 436 * on the first invalid entry. See {@link #addResourceTemplate(McpResourceTemplateHandler...)} for the 437 * validated conditions. 438 * 439 * <p> 440 * As a side benefit of validation already compiling every entry's {@link McpUriTemplateMatcher} once, 441 * this returns an identity-keyed map from each validated handler to its compiled matcher, so callers can 442 * publish it as {@link #compiledResourceTemplateMatchers} and reuse the compiled matcher on the 443 * per-request paths ({@link #resolveResourceTemplate(String)}, {@link #hasAnyCompleter()}, 444 * {@link #templateCompleter(String, String)}) instead of recompiling from the {@code uriTemplate} string 445 * on every call. 446 */ 447 private static Map<McpResourceTemplateHandler, McpUriTemplateMatcher> validateResourceTemplates(List<McpResourceTemplateHandler> candidate) { 448 var seenTemplates = new HashSet<String>(); 449 var compiled = new IdentityHashMap<McpResourceTemplateHandler, McpUriTemplateMatcher>(); 450 for (var i = 0; i < candidate.size(); i++) { 451 var handler = candidate.get(i); 452 if (handler == null) 453 throw iaex("Invalid resource-template registration at index %s: handler must not be null", i); 454 var descriptor = handler.descriptor(); 455 if (descriptor == null) 456 throw iaex("Invalid resource-template registration at index %s: descriptor() must not return null", i); 457 var uriTemplate = descriptor.getUriTemplate(); 458 if (ib(uriTemplate)) 459 throw iaex("Invalid resource-template registration at index %s (template '%s'): uriTemplate must not be null or blank", 460 i, uriTemplate); 461 McpUriTemplateMatcher matcher; 462 try { 463 matcher = McpUriTemplateMatcher.compile(uriTemplate); 464 } catch (IllegalArgumentException e) { 465 throw iaex(e, "Invalid resource-template registration at index %s (template '%s'): %s", i, uriTemplate, e.getMessage()); 466 } 467 if (! seenTemplates.add(uriTemplate)) 468 throw iaex("Invalid resource-template registration at index %s (template '%s'): duplicate uriTemplate", i, uriTemplate); 469 compiled.put(handler, matcher); 470 } 471 return Collections.unmodifiableMap(compiled); 472 } 473 474 /** 475 * Resolves the completer for one declared variable of a registered resource-template handler, enforcing 476 * in one neutral place - rather than in each dated adapter - that an undeclared variable name never 477 * receives a completer even if the handler itself misbehaves and returns one. 478 * 479 * @param handler The resource-template handler. Must not be {@code null}, and its 480 * {@link McpResourceTemplateHandler#descriptor()}.{@code uriTemplate} must be well-formed (as enforced by 481 * registration validation). 482 * @param variableName The variable name from a {@code completion/complete} request. 483 * @return The handler's completer for that variable, or {@code null} if the variable is not declared by 484 * the template or the handler supplies no completer for it. 485 */ 486 static McpCompleter resourceTemplateCompleter(McpResourceTemplateHandler handler, String variableName) { 487 return resourceTemplateCompleter(handler, variableName, McpUriTemplateMatcher.compile(handler.descriptor().getUriTemplate())); 488 } 489 490 /** 491 * Same contract as {@link #resourceTemplateCompleter(McpResourceTemplateHandler, String)}, but takes an 492 * already-compiled {@code matcher} (typically the one cached in {@link #compiledResourceTemplateMatchers} 493 * for a registered handler) instead of recompiling the template from its {@code uriTemplate} string. 494 */ 495 static McpCompleter resourceTemplateCompleter(McpResourceTemplateHandler handler, String variableName, McpUriTemplateMatcher matcher) { 496 var declared = matcher.variableNames(); 497 return declared.contains(variableName) ? handler.completer(variableName) : null; 498 } 499 500 /** 501 * Resolves the concrete {@code resources/read} request URI {@code uri} against the registered 502 * resource-template registry, selecting the single winning template handler using the deterministic 503 * specificity ranking shared identically by both dated adapters. 504 * 505 * <p> 506 * A candidate is every reverse-matchable ({@link McpUriTemplateMatcher#isReverseMatchable()}) template 507 * handler whose {@link McpUriTemplateMatcher#match(String)} succeeds against {@code uri}; a 508 * non-reverse-matchable or non-matching template handler is never a candidate. Successful candidates are 509 * ranked, highest priority first, by exactly: 510 * <ol> 511 * <li>greater {@link McpUriTemplateMatcher#literalOctetCount() literalOctetCount}; 512 * <li>then fewer {@link McpUriTemplateMatcher#variableCount() variableCount}; and 513 * <li>then earlier registration index (candidates are scanned in registration order and a later 514 * candidate only displaces the current winner on a strictly better key, so the first-registered 515 * candidate wins a complete tie). 516 * </ol> 517 * No other tie-breaker - operator type, capture width, descriptor name/title, or match-time value 518 * length - is consulted. 519 * 520 * <p> 521 * This method does not consult exact {@link McpResourceHandler} registrations. Exact lookup is 522 * unconditionally higher precedence than any template match; callers must perform exact lookup first 523 * and invoke this method only on an exact miss. 524 * 525 * @param uri The concrete request URI. Can be {@code null}, in which case this method returns 526 * {@code null}. 527 * @return The winning match (handler plus its immutable, insertion-ordered decoded variable map), or 528 * {@code null} if no registered reverse-matchable template matches {@code uri}. 529 */ 530 public ResourceTemplateMatch resolveResourceTemplate(String uri) { 531 if (uri == null) 532 return null; 533 McpResourceTemplateHandler winner = null; 534 Map<String,String> winnerVariables = null; 535 McpUriTemplateMatcher winnerMatcher = null; 536 var templates = getResourceTemplates(); 537 var matchers = compiledResourceTemplateMatchers; 538 for (var handler : templates) { 539 if (handler == null) 540 continue; 541 var descriptor = handler.descriptor(); 542 if (descriptor == null) 543 continue; 544 var matcher = matchers.get(handler); 545 if (matcher == null) 546 matcher = McpUriTemplateMatcher.compile(descriptor.getUriTemplate()); 547 if (! matcher.isReverseMatchable()) 548 continue; 549 var variables = matcher.match(uri); 550 if (variables == null) 551 continue; 552 if (winner == null 553 || matcher.literalOctetCount() > winnerMatcher.literalOctetCount() 554 || (matcher.literalOctetCount() == winnerMatcher.literalOctetCount() 555 && matcher.variableCount() < winnerMatcher.variableCount())) { 556 winner = handler; 557 winnerVariables = variables; 558 winnerMatcher = matcher; 559 } 560 } 561 return winner == null ? null : new ResourceTemplateMatch(winner, winnerVariables); 562 } 563 564 /** 565 * The result of {@link #resolveResourceTemplate(String)}: the winning resource-template handler paired 566 * with the variables decoded from the concrete request URI. 567 * 568 * @param handler The winning handler. Never {@code null}. 569 * @param variables The immutable, insertion-ordered map of the handler's declared variables to their 570 * decoded values, captured from the request URI. Never {@code null}. 571 */ 572 public record ResourceTemplateMatch(McpResourceTemplateHandler handler, Map<String,String> variables) {} 573 574 /** 575 * Resolves the completer registered for one declared argument of a registered prompt, by exact prompt name 576 * and exact argument name. 577 * 578 * <p> 579 * This is one half of the neutral cross-target completion lookup shared identically by both dated 580 * adapters; see {@link #templateCompleter(String, String)} for the resource-template half and 581 * {@link #completer(McpCompletionRef, String)} for the unified entry point. 582 * 583 * @param promptName The exact prompt name to look up. Can be {@code null}, in which case this method 584 * returns {@code null}. 585 * @param argumentName The exact argument name to look up. Can be {@code null}, in which case this method 586 * returns {@code null}. 587 * @return The argument's completer, or {@code null} if the prompt is unknown, the argument is undeclared, 588 * or the argument declares no completer. Never invokes the completer. 589 */ 590 public McpCompleter promptCompleter(String promptName, String argumentName) { 591 if (promptName == null || argumentName == null) 592 return null; 593 for (var handler : getPrompts()) { 594 if (handler == null) 595 continue; 596 var descriptor = handler.descriptor(); 597 if (descriptor == null || neq(promptName, descriptor.getName())) 598 continue; 599 var arguments = descriptor.getArguments(); 600 return arguments == null ? null : completerForArgument(arguments, argumentName); 601 } 602 return null; 603 } 604 605 /** 606 * Scans one prompt's declared arguments for the exact-named argument's completer, extracted from 607 * {@link #promptCompleter(String, String)} to keep that method's cognitive complexity within the 608 * project's guard-clause-density threshold. 609 */ 610 private static McpCompleter completerForArgument(List<McpPromptArgument> arguments, String argumentName) { 611 for (var argument : arguments) 612 if (argument != null && eq(argumentName, argument.getName())) 613 return argument.getCompleter(); 614 return null; 615 } 616 617 /** 618 * Resolves the completer registered for one declared variable of a registered resource-template, by exact 619 * registered {@code uriTemplate} string and exact variable name. 620 * 621 * <p> 622 * Matching is against the exact registered template string, not a reverse-match against a concrete URI: a 623 * {@code completion/complete} reference names the declaration being completed, never a concrete/expanded 624 * URI. This is one half of the neutral cross-target completion lookup shared identically by both dated 625 * adapters; see {@link #promptCompleter(String, String)} for the prompt half and 626 * {@link #completer(McpCompletionRef, String)} for the unified entry point. Delegates the "variable must be 627 * declared by the template" check to {@link #resourceTemplateCompleter(McpResourceTemplateHandler, String)} 628 * rather than re-parsing. 629 * 630 * @param uriTemplate The exact registered {@code uriTemplate} to look up. Can be {@code null}, in which 631 * case this method returns {@code null}. 632 * @param variableName The exact variable name to look up. Can be {@code null}, in which case this method 633 * returns {@code null}. 634 * @return The variable's completer, or {@code null} if the template is unregistered, the variable is 635 * undeclared, or the handler declares no completer for it. Never invokes the completer. 636 */ 637 public McpCompleter templateCompleter(String uriTemplate, String variableName) { 638 if (uriTemplate == null || variableName == null) 639 return null; 640 var templates = getResourceTemplates(); 641 var matchers = compiledResourceTemplateMatchers; 642 for (var handler : templates) { 643 if (handler == null) 644 continue; 645 var descriptor = handler.descriptor(); 646 if (descriptor == null || ! uriTemplate.equals(descriptor.getUriTemplate())) 647 continue; 648 var matcher = matchers.get(handler); 649 return matcher != null ? resourceTemplateCompleter(handler, variableName, matcher) : resourceTemplateCompleter(handler, variableName); 650 } 651 return null; 652 } 653 654 /** 655 * Unified neutral completion lookup: resolves the completer for a {@code completion/complete} target, 656 * dispatching by {@link McpCompletionRef.Kind} to {@link #promptCompleter(String, String)} or 657 * {@link #templateCompleter(String, String)}. 658 * 659 * <p> 660 * Both dated adapters call this same method for both target kinds, so template/prompt resolution policy is 661 * defined exactly once, in this neutral module. 662 * 663 * @param ref The completion reference identifying the exact prompt name or registered template string. 664 * Can be {@code null}, in which case this method returns {@code null}. 665 * @param argumentName The exact argument/variable name to look up. Can be {@code null}, in which case this 666 * method returns {@code null}. 667 * @return The resolved completer, or {@code null} if {@code ref} is {@code null}/has no {@link 668 * McpCompletionRef#getKind() kind}, or if the target-specific lookup finds none. Never invokes the 669 * completer. 670 */ 671 public McpCompleter completer(McpCompletionRef ref, String argumentName) { 672 if (ref == null || ref.getKind() == null) 673 return null; 674 if (ref.getKind() == McpCompletionRef.Kind.PROMPT) 675 return promptCompleter(ref.getTarget(), argumentName); 676 return templateCompleter(ref.getTarget(), argumentName); 677 } 678 679 /** 680 * Reports whether {@code completions} capability should be advertised: whether at least one registered 681 * prompt argument or resource-template variable currently declares a non-{@code null} completer. 682 * 683 * <p> 684 * This never invokes a completer; it only detects registration, so both dated adapters can use it for 685 * auto-derived capability advertisement without side effects. 686 * 687 * @return {@code true} if at least one prompt-argument completer or resource-template variable completer 688 * is registered. 689 */ 690 public boolean hasAnyCompleter() { 691 for (var handler : getPrompts()) { 692 if (handler == null) 693 continue; 694 var descriptor = handler.descriptor(); 695 var arguments = descriptor == null ? null : descriptor.getArguments(); 696 if (arguments == null) 697 continue; 698 for (var argument : arguments) 699 if (argument != null && argument.getCompleter() != null) 700 return true; 701 } 702 var templates = getResourceTemplates(); 703 var matchers = compiledResourceTemplateMatchers; 704 for (var handler : templates) { 705 if (handler == null) 706 continue; 707 var descriptor = handler.descriptor(); 708 var uriTemplate = descriptor == null ? null : descriptor.getUriTemplate(); 709 if (uriTemplate == null) 710 continue; 711 var matcher = matchers.get(handler); 712 var variableNames = matcher != null ? matcher.variableNames() : McpUriTemplateMatcher.compile(uriTemplate).variableNames(); 713 for (var variableName : variableNames) 714 if (handler.completer(variableName) != null) 715 return true; 716 } 717 return false; 718 } 719 720 /** 721 * Pagination strategy for {@code list} dispatchers (tools / prompts / resources / resource templates). 722 * 723 * @return The cursor. Never {@code null} (defaults to {@link McpCursor#SINGLE_PAGE}). 724 */ 725 public McpCursor getCursor() { 726 return cursor; 727 } 728 729 /** 730 * Sets the pagination strategy. 731 * 732 * @param cursor The new value (or {@code null} to reset to {@link McpCursor#SINGLE_PAGE}). 733 * @return This object (for method chaining). 734 */ 735 public McpServerConfig setCursor(McpCursor cursor) { 736 this.cursor = cursor == null ? McpCursor.SINGLE_PAGE : cursor; 737 return this; 738 } 739 740 /** 741 * The validator used to authenticate {@code Authorization: Bearer} tokens on MCP POST requests. 742 * 743 * @return The validator, or {@code null} if none is configured. 744 */ 745 public TokenValidator getTokenValidator() { 746 return tokenValidator; 747 } 748 749 /** 750 * Requires a valid bearer token on MCP POST requests, verified by the given validator. 751 * 752 * @param value The validator. Can be {@code null} to clear. 753 * @return This object (for method chaining). 754 */ 755 public McpServerConfig setTokenValidator(TokenValidator value) { 756 tokenValidator = value; 757 return this; 758 } 759 760 /** 761 * Whether an endpoint with no authentication serves callers that are not on a loopback address. 762 * 763 * @return {@code true} if unauthenticated non-loopback callers are served. Defaults to {@code false}. 764 */ 765 public boolean isAllowUnauthenticated() { 766 return allowUnauthenticated; 767 } 768 769 /** 770 * Allows an endpoint with no authentication to serve callers that are not on a loopback address. 771 * 772 * <p> 773 * Without this, an MCP endpoint that has neither a {@link #setTokenValidator(TokenValidator) token validator} nor 774 * another authentication layer answers {@code 403} to non-loopback callers. 775 * 776 * @param value The new value. 777 * @return This object (for method chaining). 778 */ 779 public McpServerConfig allowUnauthenticated(boolean value) { 780 allowUnauthenticated = value; 781 return this; 782 } 783}