Skip to content

Commit 262ce55

Browse files
authored
Merge pull request #333 from konlue/feat/t268-interceptor-tool-filtering
fix(agent): honor interceptor tool selection and dynamic registries in standalone ReAct (issue #268)
2 parents 3cfff6d + 45224e1 commit 262ce55

2 files changed

Lines changed: 265 additions & 9 deletions

File tree

‎argi-agent/argi-agent-core/src/main/java/io/github/agentic/ai/agent/react/ReActAgent.java‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,8 @@ private void run() {
343343
for (int turn = 0; turn < maxTurns; turn++) {
344344
context.control().assertActive();
345345
ToolRegistry availableTools = resolveTools(state);
346-
ChatResponse response = modelTurn(messages, state, usage, availableTools);
346+
AtomicReference<ToolRegistry> effectiveTools = new AtomicReference<>(availableTools);
347+
ChatResponse response = modelTurn(messages, state, usage, availableTools, effectiveTools);
347348
if (response.messages().isEmpty()) {
348349
throw new IllegalStateException("Model response did not contain an assistant message");
349350
}
@@ -356,7 +357,7 @@ private void run() {
356357
return;
357358
}
358359
for (ToolCall call : response.toolCalls()) {
359-
ToolStep step = executeTool(call, messages, state, availableTools);
360+
ToolStep step = executeTool(call, messages, state, effectiveTools.get());
360361
if (step.suspension() != null) {
361362
AgentOutcome outcome = new AgentOutcome(AgentOutcome.Status.SUSPENDED, messages, state,
362363
usage.value(), step.suspension());
@@ -378,17 +379,29 @@ private ToolRegistry resolveTools(Map<String, Object> state) {
378379
}
379380
ToolRegistry dynamic = Objects.requireNonNull(dynamicToolProvider.apply(Map.copyOf(state)),
380381
"dynamic tool provider returned no registry");
381-
List<Tool> combined = new ArrayList<>(tools.tools());
382-
combined.addAll(dynamic.tools());
383-
return new ToolRegistry(combined);
382+
// Static bindings shadow same-named dynamic disclosures instead of failing the
383+
// merge (issue #268: a testable duplicate-name policy, consistent with
384+
// ModelRequest.getTools()'s distinct order).
385+
Map<String, Tool> combined = new LinkedHashMap<>();
386+
for (Tool tool : tools.tools()) {
387+
combined.put(tool.definition().name(), tool);
388+
}
389+
for (Tool tool : dynamic.tools()) {
390+
combined.putIfAbsent(tool.definition().name(), tool);
391+
}
392+
return new ToolRegistry(List.copyOf(combined.values()));
384393
}
385394

386395
private ChatResponse modelTurn(List<ChatMessage> messages, Map<String, Object> state,
387-
UsageAccumulator usage, ToolRegistry availableTools) {
396+
UsageAccumulator usage, ToolRegistry availableTools,
397+
AtomicReference<ToolRegistry> effectiveTools) {
388398
context.control().assertActive();
389399
ModelRequest request = ModelRequest.builder().messages(messages).toolRegistry(availableTools)
390400
.trustedExecutionContext(context.trusted()).context(state).attributes(state).build();
391-
ModelCallHandler handler = modelRequest -> invokeModel(modelRequest, usage);
401+
// The effective tool set is only known at the end of the interceptor chain,
402+
// where selection semantics are resolved; execution in the same turn must use
403+
// exactly the set the model was shown (issue #268: declared and executed agree).
404+
ModelCallHandler handler = modelRequest -> invokeModel(modelRequest, usage, effectiveTools);
392405
for (int index = interceptors.size() - 1; index >= 0; index--) {
393406
ModelInterceptor interceptor = interceptors.get(index);
394407
ModelCallHandler next = handler;
@@ -401,8 +414,37 @@ private ChatResponse modelTurn(List<ChatMessage> messages, Map<String, Object> s
401414
return response.getChatResponse();
402415
}
403416

404-
private ModelResponse invokeModel(ModelRequest request, UsageAccumulator usage) {
405-
ChatRequest chatRequest = new ChatRequest(request.getMessages(), request.getToolRegistry().definitions(),
417+
/**
418+
* Resolves the effective tool set at the end of the interceptor chain: static
419+
* bindings and the invocation-local dynamic registry merged (static shadows
420+
* dynamic on name conflicts, matching {@link ModelRequest#getTools()}), narrowed
421+
* by the explicit selection when one is specified. An explicit empty selection
422+
* disables all tool disclosure and execution; an absent selection uses every
423+
* binding.
424+
*/
425+
private ToolRegistry effectiveToolSet(ModelRequest request) {
426+
List<String> selection = request.hasToolSelection() ? request.getTools() : null;
427+
if (selection == null && request.getDynamicToolRegistry().tools().isEmpty()) {
428+
return request.getToolRegistry();
429+
}
430+
Map<String, Tool> effective = new LinkedHashMap<>();
431+
for (Tool tool : request.getToolRegistry().tools()) {
432+
effective.put(tool.definition().name(), tool);
433+
}
434+
for (Tool tool : request.getDynamicToolRegistry().tools()) {
435+
effective.putIfAbsent(tool.definition().name(), tool);
436+
}
437+
if (selection != null) {
438+
effective.keySet().retainAll(selection);
439+
}
440+
return new ToolRegistry(List.copyOf(effective.values()));
441+
}
442+
443+
private ModelResponse invokeModel(ModelRequest request, UsageAccumulator usage,
444+
AtomicReference<ToolRegistry> effectiveTools) {
445+
ToolRegistry effective = effectiveToolSet(request);
446+
effectiveTools.set(effective);
447+
ChatRequest chatRequest = new ChatRequest(request.getMessages(), effective.definitions(),
406448
request.getOptions(), request.getAttributes());
407449
if (streamModel) {
408450
return ModelResponse.of(collectModelStream(chatRequest, usage));

‎argi-agent/argi-agent-core/src/test/java/io/github/agentic/ai/agent/react/ReActAgentTest.java‎

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,220 @@ public void onComplete() {
167167
assertTrue(events.stream().anyMatch(event -> event instanceof AgentEvent.MessageDelta));
168168
}
169169

170+
// ------------------------------------------------------------------
171+
// issue #268: interceptor tool selection must gate disclosure AND execution
172+
// ------------------------------------------------------------------
173+
174+
@Test
175+
void unfilteredRunDisclosesStaticAndDynamicTools() throws Exception {
176+
Tool staticTool = tool("chosen", "{}", (ignored, context) ->
177+
CompletableFuture.completedFuture(ToolResult.text("static")));
178+
Tool dynamicTool = tool("dyn", "{}", (ignored, context) ->
179+
CompletableFuture.completedFuture(ToolResult.text("dynamic")));
180+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("answer"), List.of(), 1)));
181+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(staticTool)))
182+
.dynamicTools(state -> new ToolRegistry(List.of(dynamicTool))).build();
183+
184+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
185+
186+
List<String> disclosed = client.requests.get(0).tools().stream()
187+
.map(ToolDefinition::name).toList();
188+
assertEquals(List.of("chosen", "dyn"), disclosed);
189+
}
190+
191+
@Test
192+
void explicitEmptySelectionDisablesDisclosureAndExecution() throws Exception {
193+
ToolCall call = new ToolCall("call-1", "secret", "{}");
194+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("try", List.of(call)),
195+
List.of(call), 1), response(ChatMessage.assistant("blocked"), List.of(), 1)));
196+
ModelInterceptor interceptor = new ModelInterceptor() {
197+
public String getName() {
198+
return "disable-tools";
199+
}
200+
201+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
202+
return next.call(ModelRequest.builder(request).tools(List.of()).build());
203+
}
204+
};
205+
Tool secret = tool("secret", "{}", (ignored, context) ->
206+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
207+
AgentOutcome outcome = ReActAgent.builder(client).tools(new ToolRegistry(List.of(secret)))
208+
.interceptors(List.of(interceptor)).build().invoke(request(), context()).get(3, TimeUnit.SECONDS);
209+
210+
// The model sees no tools at all.
211+
assertTrue(client.requests.get(0).tools().isEmpty());
212+
// A tool call for a filtered-out tool surfaces via the unknown-tool error path.
213+
assertEquals("blocked", outcome.messages().get(outcome.messages().size() - 1).text());
214+
assertTrue(outcome.messages().stream()
215+
.anyMatch(message -> message.text().contains("Unknown tool: secret")));
216+
}
217+
218+
@Test
219+
void subsetSelectionDisclosesAndExecutesOnlyChosenTools() throws Exception {
220+
ToolCall call = new ToolCall("call-1", "chosen", "{}");
221+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("use", List.of(call)),
222+
List.of(call), 1), response(ChatMessage.assistant("done"), List.of(), 1)));
223+
ModelInterceptor interceptor = new ModelInterceptor() {
224+
public String getName() {
225+
return "subset";
226+
}
227+
228+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
229+
return next.call(ModelRequest.builder(request).tools(List.of("chosen")).build());
230+
}
231+
};
232+
Tool chosen = tool("chosen", "{}", (ignored, context) ->
233+
CompletableFuture.completedFuture(ToolResult.text("chosen result")));
234+
Tool secret = tool("secret", "{}", (ignored, context) ->
235+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
236+
AgentOutcome outcome = ReActAgent.builder(client).tools(new ToolRegistry(List.of(chosen, secret)))
237+
.interceptors(List.of(interceptor)).build().invoke(request(), context()).get(3, TimeUnit.SECONDS);
238+
239+
List<String> disclosed = client.requests.get(0).tools().stream()
240+
.map(ToolDefinition::name).toList();
241+
assertEquals(List.of("chosen"), disclosed);
242+
assertTrue(outcome.messages().stream().anyMatch(message -> "chosen result".equals(message.text())));
243+
assertTrue(outcome.messages().stream().noneMatch(message -> "leaked".equals(message.text())));
244+
}
245+
246+
@Test
247+
void dynamicToolsParticipateInSelection() throws Exception {
248+
Tool dynamic = tool("dyn", "{}", (ignored, context) ->
249+
CompletableFuture.completedFuture(ToolResult.text("dynamic result")));
250+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("answer"), List.of(), 1)));
251+
ModelInterceptor interceptor = new ModelInterceptor() {
252+
public String getName() {
253+
return "dynamic-only";
254+
}
255+
256+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
257+
return next.call(ModelRequest.builder(request).tools(List.of("dyn")).build());
258+
}
259+
};
260+
ReActAgent agent = ReActAgent.builder(client).dynamicTools(state -> new ToolRegistry(List.of(dynamic)))
261+
.interceptors(List.of(interceptor)).build();
262+
263+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
264+
265+
List<String> disclosed = client.requests.get(0).tools().stream()
266+
.map(ToolDefinition::name).toList();
267+
assertEquals(List.of("dyn"), disclosed);
268+
}
269+
270+
@Test
271+
void staticToolShadowsDynamicToolOnNameConflict() throws Exception {
272+
AtomicInteger staticExecutions = new AtomicInteger();
273+
AtomicInteger dynamicExecutions = new AtomicInteger();
274+
Tool staticTool = tool("lookup", "{}", (ignored, context) -> {
275+
staticExecutions.incrementAndGet();
276+
return CompletableFuture.completedFuture(ToolResult.text("original"));
277+
});
278+
Tool dynamicTool = tool("lookup", "{}", (ignored, context) -> {
279+
dynamicExecutions.incrementAndGet();
280+
return CompletableFuture.completedFuture(ToolResult.text("replacement"));
281+
});
282+
ToolCall call = new ToolCall("call-1", "lookup", "{}");
283+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("use", List.of(call)),
284+
List.of(call), 1), response(ChatMessage.assistant("done"), List.of(), 1)));
285+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(staticTool)))
286+
.dynamicTools(state -> new ToolRegistry(List.of(dynamicTool))).build();
287+
288+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
289+
290+
// Static bindings shadow same-named dynamic disclosures (getTools() semantics).
291+
assertEquals(1, staticExecutions.get());
292+
assertEquals(0, dynamicExecutions.get());
293+
}
294+
295+
@Test
296+
void streamingRunDisclosesTheSameFilteredSetAsNonStreaming() throws Exception {
297+
Tool secret = tool("secret", "{}", (ignored, context) ->
298+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
299+
StreamingClient client = new StreamingClient();
300+
ModelInterceptor interceptor = new ModelInterceptor() {
301+
public String getName() {
302+
return "disable-tools";
303+
}
304+
305+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
306+
return next.call(ModelRequest.builder(request).tools(List.of()).build());
307+
}
308+
};
309+
ReActAgent agent = ReActAgent.builder(client).streamModel(true).tools(new ToolRegistry(List.of(secret)))
310+
.interceptors(List.of(interceptor)).build();
311+
312+
try (AgentExecutionContext context = context()) {
313+
CompletableFuture<AgentOutcome> outcome = new CompletableFuture<>();
314+
agent.stream(request(), context).subscribe(new Flow.Subscriber<>() {
315+
public void onSubscribe(Flow.Subscription subscription) {
316+
subscription.request(Long.MAX_VALUE);
317+
}
318+
319+
public void onNext(AgentEvent event) {
320+
if (event instanceof AgentEvent.Finished finished) {
321+
outcome.complete(finished.outcome());
322+
}
323+
}
324+
325+
public void onError(Throwable error) {
326+
outcome.completeExceptionally(error);
327+
}
328+
329+
public void onComplete() {
330+
}
331+
});
332+
outcome.get(3, TimeUnit.SECONDS);
333+
}
334+
assertTrue(client.requests.get(0).tools().isEmpty());
335+
}
336+
337+
@Test
338+
void selectionDoesNotLeakAcrossSequentialRuns() throws Exception {
339+
ToolCall chosenCall = new ToolCall("call-1", "chosen", "{}");
340+
ScriptedClient client = new ScriptedClient(List.of(
341+
response(ChatMessage.assistant("use", List.of(chosenCall)), List.of(chosenCall), 1),
342+
response(ChatMessage.assistant("done"), List.of(), 1),
343+
response(ChatMessage.assistant("use", List.of(chosenCall)), List.of(chosenCall), 1),
344+
response(ChatMessage.assistant("done"), List.of(), 1)));
345+
ModelInterceptor interceptor = new ModelInterceptor() {
346+
public String getName() {
347+
return "subset";
348+
}
349+
350+
public ModelResponse interceptModel(ModelRequest request, ModelCallHandler next) {
351+
return next.call(ModelRequest.builder(request).tools(List.of("chosen")).build());
352+
}
353+
};
354+
Tool chosen = tool("chosen", "{}", (ignored, context) ->
355+
CompletableFuture.completedFuture(ToolResult.text("chosen result")));
356+
Tool secret = tool("secret", "{}", (ignored, context) ->
357+
CompletableFuture.completedFuture(ToolResult.text("leaked")));
358+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(chosen, secret)))
359+
.interceptors(List.of(interceptor)).build();
360+
361+
AgentOutcome first = agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
362+
AgentOutcome second = agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
363+
364+
for (AgentOutcome outcome : List.of(first, second)) {
365+
assertTrue(outcome.messages().stream().anyMatch(message -> "chosen result".equals(message.text())));
366+
assertTrue(outcome.messages().stream().noneMatch(message -> "leaked".equals(message.text())));
367+
}
368+
}
369+
370+
@Test
371+
void unfilteredRunWithNoDynamicToolsKeepsRegistryFastPath() throws Exception {
372+
Tool staticTool = tool("only", "{}", (ignored, context) ->
373+
CompletableFuture.completedFuture(ToolResult.text("ok")));
374+
ScriptedClient client = new ScriptedClient(List.of(response(ChatMessage.assistant("answer"), List.of(), 1)));
375+
ReActAgent agent = ReActAgent.builder(client).tools(new ToolRegistry(List.of(staticTool))).build();
376+
377+
agent.invoke(request(), context()).get(3, TimeUnit.SECONDS);
378+
379+
List<String> disclosed = client.requests.get(0).tools().stream()
380+
.map(ToolDefinition::name).toList();
381+
assertEquals(List.of("only"), disclosed);
382+
}
383+
170384
@Test
171385
void deniedToolCanSuspendForHumanApproval() throws Exception {
172386
ToolCall call = new ToolCall("call-1", "danger", "{}");

0 commit comments

Comments
 (0)