Skip to content

Commit a211ac4

Browse files
google-genai-botcopybara-github
authored andcommitted
feat: Add BaseToolset and update McpToolset to use the new interface
PiperOrigin-RevId: 781378937
1 parent 315f354 commit a211ac4

File tree

9 files changed

+250
-221
lines changed

9 files changed

+250
-221
lines changed

core/src/main/java/com/google/adk/agents/CallbackContext.java

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818

1919
import com.google.adk.events.EventActions;
2020
import com.google.adk.sessions.State;
21-
import com.google.genai.types.Content;
2221
import com.google.genai.types.Part;
2322
import io.reactivex.rxjava3.core.Maybe;
2423
import java.util.Optional;
@@ -47,11 +46,6 @@ public State state() {
4746
return state;
4847
}
4948

50-
/** Returns the user content that initiated this invocation. */
51-
public Optional<Content> userContent() {
52-
return invocationContext.userContent();
53-
}
54-
5549
/** Returns the EventActions associated with this context. */
5650
public EventActions eventActions() {
5751
return eventActions;

core/src/main/java/com/google/adk/agents/LlmAgent.java

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package com.google.adk.agents;
1818

19+
import static com.google.common.collect.ImmutableList.toImmutableList;
1920
import static java.util.stream.Collectors.joining;
2021

2122
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -47,6 +48,7 @@
4748
import com.google.adk.models.BaseLlm;
4849
import com.google.adk.models.Model;
4950
import com.google.adk.tools.BaseTool;
51+
import com.google.adk.tools.BaseToolset;
5052
import com.google.common.base.Preconditions;
5153
import com.google.common.collect.ImmutableList;
5254
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -56,6 +58,7 @@
5658
import io.reactivex.rxjava3.core.Flowable;
5759
import io.reactivex.rxjava3.core.Maybe;
5860
import io.reactivex.rxjava3.core.Single;
61+
import java.util.ArrayList;
5962
import java.util.List;
6063
import java.util.Map;
6164
import java.util.Optional;
@@ -81,7 +84,7 @@ public enum IncludeContents {
8184
private final Optional<Model> model;
8285
private final Instruction instruction;
8386
private final Instruction globalInstruction;
84-
private final List<BaseTool> tools;
87+
private final List<Object> toolsUnion;
8588
private final Optional<GenerateContentConfig> generateContentConfig;
8689
private final Optional<BaseExampleProvider> exampleProvider;
8790
private final IncludeContents includeContents;
@@ -130,7 +133,7 @@ protected LlmAgent(Builder builder) {
130133
this.outputSchema = Optional.ofNullable(builder.outputSchema);
131134
this.executor = Optional.ofNullable(builder.executor);
132135
this.outputKey = Optional.ofNullable(builder.outputKey);
133-
this.tools = builder.tools != null ? builder.tools : ImmutableList.of();
136+
this.toolsUnion = builder.toolsUnion != null ? builder.toolsUnion : ImmutableList.of();
134137

135138
this.llmFlow = determineLlmFlow();
136139

@@ -153,7 +156,7 @@ public static class Builder {
153156
private Instruction instruction;
154157
private Instruction globalInstruction;
155158
private ImmutableList<BaseAgent> subAgents;
156-
private ImmutableList<BaseTool> tools;
159+
private ImmutableList<Object> toolsUnion;
157160
private GenerateContentConfig generateContentConfig;
158161
private BaseExampleProvider exampleProvider;
159162
private IncludeContents includeContents;
@@ -234,14 +237,14 @@ public Builder subAgents(BaseAgent... subAgents) {
234237
}
235238

236239
@CanIgnoreReturnValue
237-
public Builder tools(List<? extends BaseTool> tools) {
238-
this.tools = ImmutableList.copyOf(tools);
240+
public Builder tools(List<?> tools) {
241+
this.toolsUnion = ImmutableList.copyOf(tools);
239242
return this;
240243
}
241244

242245
@CanIgnoreReturnValue
243-
public Builder tools(BaseTool... tools) {
244-
this.tools = ImmutableList.copyOf(tools);
246+
public Builder tools(Object... tools) {
247+
this.toolsUnion = ImmutableList.copyOf(tools);
245248
return this;
246249
}
247250

@@ -580,7 +583,7 @@ protected void validate() {
580583
+ ": if outputSchema is set, subAgents must be empty to disable agent"
581584
+ " transfer.");
582585
}
583-
if (this.tools != null && !this.tools.isEmpty()) {
586+
if (this.toolsUnion != null && !this.toolsUnion.isEmpty()) {
584587
throw new IllegalArgumentException(
585588
"Invalid config for agent "
586589
+ this.name
@@ -687,6 +690,42 @@ public Single<String> canonicalGlobalInstruction(ReadonlyContext context) {
687690
throw new IllegalStateException("Unknown Instruction subtype: " + instruction.getClass());
688691
}
689692

693+
/**
694+
* Constructs the list of tools for this agent based on the {@link #tools} field.
695+
*
696+
* <p>This method is only for use by Agent Development Kit.
697+
*
698+
* @param context The context to retrieve the session state.
699+
* @return The resolved list of tools as a {@link Single} wrapped list of {@link BaseTool}.
700+
*/
701+
public Single<List<BaseTool>> canonicalTools(Optional<ReadonlyContext> context) {
702+
List<Single<List<BaseTool>>> toolSingles = new ArrayList<>();
703+
for (Object toolOrToolset : toolsUnion) {
704+
if (toolOrToolset instanceof BaseTool baseTool) {
705+
toolSingles.add(Single.just(ImmutableList.of(baseTool)));
706+
} else if (toolOrToolset instanceof BaseToolset baseToolset) {
707+
toolSingles.add(baseToolset.getTools(context.orElse(null)));
708+
} else {
709+
throw new IllegalArgumentException(
710+
"Object in tools list is not of a supported type: "
711+
+ toolOrToolset.getClass().getName());
712+
}
713+
}
714+
return Single.concat(toolSingles)
715+
.toList()
716+
.map(listOfLists -> listOfLists.stream().flatMap(List::stream).collect(toImmutableList()));
717+
}
718+
719+
/** Overload of canonicalTools that defaults to an empty context. */
720+
public Single<List<BaseTool>> canonicalTools() {
721+
return canonicalTools(Optional.empty());
722+
}
723+
724+
/** Convenience overload of canonicalTools that accepts a non-optional ReadonlyContext. */
725+
public Single<List<BaseTool>> canonicalTools(ReadonlyContext context) {
726+
return canonicalTools(Optional.ofNullable(context));
727+
}
728+
690729
public Instruction instruction() {
691730
return instruction;
692731
}
@@ -719,8 +758,8 @@ public IncludeContents includeContents() {
719758
return includeContents;
720759
}
721760

722-
public List<BaseTool> tools() {
723-
return tools;
761+
public List<Object> tools() {
762+
return toolsUnion;
724763
}
725764

726765
public boolean disallowTransferToParent() {

core/src/main/java/com/google/adk/agents/ReadonlyContext.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.google.adk.agents;
1818

1919
import com.google.common.collect.ImmutableMap;
20+
import com.google.genai.types.Content;
2021
import java.util.Map;
2122
import java.util.Optional;
2223

@@ -29,6 +30,11 @@ public ReadonlyContext(InvocationContext invocationContext) {
2930
this.invocationContext = invocationContext;
3031
}
3132

33+
/** Returns the user content that initiated this invocation. */
34+
public Optional<Content> userContent() {
35+
return invocationContext.userContent();
36+
}
37+
3238
/** Returns the ID of the current invocation. */
3339
public String invocationId() {
3440
return invocationContext.invocationId();

core/src/main/java/com/google/adk/flows/llmflows/BaseLlmFlow.java

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import com.google.adk.agents.InvocationContext;
2525
import com.google.adk.agents.LiveRequest;
2626
import com.google.adk.agents.LlmAgent;
27+
import com.google.adk.agents.ReadonlyContext;
2728
import com.google.adk.agents.RunConfig.StreamingMode;
2829
import com.google.adk.events.Event;
2930
import com.google.adk.exceptions.LlmCallsLimitExceededException;
@@ -112,20 +113,22 @@ protected Single<RequestProcessingResult> preprocess(
112113
processedRequest -> {
113114
LlmRequest.Builder updatedRequestBuilder = processedRequest.toBuilder();
114115

115-
Completable toolProcessingCompletable =
116-
Flowable.fromIterable(agent.tools())
117-
.concatMapCompletable(
118-
tool ->
119-
tool.processLlmRequest(
120-
updatedRequestBuilder, ToolContext.builder(context).build()));
121-
122-
return toolProcessingCompletable.andThen(
123-
Single.fromCallable(
124-
() -> {
125-
Iterable<Event> combinedEvents = Iterables.concat(eventIterables);
126-
return RequestProcessingResult.create(
127-
updatedRequestBuilder.build(), combinedEvents);
128-
}));
116+
return agent
117+
.canonicalTools(new ReadonlyContext(context))
118+
.flatMapCompletable(
119+
tools ->
120+
Flowable.fromIterable(tools)
121+
.concatMapCompletable(
122+
tool ->
123+
tool.processLlmRequest(
124+
updatedRequestBuilder, ToolContext.builder(context).build())))
125+
.andThen(
126+
Single.fromCallable(
127+
() -> {
128+
Iterable<Event> combinedEvents = Iterables.concat(eventIterables);
129+
return RequestProcessingResult.create(
130+
updatedRequestBuilder.build(), combinedEvents);
131+
}));
129132
});
130133
}
131134

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.google.adk.tools;
2+
3+
import com.google.adk.agents.ReadonlyContext;
4+
import io.reactivex.rxjava3.core.Single;
5+
import java.util.List;
6+
import java.util.Optional;
7+
8+
/** Base interface for toolsets. */
9+
public interface BaseToolset extends AutoCloseable {
10+
11+
/**
12+
* Return all tools in the toolset based on the provided context.
13+
*
14+
* @param readonlyContext Context used to filter tools available to the agent.
15+
* @return A Single emitting a list of tools available under the specified context.
16+
*/
17+
Single<List<BaseTool>> getTools(ReadonlyContext readonlyContext);
18+
19+
/**
20+
* Performs cleanup and releases resources held by the toolset.
21+
*
22+
* <p>NOTE: This method is invoked, for example, at the end of an agent server's lifecycle or when
23+
* the toolset is no longer needed. Implementations should ensure that any open connections,
24+
* files, or other managed resources are properly released to prevent leaks.
25+
*/
26+
@Override
27+
void close() throws Exception;
28+
29+
/**
30+
* Helper method to be used by implementers that returns true if the given tool is in the provided
31+
* list of tools of if testing against the given ToolPredicate returns true (otherwise false).
32+
*
33+
* @param tool The tool to check.
34+
* @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.
35+
* @param readonlyContext The current context.
36+
* @return true if the tool is selected.
37+
*/
38+
default boolean isToolSelected(
39+
BaseTool tool, Optional<Object> toolFilter, Optional<ReadonlyContext> readonlyContext) {
40+
if (toolFilter.isEmpty()) {
41+
return true;
42+
}
43+
Object filter = toolFilter.get();
44+
if (filter instanceof ToolPredicate toolPredicate) {
45+
return toolPredicate.test(tool, readonlyContext);
46+
}
47+
if (filter instanceof List) {
48+
@SuppressWarnings("unchecked")
49+
List<String> toolNames = (List<String>) filter;
50+
return toolNames.contains(tool.name());
51+
}
52+
return false;
53+
}
54+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.google.adk.tools;
2+
3+
import com.google.adk.agents.ReadonlyContext;
4+
import java.util.Optional;
5+
6+
/**
7+
* Functional interface to decide whether a tool should be exposed to the LLM based on the current
8+
* context.
9+
*/
10+
@FunctionalInterface
11+
public interface ToolPredicate {
12+
/**
13+
* Decides if the given tool is selected.
14+
*
15+
* @param tool The tool to check.
16+
* @param readonlyContext The current context.
17+
* @return true if the tool should be selected, false otherwise.
18+
*/
19+
boolean test(BaseTool tool, Optional<ReadonlyContext> readonlyContext);
20+
}

0 commit comments

Comments
 (0)