|
| 1 | +/* |
| 2 | + * Copyright 2025-2026 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.github.agentic.ai.graph.agent.interceptor.toolcatalog; |
| 18 | + |
| 19 | +import io.github.agentic.ai.api.chat.ChatMessage; |
| 20 | +import io.github.agentic.ai.api.chat.ChatRole; |
| 21 | +import io.github.agentic.ai.api.chat.ToolDefinition; |
| 22 | +import io.github.agentic.ai.api.tool.Tool; |
| 23 | +import io.github.agentic.ai.api.tool.ToolRegistry; |
| 24 | +import io.github.agentic.ai.graph.agent.interceptor.ModelCallHandler; |
| 25 | +import io.github.agentic.ai.graph.agent.interceptor.ModelInterceptor; |
| 26 | +import io.github.agentic.ai.graph.agent.interceptor.ModelRequest; |
| 27 | +import io.github.agentic.ai.graph.agent.interceptor.ModelResponse; |
| 28 | +import io.github.agentic.ai.graph.agent.tool.catalog.OfferedTool; |
| 29 | +import io.github.agentic.ai.graph.agent.tool.catalog.ToolCatalog; |
| 30 | +import io.github.agentic.ai.graph.agent.tool.catalog.ToolCatalogOffer; |
| 31 | +import io.github.agentic.ai.graph.agent.tool.catalog.ToolCatalogQuery; |
| 32 | +import io.github.agentic.ai.graph.agent.tool.catalog.ToolCatalogSearchResult; |
| 33 | +import io.github.agentic.ai.graph.agent.tool.catalog.ToolCatalogSearchStatus; |
| 34 | +import io.github.agentic.ai.graph.agent.tool.catalog.ToolSummary; |
| 35 | +import io.github.agentic.ai.graph.execution.TrustedExecutionContext; |
| 36 | + |
| 37 | +import java.util.ArrayList; |
| 38 | +import java.util.HashMap; |
| 39 | +import java.util.HashSet; |
| 40 | +import java.util.List; |
| 41 | +import java.util.Map; |
| 42 | +import java.util.Objects; |
| 43 | +import java.util.Set; |
| 44 | +import java.util.function.Function; |
| 45 | + |
| 46 | +import org.slf4j.Logger; |
| 47 | +import org.slf4j.LoggerFactory; |
| 48 | + |
| 49 | +/** |
| 50 | + * Opt-in model interceptor that discloses a bounded, authorized subset of a |
| 51 | + * {@link ToolCatalog} to each model call. |
| 52 | + * |
| 53 | + * <p> |
| 54 | + * For every model call the interceptor derives a query (by default from the last user |
| 55 | + * message), searches the catalog with the run's |
| 56 | + * {@link ModelRequest#getTrustedExecutionContext() trusted execution context}, releases |
| 57 | + * full schemas only for the matched tools and adds them to the request's dynamic tool |
| 58 | + * registry under their qualified names. The released definitions are recorded under |
| 59 | + * {@link #OFFERED_TOOLS_CONTEXT_KEY} so later steps know exactly which versions were |
| 60 | + * offered; the search outcome is recorded under {@link #SEARCH_STATUS_CONTEXT_KEY}. |
| 61 | + * </p> |
| 62 | + * <p> |
| 63 | + * Catalog tools are never contributed through {@link #getTools()}, so the static tool set |
| 64 | + * of the agent does not change. An empty, unauthenticated or failed search discloses no |
| 65 | + * catalog tool and leaves the request's existing tools untouched; it never falls back to |
| 66 | + * the whole catalog. Disclosure is bounded by {@link Builder#maxTools(int)} and by the |
| 67 | + * catalog's own bound. A non-empty explicit tool selection made by an outer interceptor |
| 68 | + * is extended with the disclosed tools; an explicit empty selection disables tools for |
| 69 | + * the call and is respected. Tool execution is still authorized independently by the tool |
| 70 | + * execution boundary, for example |
| 71 | + * {@link io.github.agentic.ai.graph.agent.interceptor.authorization.ToolAuthorizationInterceptor}. |
| 72 | + * </p> |
| 73 | + */ |
| 74 | +public class ToolCatalogInterceptor extends ModelInterceptor { |
| 75 | + |
| 76 | + private static final Logger log = LoggerFactory.getLogger(ToolCatalogInterceptor.class); |
| 77 | + |
| 78 | + /** Request context key holding the {@code List<OfferedTool>} disclosed by this call. */ |
| 79 | + public static final String OFFERED_TOOLS_CONTEXT_KEY = "argi.toolCatalog.offeredTools"; |
| 80 | + |
| 81 | + /** Request context key holding the {@link ToolCatalogSearchStatus} of this call. */ |
| 82 | + public static final String SEARCH_STATUS_CONTEXT_KEY = "argi.toolCatalog.searchStatus"; |
| 83 | + |
| 84 | + private final ToolCatalog catalog; |
| 85 | + |
| 86 | + private final int maxTools; |
| 87 | + |
| 88 | + private final Set<String> domains; |
| 89 | + |
| 90 | + private final Set<String> tags; |
| 91 | + |
| 92 | + private final Function<ModelRequest, String> queryText; |
| 93 | + |
| 94 | + private ToolCatalogInterceptor(Builder builder) { |
| 95 | + this.catalog = builder.catalog; |
| 96 | + this.maxTools = builder.maxTools != null ? builder.maxTools : builder.catalog.maxResults(); |
| 97 | + this.domains = Set.copyOf(builder.domains); |
| 98 | + this.tags = Set.copyOf(builder.tags); |
| 99 | + this.queryText = builder.queryText; |
| 100 | + } |
| 101 | + |
| 102 | + public static Builder builder() { |
| 103 | + return new Builder(); |
| 104 | + } |
| 105 | + |
| 106 | + @Override |
| 107 | + public ModelResponse interceptModel(ModelRequest request, ModelCallHandler handler) { |
| 108 | + if (request.hasToolSelection() && request.getTools().isEmpty()) { |
| 109 | + // An outer interceptor explicitly disabled tools for this call; never override. |
| 110 | + return handler.call(record(request, ToolCatalogSearchStatus.EMPTY, List.of()).build()); |
| 111 | + } |
| 112 | + TrustedExecutionContext context = request.getTrustedExecutionContext().orElse(null); |
| 113 | + ToolCatalogSearchResult result; |
| 114 | + ToolCatalogOffer offer; |
| 115 | + try { |
| 116 | + String text = this.queryText.apply(request); |
| 117 | + ToolCatalogQuery query = new ToolCatalogQuery(text, this.domains, this.tags, this.maxTools); |
| 118 | + result = this.catalog.search(query, context); |
| 119 | + offer = result.matched() |
| 120 | + ? this.catalog.offer(result.tools().stream().map(ToolSummary::id).toList(), context) : null; |
| 121 | + } |
| 122 | + catch (RuntimeException ex) { |
| 123 | + log.warn("Tool catalog disclosure failed, continuing without catalog tools: {}", ex.toString()); |
| 124 | + return handler.call(record(request, ToolCatalogSearchStatus.FAILED, List.of()).build()); |
| 125 | + } |
| 126 | + if (offer == null || offer.isEmpty()) { |
| 127 | + ToolCatalogSearchStatus status = result.matched() ? ToolCatalogSearchStatus.EMPTY : result.status(); |
| 128 | + return handler.call(record(request, status, List.of()).build()); |
| 129 | + } |
| 130 | + return handler.call(disclose(request, offer).build()); |
| 131 | + } |
| 132 | + |
| 133 | + private ModelRequest.Builder disclose(ModelRequest request, ToolCatalogOffer offer) { |
| 134 | + Set<String> taken = new HashSet<>(); |
| 135 | + request.getToolRegistry().definitions().forEach(definition -> taken.add(definition.name())); |
| 136 | + List<Tool> dynamic = new ArrayList<>(); |
| 137 | + for (ToolDefinition definition : request.getDynamicToolRegistry().definitions()) { |
| 138 | + taken.add(definition.name()); |
| 139 | + dynamic.add(request.getDynamicToolRegistry().find(definition.name()).orElseThrow()); |
| 140 | + } |
| 141 | + List<OfferedTool> disclosed = new ArrayList<>(); |
| 142 | + Map<String, String> descriptions = new HashMap<>(request.getToolDescriptions()); |
| 143 | + List<String> names = new ArrayList<>(); |
| 144 | + for (int i = 0; i < offer.tools().size(); i++) { |
| 145 | + Tool tool = offer.tools().get(i); |
| 146 | + String name = tool.definition().name(); |
| 147 | + if (!taken.add(name)) { |
| 148 | + // An existing binding with the same name always wins; never shadow it. |
| 149 | + continue; |
| 150 | + } |
| 151 | + dynamic.add(tool); |
| 152 | + disclosed.add(offer.offered().get(i)); |
| 153 | + descriptions.put(name, tool.definition().description()); |
| 154 | + names.add(name); |
| 155 | + } |
| 156 | + ModelRequest.Builder builder = record(request, |
| 157 | + disclosed.isEmpty() ? ToolCatalogSearchStatus.EMPTY : ToolCatalogSearchStatus.MATCHED, disclosed); |
| 158 | + if (disclosed.isEmpty()) { |
| 159 | + return builder; |
| 160 | + } |
| 161 | + builder.dynamicToolRegistry(new ToolRegistry(dynamic)).toolDescriptions(descriptions); |
| 162 | + if (request.hasToolSelection()) { |
| 163 | + // An upstream explicit selection would otherwise filter out the catalog tools. |
| 164 | + List<String> selection = new ArrayList<>(request.getTools()); |
| 165 | + selection.addAll(names); |
| 166 | + builder.tools(selection); |
| 167 | + } |
| 168 | + log.debug("Tool catalog disclosed {} tool(s): {}", names.size(), names); |
| 169 | + return builder; |
| 170 | + } |
| 171 | + |
| 172 | + private static ModelRequest.Builder record(ModelRequest request, ToolCatalogSearchStatus status, |
| 173 | + List<OfferedTool> offered) { |
| 174 | + Map<String, Object> context = new HashMap<>(request.getContext()); |
| 175 | + context.put(SEARCH_STATUS_CONTEXT_KEY, status); |
| 176 | + context.put(OFFERED_TOOLS_CONTEXT_KEY, List.copyOf(offered)); |
| 177 | + return ModelRequest.builder(request).context(context); |
| 178 | + } |
| 179 | + |
| 180 | + static String lastUserMessage(ModelRequest request) { |
| 181 | + List<ChatMessage> messages = request.getMessages(); |
| 182 | + for (int i = messages.size() - 1; i >= 0; i--) { |
| 183 | + ChatMessage message = messages.get(i); |
| 184 | + if (message.role() == ChatRole.USER) { |
| 185 | + return message.text(); |
| 186 | + } |
| 187 | + } |
| 188 | + return ""; |
| 189 | + } |
| 190 | + |
| 191 | + @Override |
| 192 | + public String getName() { |
| 193 | + return "ToolCatalog"; |
| 194 | + } |
| 195 | + |
| 196 | + public static class Builder { |
| 197 | + |
| 198 | + private ToolCatalog catalog; |
| 199 | + |
| 200 | + private Integer maxTools; |
| 201 | + |
| 202 | + private Set<String> domains = Set.of(); |
| 203 | + |
| 204 | + private Set<String> tags = Set.of(); |
| 205 | + |
| 206 | + private Function<ModelRequest, String> queryText = ToolCatalogInterceptor::lastUserMessage; |
| 207 | + |
| 208 | + /** Required catalog to search. */ |
| 209 | + public Builder catalog(ToolCatalog catalog) { |
| 210 | + this.catalog = catalog; |
| 211 | + return this; |
| 212 | + } |
| 213 | + |
| 214 | + /** |
| 215 | + * Maximum catalog tools disclosed per model call; the catalog's own bound still |
| 216 | + * applies. Defaults to the catalog bound. |
| 217 | + */ |
| 218 | + public Builder maxTools(int maxTools) { |
| 219 | + if (maxTools <= 0) { |
| 220 | + throw new IllegalArgumentException("maxTools must be > 0"); |
| 221 | + } |
| 222 | + this.maxTools = maxTools; |
| 223 | + return this; |
| 224 | + } |
| 225 | + |
| 226 | + /** Restricts retrieval to these domains. */ |
| 227 | + public Builder domains(Set<String> domains) { |
| 228 | + this.domains = Objects.requireNonNull(domains, "domains must not be null"); |
| 229 | + return this; |
| 230 | + } |
| 231 | + |
| 232 | + /** Restricts retrieval to tools carrying at least one of these tags. */ |
| 233 | + public Builder tags(Set<String> tags) { |
| 234 | + this.tags = Objects.requireNonNull(tags, "tags must not be null"); |
| 235 | + return this; |
| 236 | + } |
| 237 | + |
| 238 | + /** Derives the free-text query; defaults to the last user message. */ |
| 239 | + public Builder queryText(Function<ModelRequest, String> queryText) { |
| 240 | + this.queryText = Objects.requireNonNull(queryText, "queryText must not be null"); |
| 241 | + return this; |
| 242 | + } |
| 243 | + |
| 244 | + public ToolCatalogInterceptor build() { |
| 245 | + if (this.catalog == null) { |
| 246 | + throw new IllegalStateException("Tool catalog is required"); |
| 247 | + } |
| 248 | + return new ToolCatalogInterceptor(this); |
| 249 | + } |
| 250 | + |
| 251 | + } |
| 252 | + |
| 253 | +} |
0 commit comments