tool.go
Overview
This file implements an adapter that integrates Model Context Protocol (MCP) tools into the agent tooling system. It defines a wrapper type that converts MCP tools into native tools conforming to the tool.Tool interface used by agents and large language models (LLMs). This allows agents to discover and invoke external MCP tools seamlessly as part of their toolsets.
The main responsibilities of this file include:
Converting MCP tool metadata into ADK-compatible tool declarations.
Managing MCP client sessions used to communicate with the MCP server.
Executing MCP tool calls on behalf of agents and handling the results or errors.
Providing implementations of the
tool.Toolinterface to expose MCP tools transparently.
This integration extends the Tooling System with MCP tools, enabling dynamic extension of agent capabilities through the MCP ecosystem.
Types and Functions
getSessionFunc
type getSessionFunc func(ctx context.Context) (*mcp.ClientSession, error)
Description: Function type used to obtain an MCP client session on demand.
Parameters:
ctx context.Context: Context for cancellation and deadlines.
Returns:
*mcp.ClientSession: The MCP client session.error: Any error encountered obtaining the session.
This function type is used internally to lazily initialize and retrieve the MCP session required to call MCP tools.
convertTool
func convertTool(t *mcp.Tool, getSessionFunc getSessionFunc) (tool.Tool, error)
Description: Converts an MCP tool descriptor into a native
tool.Toolimplementation that wraps the MCP tool.Parameters:
t *mcp.Tool: MCP tool metadata including name, description, input/output JSON schemas.getSessionFunc getSessionFunc: Function to obtain the MCP client session.
Returns:
tool.Tool: The wrapped MCP tool implementing thetool.Toolinterface.error: Any conversion error.
This function creates an instance of mcpTool that holds the MCP tool's name, description, and JSON schema for input/output validation, along with the session getter function.
mcpTool
type mcpTool struct {
name string
description string
funcDeclaration *genai.FunctionDeclaration
getSessionFunc getSessionFunc
}
Description: Concrete implementation of the
tool.Toolinterface wrapping an MCP tool.Fields:
name string: The MCP tool name.description string: Human-readable description of the tool.funcDeclaration *genai.FunctionDeclaration: Function declaration exposing the tool's interface to LLMs, including JSON schemas.getSessionFunc getSessionFunc: Function to obtain the MCP client session for tool invocation.
This struct acts as the adapter between MCP tools and the ADK tooling system.
Name() string
func (t *mcpTool) Name() string
Description: Returns the tool's name.
Returns:
string: Name of the tool.
Implements the tool.Tool interface method.
Description() string
func (t *mcpTool) Description() string
Description: Returns the tool's description.
Returns:
string: Human-readable description of the tool.
Implements the tool.Tool interface method.
IsLongRunning() bool
func (t *mcpTool) IsLongRunning() bool
Description: Indicates whether the tool performs long-running operations.
Returns:
bool: Always returnsfalsefor MCP tools here.
Implements the tool.Tool interface method. MCP tools are treated as short-lived calls.
ProcessRequest
func (t *mcpTool) ProcessRequest(ctx tool.Context, req *model.LLMRequest) error
Description: Processes the LLM request by packing the tool information into the request for the LLM to consume.
Parameters:
ctx tool.Context: The agent invocation context.req *model.LLMRequest: The LLM request being constructed.
Returns:
error: Any error encountered during processing.
This method calls a utility to pack the tool declaration into the LLM request, enabling the LLM to discover and invoke the tool.
Declaration() *genai.FunctionDeclaration
func (t *mcpTool) Declaration() *genai.FunctionDeclaration
Description: Returns the function declaration describing the tool's interface for the LLM.
Returns:
*genai.FunctionDeclaration: Contains the tool's name, description, and JSON schemas for input/output.
Used by the LLM tooling integration to register the MCP tool's callable interface.
Run
func (t *mcpTool) Run(ctx tool.Context, args any) (map[string]any, error)
Description: Executes the MCP tool with the given arguments, returning the result or an error.
Parameters:
ctx tool.Context: The agent invocation context (carries context.Context internally).args any: Arguments passed to the tool call, typically a map matching the input JSON schema.
Returns:
map[string]any: Result map containing the tool output under the"output"key.error: Any error encountered during tool execution or response processing.
Implementation Details:
Obtains the MCP client session via
getSessionFunc.Calls
session.CallToolwith the tool name and arguments.Checks for errors returned by the MCP tool call:
If
IsErroris true, aggregates textual error details from the response content.Returns an error with detailed messages if present.
If structured content is available in the response, returns it under
"output".Otherwise, concatenates all text content from the response and returns it as a string under
"output".If no text content is found, returns an error indicating empty response content.
This method encapsulates the MCP protocol call lifecycle and adapts the response to the agent tooling conventions.
Important Implementation Details
Session Management:
The MCP client session is managed externally and obtained via the injectedgetSessionFunc. This supports lazy initialization and caching of MCP sessions.Error Handling:
MCP tool call errors are converted into Go errors with detailed textual content extracted from the MCP response. This provides meaningful error diagnostics to the caller.Response Handling:
Supports both structured JSON content and plain text results, mapping either into a generic output map consumable by LLMs.Tool Declaration:
The tool's interface is exposed to LLMs via agenai.FunctionDeclarationwith JSON schemas that describe the expected input and output, enabling automatic validation and function call support.Interface Compliance:
ThemcpTooltype implements bothtoolinternal.FunctionToolandtoolinternal.RequestProcessorinterfaces, ensuring it integrates properly with the ADK tooling lifecycle.
Interactions with Other System Components
MCP Client Session (
mcp.ClientSession):
The file relies on the MCP client session to perform tool discovery and invocation over the MCP protocol.Agent Invocation Context (
tool.Context):
Carries contextual information and cancellation signals during tool execution.LLM Request (
model.LLMRequest):
MCP tools are packed into LLM requests for the LLM to be aware of their callable interface.Tooling System (
tool.ToolInterface):
Implements the standard tool interface required by the agent tooling framework to enable uniform tool invocation.MCP Tool Metadata (
mcp.Tool):
Converts MCP tool metadata into the ADK tooling system's function declarations.
This file is a crucial bridge between the MCP protocol toolset and the ADK agent tooling system, enabling agents to transparently invoke external MCP tools.
Usage Example
// Assume getSession is a function that returns a cached MCP client session.
mcpTool, err := convertTool(mcpToolMetadata, getSession)
if err != nil {
// Handle error
}
// Use the tool in an agent context.
ctx := toolContext // implementor of tool.Context
args := map[string]any{
"query": "example input",
}
result, err := mcpTool.Run(ctx, args)
if err != nil {
// Handle tool execution error
}
// Access output result
output := result["output"]
Structure Diagram
classDiagram
class mcpTool {
-name: string
-description: string
-funcDeclaration: genai.FunctionDeclaration
-getSessionFunc: getSessionFunc
+Name(): string
+Description(): string
+IsLongRunning(): bool
+ProcessRequest(tool.Context, *model.LLMRequest): error
+Declaration(): *genai.FunctionDeclaration
+Run(tool.Context, any): map[string]any, error
}
mcpTool ..|> toolinternal.FunctionTool
mcpTool ..|> toolinternal.RequestProcessor
References to Related Topics
For general concepts about tools and their integration with agents and LLMs, see the Tooling System topic.
For detailed context handling and lifecycle of agent invocation, refer to Agent Invocation Context and Agent Lifecycle and Callbacks.
The MCP Toolset Integration is a subtopic of the Tooling System and closely relates to LLM Integration and Agents for agent interactions.
For how tools declare their function signatures to LLMs, see Function Tools.