The Tool system is a core component of the tRPC-Agent-Go framework, enabling Agents to interact with external services and functions. The framework supports multiple tool types, including Function Tools and external tools integrated via the MCP (Model Context Protocol) standard.
Overview
π― Key Features
π§ Multiple Tool Types: Supports Function Tools and MCP standard tools.
π Streaming Responses: Supports both real-time streaming responses and normal responses.
β‘ Parallel Execution: Tool invocations support parallel execution to improve performance.
π MCP Protocol: Full support for STDIO, SSE, and Streamable HTTP transports.
π οΈ Configuration Support: Provides configuration options and filter support.
Core Concepts
π§ Tool
A Tool is an abstraction of a single capability that implements the tool.Tool interface. Each Tool provides specific functionality such as mathematical calculation, search, time query, etc.
A ToolSet is a collection of related tools that implements the tool.ToolSet interface. A ToolSet manages the lifecycle of tools, connections, and resource cleanup.
import"trpc.group/trpc-go/trpc-agent-go/tool/function"// 1. Define a tool function.funccalculator(ctxcontext.Context,reqstruct{Operationstring`json:"operation"`Afloat64`json:"a"`Bfloat64`json:"b"`})(map[string]interface{},error){switchreq.Operation{case"add":returnmap[string]interface{}{"result":req.A+req.B},nilcase"multiply":returnmap[string]interface{}{"result":req.A*req.B},nildefault:returnnil,fmt.Errorf("unsupported operation: %s",req.Operation)}}// 2. Create the tool.calculatorTool:=function.NewFunctionTool(calculator,function.WithName("calculator"),function.WithDescription("Perform mathematical operations."),)// 3. Integrate into an Agent.agent:=llmagent.New("math-assistant",llmagent.WithModel(model),llmagent.WithTools([]tool.Tool{calculatorTool}))
// 1. Define input and output structures.typeweatherInputstruct{Locationstring`json:"location"`}typeweatherOutputstruct{Weatherstring`json:"weather"`}// 2. Implement the streaming tool function.funcgetStreamableWeather(inputweatherInput)*tool.StreamReader{stream:=tool.NewStream(10)gofunc(){deferstream.Writer.Close()// Simulate progressively returning weather data.result:="Sunny, 25Β°C in "+input.Locationfori:=0;i<len(result);i++{chunk:=tool.StreamChunk{Content:weatherOutput{Weather:result[i:i+1],},Metadata:tool.Metadata{CreatedAt:time.Now()},}ifclosed:=stream.Writer.Send(chunk,nil);closed{break}time.Sleep(10*time.Millisecond)// Simulate latency.}}()returnstream.Reader}// 3. Create the streaming tool.weatherStreamTool:=function.NewStreamableFunctionTool[weatherInput,weatherOutput](getStreamableWeather,function.WithName("get_weather_stream"),function.WithDescription("Get weather information as a stream."),)// 4. Use the streaming tool.reader,err:=weatherStreamTool.StreamableCall(ctx,jsonArgs)iferr!=nil{returnerr}// Receive streaming data.for{chunk,err:=reader.Recv()iferr==io.EOF{break// End of stream.}iferr!=nil{returnerr}// Process each chunk.fmt.Printf("Received: %v\n",chunk.Content)}reader.Close()
Built-in Tools
DuckDuckGo Search Tool
The DuckDuckGo tool is based on the DuckDuckGo Instant Answer API and provides factual and encyclopedia-style information search capabilities.
import"trpc.group/trpc-go/trpc-agent-go/tool/duckduckgo"// Create a DuckDuckGo search tool.searchTool:=duckduckgo.NewTool()// Integrate into an Agent.searchAgent:=llmagent.New("search-assistant",llmagent.WithModel(model),llmagent.WithTools([]tool.Tool{searchTool}))
MCP (Model Context Protocol) is an open protocol that standardizes how applications provide context to LLMs. MCP tools are based on JSON-RPC 2.0 and provide standardized integration with external services for Agents.
MCP ToolSet Features:
π Unified interface: All MCP tools are created via mcp.NewMCPToolSet().
π Multiple transports: Supports STDIO, SSE, and Streamable HTTP.
π§ Tool filters: Supports including/excluding specific tools.
import"trpc.group/trpc-go/trpc-agent-go/tool/mcp"// Create an MCP ToolSet (STDIO example).mcpToolSet:=mcp.NewMCPToolSet(mcp.ConnectionConfig{Transport:"stdio",// Transport method.Command:"go",// Command to execute.Args:[]string{"run","./stdio_server/main.go"},Timeout:10*time.Second,},mcp.WithToolFilter(mcp.NewIncludeFilter("echo","add")),// Optional: tool filter.)// Integrate into an Agent.agent:=llmagent.New("mcp-assistant",llmagent.WithModel(model),llmagent.WithToolSets([]tool.ToolSet{mcpToolSet}))
Transport Configuration
MCP ToolSet supports three transports via the Transport field:
1. STDIO Transport
Communicates with external processes via standard input/output. Suitable for local scripts and CLI tools.
mcpToolSet:=mcp.NewMCPToolSet(mcp.ConnectionConfig{Transport:"streamable_http",// Use the full name.ServerURL:"http://localhost:3000/mcp",Timeout:10*time.Second,},)
Session Reconnection Support
MCP ToolSet supports automatic session reconnection to recover from server restarts or session expiration.
// SSE/Streamable HTTP transports support session reconnectionsseToolSet:=mcp.NewMCPToolSet(mcp.ConnectionConfig{Transport:"sse",ServerURL:"http://localhost:8080/sse",Timeout:10*time.Second,},mcp.WithSessionReconnect(3),// Enable session reconnection with max 3 attempts)
Reconnection Features:
π Auto Reconnect: Automatically recreates session when connection loss or expiration is detected
π― Independent Retries: Each tool call gets independent reconnection attempts
π‘οΈ Conservative Strategy: Only triggers reconnection for clear connection/session errors to avoid infinite loops
Agent Tool (AgentTool)
AgentTool lets you expose an existing Agent as a tool to be used by a parent Agent. Compared with a plain function tool, AgentTool provides:
β Reuse: Wrap complex Agent capabilities as a standard tool
π Streaming: Optionally forward the child Agentβs streaming events inline to the parent flow
π§ Control: Options to skip post-tool summarization and to enable/disable inner forwarding
import("trpc.group/trpc-go/trpc-agent-go/agent/llmagent""trpc.group/trpc-go/trpc-agent-go/model""trpc.group/trpc-go/trpc-agent-go/tool"agenttool"trpc.group/trpc-go/trpc-agent-go/tool/agent")// 1) Define a reusable child Agent (streaming recommended)mathAgent:=llmagent.New("math-specialist",llmagent.WithModel(modelInstance),llmagent.WithInstruction("You are a math specialist..."),llmagent.WithGenerationConfig(model.GenerationConfig{Stream:true}),)// 2) Wrap as an Agent toolmathTool:=agenttool.NewTool(mathAgent,agenttool.WithSkipSummarization(true),// opt-in: skip the outer summarization after tool.responseagenttool.WithStreamInner(true),// forward child Agent streaming events to parent flow)// 3) Use in parent Agentparent:=llmagent.New("assistant",llmagent.WithModel(modelInstance),llmagent.WithGenerationConfig(model.GenerationConfig{Stream:true}),llmagent.WithTools([]tool.Tool{mathTool}),)
Streaming Inner Forwarding
When WithStreamInner(true) is enabled, AgentTool forwards child Agent events to the parent flow as they happen:
Forwarded items are actual event.Event instances, carrying incremental text in choice.Delta.Content
To avoid duplication, the child Agentβs final full message is not forwarded again; it is aggregated into the final tool.response content for the next LLM turn (to satisfy providers requiring tool messages)
UI guidance: show forwarded child deltas; avoid printing the aggregated final tool.response content unless debugging
Example: Only show tool fragments when needed to avoid duplicates
import("trpc.group/trpc-go/trpc-agent-go/agent/llmagent""trpc.group/trpc-go/trpc-agent-go/tool/function""trpc.group/trpc-go/trpc-agent-go/tool/duckduckgo""trpc.group/trpc-go/trpc-agent-go/tool/mcp")// Create function tools.calculatorTool:=function.NewFunctionTool(calculator,function.WithName("calculator"),function.WithDescription("Perform basic mathematical operations."))timeTool:=function.NewFunctionTool(getCurrentTime,function.WithName("current_time"),function.WithDescription("Get the current time."))// Create a built-in tool.searchTool:=duckduckgo.NewTool()// Create MCP ToolSets (examples for different transports).stdioToolSet:=mcp.NewMCPToolSet(mcp.ConnectionConfig{Transport:"stdio",Command:"python",Args:[]string{"-m","my_mcp_server"},Timeout:10*time.Second,},)sseToolSet:=mcp.NewMCPToolSet(mcp.ConnectionConfig{Transport:"sse",ServerURL:"http://localhost:8080/sse",Timeout:10*time.Second,},)streamableToolSet:=mcp.NewMCPToolSet(mcp.ConnectionConfig{Transport:"streamable_http",ServerURL:"http://localhost:3000/mcp",Timeout:10*time.Second,},)// Create an Agent and integrate all tools.agent:=llmagent.New("ai-assistant",llmagent.WithModel(model),llmagent.WithInstruction("You are a helpful AI assistant that can use various tools to help users."),// Add single tools (Tool interface).llmagent.WithTools([]tool.Tool{calculatorTool,timeTool,searchTool,}),// Add ToolSets (ToolSet interface).llmagent.WithToolSets([]tool.ToolSet{stdioToolSet,sseToolSet,streamableToolSet}),)
# Enter the tool example directory.cdexamples/tool
gorun.
# Enter the MCP tool example directory. cdexamples/mcp_tool
# Start the external server.cdstreamalbe_server&&gorunmain.go&# Run the main program.gorunmain.go-model="deepseek-chat"
Summary
The Tool system provides rich extensibility for tRPC-Agent-Go, supporting Function Tools, the DuckDuckGo Search Tool, and MCP protocol tools.