set_test.go
Overview
The set_test.go file is a Go test suite focused on validating the integration and functionality of the MCP Toolset Integration within an agent framework. It demonstrates how an MCP (Model Context Protocol) server can be hosted in-memory, how MCP tools are exposed to an agent, and how agents invoke these tools to respond to natural language queries.
This file exercises key flows such as:
Creating an in-memory MCP server with registered tools.
Establishing client-server MCP transport connections.
Wrapping MCP tools into an ADK (Agent Development Kit) toolset.
Creating an LLM agent configured with MCP tools.
Running an agent session that triggers tool invocation via function calls.
Validating event streams generated by the agent interacting with MCP tools.
Filtering MCP tools exposed to the agent.
The tests use mocks and recorded HTTP round-trippers to simulate LLM model interactions without real network calls.
Key Types and Functions
Input and Output Structs
type Input struct {
City string `json:"city" jsonschema:"city name"`
}
type Output struct {
WeatherSummary string `json:"weather_summary" jsonschema:"weather summary in the given city"`
}
Purpose: Define the typed input and output data structures for the example MCP tool
get_weather.Usage: Used for JSON marshaling/unmarshaling of tool arguments and results.
weatherFunc
func weatherFunc(ctx context.Context, req *mcp.CallToolRequest, input Input) (*mcp.CallToolResult, Output, error)
Purpose: Implements the MCP tool logic for
get_weather.Parameters:
ctx: context for cancellation and deadlines.req: MCP call request metadata.input: typed input containing the city name.
Returns:
*mcp.CallToolResult: MCP call metadata, herenilsince no special info.Output: typed result with a weather summary string.error: error if any.
Functionality: Returns a static weather summary string, e.g.,
"Today in "city" is sunny".
TestMCPToolSet
func TestMCPToolSet(t *testing.T)
Purpose: Tests basic MCP toolset integration end-to-end.
Steps:
Setup in-memory MCP client and server transports.
Create MCP server with implementation metadata (
weather_serverv1.0.0).Add the
get_weathertool withweatherFunchandler.Connect server to transport.
Create MCP toolset client with the client transport.
Create an LLM agent (
llmagent.New) configured with the MCP toolset.Run the agent with the prompt
"what is the weather in london?".Collect session events emitted by the agent.
Assert that the returned events correspond to:
A function call to
get_weatherwith argumentcity: london.The function response containing the weather summary.
The final textual LLM response including the weather summary.
Integration Points:
Uses
mcp.NewServerandmcp.AddToolto define MCP tools.Uses
mcptoolset.Newto wrap MCP tools as ADK tools.Uses
llmagent.Newto create an agent with LLM + tools.Uses
runnerto execute the agent session and collect events.
Testing:
Utilizes
cmp.Diffto compare expected and actual event sequences, ignoring fields like timestamps and IDs.Checks correctness of the function call and response workflow.
newGeminiTestClientConfig
func newGeminiTestClientConfig(t *testing.T, rrfile string) (http.RoundTripper, bool)
Purpose: Creates an HTTP RoundTripper for Gemini model API calls, optionally replaying or recording HTTP traces.
Parameters:
t: Go testing instance.rrfile: path to HTTP recording file.
Returns:
http.RoundTripper: HTTP transport for Gemini client.bool: whether the transport is in recording mode.
Functionality: Loads HTTP traces from file for deterministic test runs.
newGeminiModel
func newGeminiModel(t *testing.T, modelName string) model.LLM
Purpose: Creates a Gemini LLM model instance configured with test HTTP transport and API key.
Parameters:
t: Go testing instance.modelName: name of the Gemini model (e.g.,"gemini-2.5-flash").
Returns:
model.LLMinterface instance.Details:
Uses
newGeminiTestClientConfigto configure HTTP client.Uses a fake API key unless recording.
Reports fatal errors on model creation failure.
testAgentRunner
A helper struct to encapsulate agent execution within tests.
type testAgentRunner struct {
agent agent.Agent
sessionService session.Service
lastSession session.Session
appName string
runner *runner.Runner
}
Purpose: Provides convenient methods to run agent sessions and send messages.
Key Methods:
session(t *testing.T, appName, userID, sessionID string) (session.Session, error)Retrieves or creates a session in the in-memory session service.
Caches the last session for reuse.
Run(t *testing.T, sessionID, newMessage string) iter.Seq2[*session.Event, error]Runs the agent with a user message in the specified session.
Returns a sequence of session events and errors.
Internally creates a new
genai.Contentfrom the message text.
Usage: Used in
TestMCPToolSetto run an agent session and collect events.
TestToolFilter
func TestToolFilter(t *testing.T)
Purpose: Tests the MCP toolset's ability to filter tools by name using a predicate.
Flow:
Create in-memory MCP server with two tools:
"get_weather"and"get_weather1".Connect server.
Create MCP toolset client with a filter predicate allowing only
"get_weather".Retrieve tools from the toolset.
Assert that only one tool named
"get_weather"is present.
Significance: Validates that the MCP toolset respects configured tool filters to limit exposed tools.
Important Implementation Details
In-memory MCP Server: Uses
mcp.NewInMemoryTransports()to simulate client-server communication without network dependencies.MCP Tool Registration: Tools are added to the MCP server via
mcp.AddToolwith a Go function handler that returns typed results.Lazy Transport Setup: MCP toolset client is created with the client side of the in-memory transport.
Agent Configuration: The agent is built with a Gemini LLM model and the MCP toolset as its tools, enabling seamless LLM function calls to MCP tools.
Session and Runner: Uses an in-memory session service and a runner to execute the agent lifecycle and message processing.
Function Call Events: The test verifies the sequence of events includes expected function calls and responses, matching the MCP tool invocation lifecycle.
Tool Filtering: Demonstrates how the MCP toolset can filter tools at creation time based on a predicate, restricting available tools dynamically.
Interaction with Other Parts of the System
Model Context Protocol (MCP): The tests interact with the MCP server and client to simulate tool invocation over MCP.
Agent Framework (80561 - AI Agent Framework): The agent lifecycle, session management, and event handling are exercised.
LLM Integration and Agents (80562): The agent is configured with an LLM model and tools, invoking function calls triggered by LLM responses.
Tooling System (80556) and MCP Toolset (80577): The MCP toolset wraps MCP tools as ADK tools, enabling the agent to invoke them.
Session Management (80559) and Agent Execution Runner (80560): Sessions are managed in-memory, and the runner coordinates agent execution and event generation.
Test Utilities: The file uses internal test utilities to create HTTP round-trippers simulating Gemini API calls and to record/replay HTTP traffic.
Usage Example (from TestMCPToolSet)
// Create in-memory MCP transports
clientTransport, serverTransport := mcp.NewInMemoryTransports()
// Setup MCP server and add tools
server := mcp.NewServer(&mcp.Implementation{Name: "weather_server", Version: "v1.0.0"}, nil)
mcp.AddTool(server, &mcp.Tool{Name: "get_weather", Description: "returns weather in the given city"}, weatherFunc)
_, err := server.Connect(t.Context(), serverTransport, nil)
// Create MCP ToolSet client
ts, err := mcptoolset.New(mcptoolset.Config{
Transport: clientTransport,
})
// Create LLM agent with MCP toolset
agent, err := llmagent.New(llmagent.Config{
Name: "weather_time_agent",
Model: newGeminiModel(t, modelName),
Description: "Agent to answer questions about the time and weather in a city.",
Instruction: "I can answer your questions about the time and weather in a city.",
Toolsets: []tool.Toolset{ ts },
})
// Run agent session with prompt
runner := newTestAgentRunner(t, agent)
events := runner.Run(t, "session1", "what is the weather in london?")
This example demonstrates the setup of an MCP server and client, creation of an LLM agent with MCP tools, and execution of a session that triggers the get_weather tool.
Mermaid Diagram: Structure and Workflow of set_test.go
flowchart TD
A[MCP Server Setup]
B[MCP Tools Registration]
C[MCP In-Memory Transport]
D[MCP Toolset Client]
E[LLM Agent Creation]
F[Agent Runner]
G[Run Agent Session]
H[Collect Session Events]
I[Verify Events]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
G --> H
H --> I
Description:
The flow begins with setting up an MCP server and registering tools.
An in-memory transport connects server and client.
MCP toolset client wraps the server tools.
LLM agent is created with the MCP toolset.
The agent runner executes an agent session with user input.
Session events generated during execution are collected.
Events are verified against expected outcomes.
References to Related Topics
For details on MCP Toolset Integration architecture and concepts, see MCP Toolset Integration.
For agent session management and event lifecycle, see Session Management and Agent Execution Runner.
For LLM agent configuration and lifecycle, see LLM Integration and Agents.
For the overall tooling framework and function tools wrapping Go functions, see Tooling System.
This file exemplifies the integration of MCP tools into an agent-driven workflow, demonstrating in-memory testing of tool invocation via LLM function calls and validating agent event sequences.