### Quickstart: Load Toolset with ToolboxClient Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/javascript-sdk/core/index.md A minimal example demonstrating how to initialize the ToolboxClient and load the toolset. Ensure your Toolbox service is running and accessible at the specified URL. This example uses ES Module syntax. ```javascript import { ToolboxClient } from '@toolbox-sdk/core'; const URL = 'http://127.0.0.1:5000'; // Replace with your Toolbox service URL const client = new ToolboxClient(URL); async function quickstart() { try { const tools = await client.loadToolset(); // Use tools } catch (error) { console.error("unable to load toolset:", error.message); } } quickstart(); ``` -------------------------------- ### Local Hugo Server Setup and Preview Source: https://github.com/googleapis/mcp-toolbox/blob/main/DEVELOPER.md Commands to preview documentation changes locally by installing dependencies, generating a search index, and starting the Hugo server in a development environment. ```bash cd .hugo npm ci hugo --environment development npx pagefind --site public --output-path static/pagefind hugo server ``` -------------------------------- ### Quickstart ADK Usage Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/tbadk/_index.md A minimal example demonstrating how to initialize the Toolbox client, load a tool, and invoke it with inputs. Ensure your Toolbox service is running and accessible. ```go package main import ( "context" "fmt" "github.com/googleapis/mcp-toolbox-sdk-go/tbadk" ) func quickstart() string { inputs := map[string]any{"location": "London"} client, err := tbadk.NewToolboxClient("http://localhost:5000") if err != nil { return fmt.Sprintln("Could not start Toolbox Client", err) } tool, err := client.LoadTool("get_weather", ctx) if err != nil { return fmt.Sprintln("Could not load Toolbox Tool", err) } // pass the tool.Context as ctx into the Run() method result, err := tool.Run(ctx, inputs) if err != nil { return fmt.Sprintln("Could not invoke tool", err) } return fmt.Sprintln(result["output"]) } func main() { fmt.Println(quickstart()) } ``` -------------------------------- ### Quickstart: Load and Invoke a Tool Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/core/_index.md A minimal Go example demonstrating how to initialize the Toolbox client, load a specific tool, and invoke it with input parameters. Assumes the Toolbox service is running locally. ```go package main import ( "context" "fmt" "github.com/googleapis/mcp-toolbox-sdk-go/core" ) func quickstart() string { ctx := context.Background() inputs := map[string]any{"location": "London"} client, err := core.NewToolboxClient("http://localhost:5000") if err != nil { return fmt.Sprintln("Could not start Toolbox Client", err) } tool, err := client.LoadTool("get_weather", ctx) if err != nil { return fmt.Sprintln("Could not load Toolbox Tool", err) } result, err := tool.Invoke(ctx, inputs) if err != nil { return fmt.Sprintln("Could not invoke tool", err) } return fmt.Sprintln(result) } func main() { fmt.Println(quickstart()) } ``` -------------------------------- ### Quickstart LangGraph Agent with Toolbox Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/python-sdk/langchain/index.md Initialize a Toolbox client, load tools, and create a LangGraph agent. This example demonstrates a basic interaction with the agent and prints messages. ```python from toolbox_langchain import ToolboxClient from langchain_google_vertexai import ChatVertexAI from langgraph.prebuilt import create_react_agent async with ToolboxClient("http://127.0.0.1:5000") as toolbox: tools = toolbox.load_toolset() model = ChatVertexAI(model="gemini-3-flash-preview") agent = create_react_agent(model, tools) prompt = "How's the weather today?" for s in agent.stream({"messages": [("user", prompt)]}, stream_mode="values"): message = s["messages"][-1] if isinstance(message, tuple): print(message) else: message.pretty_print() ``` -------------------------------- ### Quickstart LlamaIndex Agent with Toolbox Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/python-sdk/llamaindex/index.md A minimal example demonstrating how to load tools from the Toolbox and use them with a LlamaIndex agent powered by Google Generative AI. ```python import asyncio from llama_index.llms.google_genai import GoogleGenAI from llama_index.core.agent.workflow import AgentWorkflow from toolbox_llamaindex import ToolboxClient async def run_agent(): async with ToolboxClient("http://127.0.0.1:5000") as toolbox: tools = toolbox.load_toolset() vertex_model = GoogleGenAI( model="gemini-3-flash-preview", vertexai_config={"project": "project-id", "location": "us-central1"}, ) agent = AgentWorkflow.from_tools_or_functions( tools, llm=vertex_model, system_prompt="You are a helpful assistant.", ) response = await agent.run(user_msg="Get some response from the agent.") print(response) asyncio.run(run_agent()) ``` -------------------------------- ### Run Toolbox with Homebrew Source: https://github.com/googleapis/mcp-toolbox/blob/main/README.md Start the Toolbox server if installed via Homebrew. The 'toolbox' binary is available in the system path. ```sh toolbox --config "tools.yaml" ``` -------------------------------- ### Install Toolbox from Source Source: https://github.com/googleapis/mcp-toolbox/blob/main/README.md Compile and install the Toolbox from its source code. Requires the latest version of Go to be installed. ```sh go install github.com/googleapis/mcp-toolbox@v1.5.0 ``` -------------------------------- ### Load Toolset with LlamaIndex SDK Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/introduction/_index.md Load tools using the Toolbox LlamaIndex SDK with this example. Ensure the SDK is installed. ```python from toolbox_llamaindex import ToolboxClient # update the url to point to your server async with ToolboxClient("http://127.0.0.1:5000") as client: # these tools can be passed to your application tools = client.load_toolset() ``` -------------------------------- ### ADK Agent Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/local_quickstart_js.md Create and run an ADK agent that loads tools from MCP Toolbox. Ensure you have installed the necessary dependencies. ```js import { Agent } from "@google/adk"; import { GoogleSearchTool } from "@google/adk/tools"; // Initialize the ADK agent const agent = new Agent({ tools: [ new GoogleSearchTool({ apiKey: process.env.GOOGLE_API_KEY, }), ], }); // Define the prompt for the agent const prompt = "Search for the latest advancements in renewable energy."; // Run the agent async function runADKAgent() { const result = await agent.run(prompt); console.log(result.text()); } runADKAgent(); ``` -------------------------------- ### Tool configuration example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/looker/tools/looker-get-explores.md A YAML configuration example for defining the looker-get-explores tool. ```yaml kind: tool name: get_explores type: looker-get-explores source: looker-source description: | This tool retrieves a list of explores defined within a specific LookML model. Explores represent a curated view of your data, typically joining several tables together to allow for focused analysis on a particular subject area. The output provides details like the explore's `name` and `label`. Parameters: - model_name (required): The name of the LookML model, obtained from `get_models`. ``` -------------------------------- ### Install BigQuery Client Library Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/bigquery/samples/local_quickstart.md Install the necessary Python client library for interacting with Google BigQuery. ```bash pip install google-cloud-bigquery ``` -------------------------------- ### Install MySQL Extension Source: https://github.com/googleapis/mcp-toolbox/blob/main/MCP-TOOLBOX-EXTENSION.md Install the Gemini CLI extension for connecting to MySQL instances not managed by Cloud SQL. The configuration guide provides detailed setup instructions. ```bash gemini extensions install https://github.com/gemini-cli-extensions/mysql ``` -------------------------------- ### Install Firestore Native Extension Source: https://github.com/googleapis/mcp-toolbox/blob/main/MCP-TOOLBOX-EXTENSION.md Use this command to install the Gemini CLI extension for querying Firestore in Native Mode. Refer to the configuration guide for setup details. ```bash gemini extensions install https://github.com/gemini-cli-extensions/firestore-native ``` -------------------------------- ### Complete Example with Authentication Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/python-sdk/llamaindex/index.md A full example demonstrating loading a tool, adding an authentication token getter, and calling the tool. ```python import asyncio from toolbox_llamaindex import ToolboxClient async def get_auth_token(): # ... Logic to retrieve ID token (e.g., from local storage, OAuth flow) # This example just returns a placeholder. Replace with your actual token retrieval. return "YOUR_ID_TOKEN" # Placeholder async with ToolboxClient("http://127.0.0.1:5000") as toolbox: tool = toolbox.load_tool("my-tool") auth_tool = tool.add_auth_token_getter("my_auth", get_auth_token) result = auth_tool.call(input="some input") print(result) ``` -------------------------------- ### Install ADK Package Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/tbadk/_index.md Install the ADK package using go get. Ensure you are using Go version 1.24.4 or higher. ```bash go get github.com/googleapis/mcp-toolbox-sdk-go/tbadk ``` -------------------------------- ### Initialize Toolbox Client Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/javascript-sdk/adk/index.md Minimal example demonstrating how to import the client, connect to a service URL, and load a toolset. ```javascript import { ToolboxClient } from '@toolbox-sdk/adk'; const URL = 'http://127.0.0.1:5000'; // Replace with your Toolbox service URL const client = new ToolboxClient(URL); async function quickstart() { try { const tools = await client.loadToolset(); // Use tools } catch (error) { console.error("unable to load toolset:", error.message); } } quickstart(); ``` ```javascript import { ToolboxClient } from '@toolbox-sdk/adk'; // Replace with the actual URL where your Toolbox service is running const URL = 'http://127.0.0.1:5000'; let client = new ToolboxClient(URL); const tools = await client.loadToolset(); // Use the client and tools as per requirement ``` -------------------------------- ### Install Looker Extension Source: https://github.com/googleapis/mcp-toolbox/blob/main/MCP-TOOLBOX-EXTENSION.md This command installs the Gemini CLI extension for querying Looker instances. Check the provided configuration link for setup and usage information. ```bash gemini extensions install https://github.com/gemini-cli-extensions/looker ``` -------------------------------- ### Multi-tenant schema setup Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/cockroachdb/tools/cockroachdb-list-schemas.md Example of creating separate schemas for different tenants. ```sql -- Create schema per tenant CREATE SCHEMA tenant_acme; CREATE SCHEMA tenant_globex; -- Create same table structure in each schema CREATE TABLE tenant_acme.orders (...); CREATE TABLE tenant_globex.orders (...); ``` -------------------------------- ### Complete Authentication Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/javascript-sdk/core/index.md This example demonstrates the full process: importing the client, defining a token retriever, initializing the client, loading a tool with authentication, and invoking the authenticated tool. Ensure the token retriever logic is correctly implemented. ```javascript import { ToolboxClient } from '@toolbox-sdk/core'; async function getAuthToken() { // ... Logic to retrieve ID token (e.g., from local storage, OAuth flow) // This example just returns a placeholder. Replace with your actual token retrieval. return "YOUR_ID_TOKEN" // Placeholder } const URL = 'http://127.0.0.1:5000'; let client = new ToolboxClient(URL); const tool = await client.loadTool("my-tool"); const authTool = tool.addAuthTokenGetters({"my_auth": getAuthToken}); const result = await authTool({input:"some input"}); console.log(result); ``` -------------------------------- ### Install PostgreSQL Extension Source: https://github.com/googleapis/mcp-toolbox/blob/main/MCP-TOOLBOX-EXTENSION.md Use this command to install the Gemini CLI extension for PostgreSQL. For Google Cloud managed PostgreSQL, consider the `cloud-sql-postgresql` or `alloydb` extensions. Refer to the configuration link for setup details. ```bash gemini extensions install https://github.com/gemini-cli-extensions/postgres ``` -------------------------------- ### Run Server with Prebuilt and Custom Tools Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/reference/cli.md Launch the Toolbox server with a combination of a custom configuration file and a prebuilt toolset. ```bash # Server with prebuilt + custom tools configurations ./toolbox --config tools.yaml --prebuilt alloydb-postgres ``` -------------------------------- ### Connect and Invoke a Tool Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/java-sdk/core/index.md Minimal example demonstrating client instantiation and tool invocation. ```java import com.google.cloud.mcp.McpToolboxClient; import java.util.Map; public class App { public static void main(String[] args) { // 1. Create the Client McpToolboxClient client = McpToolboxClient.builder() .baseUrl("https://my-toolbox-service.a.run.app/mcp") .build(); // 2. Invoke a Tool client.invokeTool("get-toy-price", Map.of("description", "plush dinosaur")) .thenAccept(result -> { // Pick the first item from the response. System.out.println("Tool Output: " + result.content().get(0).text()); }) .exceptionally(ex -> { System.err.println("Error: " + ex.getMessage()); return null; }) .join(); // Wait for completion } } ``` -------------------------------- ### Run MCP Inspector Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/mcp_quickstart/_index.md Execute this command in your terminal to start the MCP Inspector. You will be prompted to install the inspector package. ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Initialize Client with Custom HTTP Client Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/core/_index.md Demonstrates initializing the Toolbox client with a custom http.Client. The responsibility for managing the lifecycle of the provided session lies with the user. ```go core.NewToolboxClient(URL, core.WithHTTPClient(myClient)) ``` -------------------------------- ### Install SQL Server Extension Source: https://github.com/googleapis/mcp-toolbox/blob/main/MCP-TOOLBOX-EXTENSION.md Install the Gemini CLI extension for SQL Server. If you need to connect to Google Cloud managed SQL Server, use the `cloud-sql-sqlserver` extension. The configuration guide is available via the provided link. ```bash gemini extensions install https://github.com/gemini-cli-extensions/sql-server ``` -------------------------------- ### Initialize Database and User Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/quickstart/shared/database_setup.md SQL commands to create a dedicated user and database with appropriate permissions. ```sql CREATE USER toolbox_user WITH PASSWORD 'my-password'; CREATE DATABASE toolbox_db; GRANT ALL PRIVILEGES ON DATABASE toolbox_db TO toolbox_user; ALTER DATABASE toolbox_db OWNER TO toolbox_user; ``` -------------------------------- ### Complete Authentication Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/java-sdk/core/index.md A full example demonstrating how to initialize the McpToolboxClient, define a token getter, attach it to a tool, and execute the tool. The auth source name 'my_auth' must match the tool's configuration. ```java import com.google.cloud.mcp.McpToolboxClient; import com.google.cloud.mcp.AuthTokenGetter; import java.util.Map; import java.util.concurrent.CompletableFuture; public class AuthExample { public static void main(String[] args) { // 1. Define your token retrieval logic AuthTokenGetter tokenGetter = () -> { // Logic to retrieve ID token (e.g., from local storage, OAuth flow) return CompletableFuture.completedFuture("YOUR_ID_TOKEN"); }; // 2. Initialize the client McpToolboxClient client = McpToolboxClient.builder() .baseUrl("http://127.0.0.1:5000/mcp") .build(); // 3. Load tool, attach auth, and execute client.loadTool("my-tool") .thenCompose(tool -> { // "my_auth" must match the name in the tool's authSource config tool.addAuthTokenGetter("my_auth", tokenGetter); return tool.execute(Map.of("input", "some input")); }) .thenAccept(result -> { // Pick the first item from the response. System.out.println(result.content().get(0).text()); }) .join(); } } ``` -------------------------------- ### Show Regions for a Database Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/cockroachdb/tools/cockroachdb-execute-sql.md Example of executing a SQL statement to list the regions configured for the 'defaultdb' database in a multi-region setup. ```json { "sql": "SHOW REGIONS FROM DATABASE defaultdb" } ``` -------------------------------- ### Complete Authentication Workflow Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/javascript-sdk/adk/index.md A full example demonstrating the initialization of the client, registration of a token retriever, and execution of an authenticated tool. ```javascript import { ToolboxClient } from '@toolbox-sdk/adk'; async function getAuthToken() { // ... Logic to retrieve ID token (e.g., from local storage, OAuth flow) // This example just returns a placeholder. Replace with your actual token retrieval. return "YOUR_ID_TOKEN" // Placeholder } const URL = 'http://127.0.0.1:5000'; let client = new ToolboxClient(URL); const tool = await client.loadTool("my-tool"); const authTool = tool.addAuthTokenGetters({"my_auth": getAuthToken}); const result = await authTool.runAsync(args: {input:"some input"}); console.log(result); ``` -------------------------------- ### GoogleGenAI Agent Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/local_quickstart_js.md Create and run a GoogleGenAI agent that loads tools from MCP Toolbox. Ensure you have installed the necessary dependencies. ```js import { GoogleGenerativeAI } from "@google/generative-ai"; import { GoogleSearchTool } from "@google/generative-ai/tools"; // Initialize the Generative AI client const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY); // Define the tools the agent can use const tools = [ new GoogleSearchTool({ apiKey: process.env.GOOGLE_API_KEY, }), ]; // Create a model that can use tools const model = genAI.getGenerativeModel({ model: "gemini-pro", tools: tools, }); // Generate content using the model and tools async function runAgent() { const prompt = "What is the latest news about AI?"; const result = await model.generateContent({ prompt, }); const response = result.response; console.log(response.text()); } runAgent(); ``` -------------------------------- ### Redis Tool Configuration Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/redis/tools/redis-tool.md This example demonstrates the configuration of a Redis tool, including its name, type, source, description, commands, and parameters. It shows how to use templated parameters for dynamic command arguments. ```yaml kind: tool name: user_data_tool type: redis source: my-redis-instance description: | Use this tool to interact with user data stored in Redis. It can set, retrieve, and delete user-specific information. commands: - [SADD, userNames, $userNames] # Array will be flattened into multiple arguments. - [GET, $userId] parameters: - name: userId type: string description: The unique identifier for the user. - name: userNames type: array description: The user names to be set. ``` -------------------------------- ### GenkitJS Agent Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/local_quickstart_js.md Create and run a GenkitJS agent that loads tools from MCP Toolbox. Ensure you have installed the necessary dependencies. ```js import { defineAgent } from "@genkit-ai/core"; import { google } from "@genkit-ai/google-genai"; import { searchTool } from "@genkit-ai/wikipedia"; // Define the agent defineAgent({ name: "my-agent", tools: [searchTool], stream: [google.text({ model: "gemini-1.5-flash", temperature: 0.7, topK: 40, topP: 1, })], // Define the prompt for the agent prompt: "You are a helpful assistant. Use the provided tools to answer the user's question.\n\n{{.history}}\n\nUser: {{.input}}\nAI: " }); // Example of how to use the agent (this part would typically be in another file) // import { runGenkitAgent } from "@genkit-ai/core"; // async function main() { // const response = await runGenkitAgent("my-agent", { // input: "What is the capital of France?", // }); // console.log(response.text()); // } // main(); ``` -------------------------------- ### Launch Toolbox UI Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/configuration/toolbox-ui/index.md Use the --ui flag to start the interactive web interface. ```sh ./toolbox --ui ``` -------------------------------- ### LangChain Agent Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/local_quickstart_js.md Create and run a LangChain agent that loads tools from MCP Toolbox. Ensure you have installed the necessary dependencies. ```js import { ChatGoogleGenerativeAI } from "@langchain/google-genai"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { createToolCallingAgent, AgentExecutor } from "langchain/agents"; import { TavilySearchResults } from "@langchain/community/tools/retrieval"; import { formatTools } from "langchain/tools"; // Initialize the LLM const llm = new ChatGoogleGenerativeAI({ apiKey: process.env.GOOGLE_API_KEY, }); // Define the tools the agent can use const tools = [ new TavilySearchResults({ apiKey: process.env.TAVILY_API_KEY, }), ]; // Create the agent const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant."], ["human", "{input}"], ["ai", "{agent_scratchpad}"], ]); const agent = await createToolCallingAgent({ llm, tools, prompt, }); // Create the agent executor const agentExecutor = new AgentExecutor({ agent, tools, }); // Run the agent const result = await agentExecutor.invoke({ input: "What is the weather in San Francisco?", }); console.log(result); ``` -------------------------------- ### Run MCP Toolbox Server Source: https://github.com/googleapis/mcp-toolbox/blob/main/AGENTS.md Starts the MCP Toolbox server. It listens on port 5000 by default. Ensure Go 1.23+ is installed. ```bash go run . ``` -------------------------------- ### Load Tools using Python SDK Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/introduction/_index.md Example of loading tools into an application using the Toolbox Core SDK for Python. Ensure the SDK is installed. ```python from toolbox_core import ToolboxClient ``` -------------------------------- ### Run Server with Multiple Prebuilt Tools Configurations Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/reference/cli.md Configure the Toolbox server to load multiple prebuilt tool configurations, either by comma-separating them or using the flag multiple times. ```bash # Server with multiple prebuilt tools configurations ./toolbox --prebuilt alloydb-postgres,alloydb-postgres-admin # OR ./toolbox --prebuilt alloydb-postgres --prebuilt alloydb-postgres-admin ``` -------------------------------- ### Complete Authentication Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/python-sdk/core/index.md A full example demonstrating how to define a token retriever, load a tool with authentication, and invoke it. Note that the auth token getter replaces client headers with the same name followed by '_token'. ```python import asyncio from toolbox_core import ToolboxClient async def get_auth_token(): # ... Logic to retrieve ID token (e.g., from local storage, OAuth flow) # This example just returns a placeholder. Replace with your actual token retrieval. return "YOUR_ID_TOKEN" # Placeholder async with ToolboxClient("http://127.0.0.1:5000") as toolbox: tool = await toolbox.load_tool("my-tool") auth_tool = tool.add_auth_token_getters({"my_auth": get_auth_token}) result = auth_tool(input="some input") print(result) ``` -------------------------------- ### Run MCP Toolbox with Help Source: https://github.com/googleapis/mcp-toolbox/blob/main/CLAUDE.md Displays help information for the MCP Toolbox CLI. Ensure Go 1.23+ is installed. ```bash go run . --help ``` -------------------------------- ### ADK Go Integration Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/tbadk/_index.md A complete example of integrating the MCP Toolbox Go SDK with ADK Go using the tbadk package. It demonstrates initializing the toolbox client, creating a Gemini model, setting up an LLM agent, and running a query through a session. ```go //This sample contains a complete example on how to integrate MCP Toolbox Go SDK with ADK Go using the tbadk package. package main import ( "context" "fmt" "log" "os" "github.com/googleapis/mcp-toolbox-sdk-go/tbadk" "google.golang.org/adk/agent" "google.golang.org/adk/agent/llmagent" "google.golang.org/adk/model/gemini" "google.golang.org/adk/runner" "google.golang.org/adk/session" "google.golang.org/adk/tool" "google.golang.org/genai" ) func main() { genaiKey := os.Getenv("GEMINI_API_KEY") toolboxURL := "http://localhost:5000" ctx := context.Background() // Initialize MCP Toolbox client toolboxClient, err := tbadk.NewToolboxClient(toolboxURL) if err != nil { log.Fatalf("Failed to create MCP Toolbox client: %v", err) } toolsetName := "my-toolset" toolset, err := toolboxClient.LoadToolset(toolsetName, ctx) if err != nil { log.Fatalf("Failed to load MCP toolset '%s': %v\nMake sure your Toolbox server is running.", toolsetName, err) } // Create Gemini model model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{ APIKey: genaiKey, }) if err != nil { log.Fatalf("Failed to create model: %v", err) } tools := make([]tool.Tool, len(toolset)) for i := range toolset { tools[i] = &toolset[i] } llmagent, err := llmagent.New(llmagent.Config{ Name: "hotel_assistant", Model: model, Description: "Agent to answer questions about hotels.", Tools: tools, }) if err != nil { log.Fatalf("Failed to create agent: %v", err) } appName := "hotel_assistant" userID := "user-123" sessionService := session.InMemoryService() resp, err := sessionService.Create(ctx, &session.CreateRequest{ AppName: appName, UserID: userID, }) if err != nil { log.Fatalf("Failed to create the session service: %v", err) } session := resp.Session r, err := runner.New(runner.Config{ AppName: appName, Agent: llmagent, SessionService: sessionService, }) if err != nil { log.Fatalf("Failed to create runner: %v", err) } query := "Find hotels with Basel in its name." fmt.Println(query) userMsg := genai.NewContentFromText(query, genai.RoleUser) streamingMode := agent.StreamingModeSSE for event, err := range r.Run(ctx, userID, session.ID(), userMsg, agent.RunConfig{ StreamingMode: streamingMode, }) { if err != nil { fmt.Printf("\nAGENT_ERROR: %v\n", err) } else { if event.LLMResponse.Content != nil { for _, p := range event.LLMResponse.Content.Parts { if streamingMode != agent.StreamingModeSSE || event.LLMResponse.Partial { fmt.Print(p.Text) } } } } } } fmt.Println() } ``` -------------------------------- ### List Vector Specifications Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/cloud-sql-pg/tools/vector-assist-list-specs.md This YAML configuration defines a tool to list vector specifications for a given table and column. Ensure the 'vector_assist' extension is installed in your PostgreSQL database. ```yaml kind: tool name: list_specs type: vector-assist-list-specs source: my-database-source description: "This tool lists all defined vector specifications for a given table and column name. Use this tool to list vector specifications which were created in the context of the vector assist tools." ``` -------------------------------- ### Configure and Initialize Agent Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/bigquery/samples/local_quickstart.md Configure the agent with a model, name, description, instructions, and tools. Then, initialize the session and artifact services for running the agent. ```python from agent import Agent from services import InMemorySessionService, InMemoryArtifactService, Runner # --- Configure the Agent --- root_agent = Agent( model='gemini-2.0-flash-001', name='hotel_agent', description='A helpful AI assistant that can search and book hotels.', instruction=prompt, tools=[toolset], # Pass the loaded toolset ) # --- Initialize Services for Running the Agent --- session_service = InMemorySessionService() artifacts_service = InMemoryArtifactService() runner = Runner( app_name='hotel_agent', agent=root_agent, artifact_service=artifacts_service, session_service=session_service, ) ``` -------------------------------- ### Okta OIDC Configuration for Generic Auth Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/configuration/authentication/generic.md Example configuration for using Okta as the identity provider with the generic authentication service. Adjust the audience and authorizationServer URL according to your Okta setup. ```yaml kind: authService name: okta-auth type: generic audience: api://default # Or your custom Okta audience authorizationServer: https://your-subdomain.okta.com/oauth2/default mcpEnabled: true scopesRequired: - openid - profile ``` -------------------------------- ### Initialize Toolbox Client in Go Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/introduction/_index.md This Go snippet demonstrates how to initialize the Toolbox client using the Go Core SDK. It includes setting up the context and handling potential errors during client creation. Ensure the SDK is installed. ```go package main import ( "context" "log" "github.com/googleapis/mcp-toolbox-sdk-go/core" ) func main() { // update the url to point to your server URL := "http://127.0.0.1:5000" ctx := context.Background() client, err := core.NewToolboxClient(URL) if err != nil { log.Fatalf("Failed to create Toolbox client: %v", err) } ``` -------------------------------- ### Run Basic Server with Custom Port Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/reference/cli.md Start the Toolbox server using a custom configuration file and specifying a non-default port. ```bash # Basic server with custom port configuration ./toolbox --config "tools.yaml" --port 8080 ``` -------------------------------- ### Good Tool Definition Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/reference/style-guide.md Demonstrates a well-formed tool definition including name, description, and parameters. The description guides the agent and avoids including input descriptions or imperative commands. ```yaml name: get_customer_profile description: Fetches a customer profile. Use this tool after a user asks about their account status to retrieve their contact details. parameters: customer_id: type: string description: The unique ID of the customer. ``` -------------------------------- ### Configure postgres-database-overview tool Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/postgres/tools/postgres-database-overview.md Example YAML configuration for defining the postgres-database-overview tool within a project. ```yaml kind: tool name: database_overview type: postgres-database-overview source: cloudsql-pg-source description: | fetches the current state of the PostgreSQL server. It returns the postgres version, whether it's a replica, uptime duration, maximum connection limit, number of current connections, number of active connections and the percentage of connections in use. ``` -------------------------------- ### AI Assistant Prompt Example for Listing Tables Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/cockroachdb/tools/cockroachdb-list-tables.md This YAML configuration shows how to integrate the list_tables tool with an AI assistant. It specifies the tool type, source database, and a detailed description to guide the AI. ```yaml tools: list_tables: type: cockroachdb-list-tables source: my_cockroachdb description: | Lists all tables in the database with detailed schema information. Use this tool to understand: - What tables exist - What columns each table has - Data types and constraints - Relationships between tables (foreign keys) - Available indexes Always call this tool before generating SQL queries to ensure you use correct table and column names. ``` -------------------------------- ### Initialize Core Go SDK and Load Toolset Source: https://github.com/googleapis/mcp-toolbox/blob/main/README.md Initializes the Toolbox Go Core client and loads a set of tools from a specified URL. Ensure error handling is implemented for production use. ```go package main import ( "github.com/googleapis/mcp-toolbox-sdk-go/core" "context" ) func main() { // Make sure to add the error checks // update the url to point to your server URL := "http://127.0.0.1:5000"; ctx := context.Background() client, err := core.NewToolboxClient(URL) // Framework agnostic tools tools, err := client.LoadToolset("toolsetName", ctx) } ``` -------------------------------- ### HTTP Tool Configuration Example Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/http/tools/http-tool.md This YAML configuration defines an HTTP tool named 'my-http-tool' for making GET requests. It specifies the source, path, method, authentication requirements, query parameters, request body template, body parameters, and headers. ```yaml kind: tool name: my-http-tool type: http source: my-http-source method: GET path: /search description: some description authRequired: - my-google-auth-service - other-auth-service queryParams: - name: country description: some description type: string requestBody: | { "age": {{.age}}, "city": "{{.city}}" } bodyParams: - name: age description: age number type: integer - name: city description: city string type: string headers: Authorization: API_KEY Content-Type: application/json headerParams: - name: Language description: language string type: string ``` -------------------------------- ### Load Tools with Go Core SDK Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/introduction/_index.md Demonstrates loading tools using the framework-agnostic Go Core SDK. Ensure error checks are in place and update the URL to your server. ```go package main import ( "context" "encoding/json" "log" "github.com/googleapis/mcp-toolbox-sdk-go/core" "github.com/tmc/langchaingo/llms" ) func main() { // Make sure to add the error checks // update the url to point to your server URL := "http://127.0.0.1:5000" ctx := context.Background() client, err := core.NewToolboxClient(URL) if err != nil { log.Fatalf("Failed to create Toolbox client: %v", err) } // Framework agnostic tool tool, err := client.LoadTool("toolName", ctx) if err != nil { log.Fatalf("Failed to load tools: %v", err) } // Fetch the tool's input schema inputschema, err := tool.InputSchema() if err != nil { log.Fatalf("Failed to fetch inputSchema: %v", err) } var paramsSchema map[string]any _ = json.Unmarshal(inputschema, ¶msSchema) // Use this tool with LangChainGo langChainTool := llms.Tool{ Type: "function", Function: &llms.FunctionDefinition{ Name: tool.Name(), Description: tool.Description(), Parameters: paramsSchema, }, } } ``` -------------------------------- ### Complete Authentication Workflow Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/python-sdk/langchain/index.md A full example demonstrating token retrieval, tool loading, authentication attachment, and tool invocation. ```python import asyncio from toolbox_langchain import ToolboxClient async def get_auth_token(): # ... Logic to retrieve ID token (e.g., from local storage, OAuth flow) # This example just returns a placeholder. Replace with your actual token retrieval. return "YOUR_ID_TOKEN" # Placeholder async with ToolboxClient("http://127.0.0.1:5000") as toolbox: tool = toolbox.load_tool("my-tool") auth_tool = tool.add_auth_token_getter("my_auth", get_auth_token) result = auth_tool.invoke({"input": "some input"}) print(result) ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/googleapis/mcp-toolbox/blob/main/AGENTS.md Install project dependencies using npm ci. This ensures all required packages are installed in a clean state. ```bash npm ci ``` -------------------------------- ### Install ADK Dependencies Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/local_quickstart_js.md Install the ADK package. ```bash npm install @google/adk ``` -------------------------------- ### Execute Agent Script Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/bigquery/samples/local_quickstart.md Run the Python script to execute the agent and observe its output. This command initiates the local quickstart process. ```shell python hotel_agent.py ``` -------------------------------- ### Install MCP Toolbox ADK Package Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/colab_quickstart.ipynb Install the MCP Toolbox package for ADK. This command installs the necessary libraries to use ADK with the toolbox. ```bash ! pip install google-adk[toolbox] --quiet ``` -------------------------------- ### Load and Run a Tool Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/tbadk/_index.md Load a tool by its name and invoke it with input parameters. Ensure the Toolbox service is running and accessible. ```go tool, err = client.LoadTool("my-tool", ctx) inputs := map[string]any{"location": "London"} // Pass the tool.Context as ctx to the Run() function result, err := tool.Run(ctx, inputs) ``` -------------------------------- ### Example tools.yaml Configuration Source: https://github.com/googleapis/mcp-toolbox/blob/main/npm/server/README.md Defines database sources and custom SQL tools for the toolbox. This file is automatically loaded or can be specified with the --config flag. ```yaml sources: my-pg-source: kind: postgres host: 127.0.0.1 port: 5432 database: toolbox_db user: postgres password: password tools: search-hotels-by-name: kind: postgres-sql source: my-pg-source description: Search for hotels based on name. parameters: - name: name type: string description: The name of the hotel. statement: SELECT * FROM hotels WHERE name ILIKE '%' || $1 || '%'; prompts: code-review: description: "Asks the LLM to analyze code quality and suggest improvements." messages: - role: "user" content: "Please review the following code for quality, correctness, and potential improvements: {{.code}}" arguments: - name: "code" description: "The code to review" required: true ``` -------------------------------- ### Install MCP Toolbox SDK Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/python-sdk/adk/index.md Install the MCP Toolbox SDK for ADK applications using pip. This command installs the necessary package and its dependencies for ADK integration. ```bash pip install google-adk[toolbox] ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/integrations/alloydb/samples/ai-nl/alloydb_ai_nl.ipynb Installs necessary libraries including the AlloyDB Python connector, SQLAlchemy, and Vertex AI. Use --quiet for silent installation. ```python %pip install \ google-cloud-alloydb-connector[asyncpg]==1.4.0 \ sqlalchemy==2.0.36 \ vertexai==1.70.0 \ asyncio==3.4.3 \ greenlet==3.1.1 \ --quiet ``` -------------------------------- ### Integrate MCP Toolbox with Genkit Go Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/tbgenkit/_index.md A complete example demonstrating how to initialize a toolbox client, convert tools, and use them within a Genkit generation flow. ```go //This sample contains a complete example on how to integrate MCP Toolbox Go SDK with Genkit Go using the tbgenkit package. package main import ( "context" "fmt" "log" "github.com/googleapis/mcp-toolbox-sdk-go/core" "github.com/googleapis/mcp-toolbox-sdk-go/tbgenkit" "github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/genkit" "github.com/firebase/genkit/go/plugins/googlegenai" ) func main() { ctx := context.Background() toolboxClient, err := core.NewToolboxClient("http://127.0.0.1:5000") if err != nil { log.Fatalf("Failed to create Toolbox client: %v", err) } // Load the tools using the MCP Toolbox SDK. tools, err := toolboxClient.LoadToolset("my-toolset", ctx) if err != nil { log.Fatalf("Failed to load tools: %v\nMake sure your Toolbox server is running and the tool is configured.", err) } // Initialize genkit g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}), genkit.WithDefaultModel("googleai/gemini-1.5-flash"), ) // Convert your tool to a Genkit tool. genkitTools := make([]ai.Tool, len(tools)) for i, tool := range tools { newTool, err := tbgenkit.ToGenkitTool(tool, g) if err != nil { log.Fatalf("Failed to convert tool: %v\n", err) } genkitTools[i] = newTool } toolRefs := make([]ai.ToolRef, len(genkitTools)) for i, tool := range genkitTools { toolRefs[i] = tool } // Generate llm response using prompts and tools. resp, err := genkit.Generate(ctx, g, ai.WithPrompt("Find hotels in Basel with Basel in it's name."), ai.WithTools(toolRefs...), ) if err != nil { log.Fatalf("%v\n", err) } fmt.Println(resp.Text()) } ``` -------------------------------- ### Install GoogleGenAI Dependencies Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/getting-started/local_quickstart_js.md Install the Google GenAI SDK package. ```bash npm install @google/genai ``` -------------------------------- ### Integrate Toolbox with Google GenAI Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/connect-to/toolbox-sdks/go-sdk/core/_index.md This sample demonstrates integration with the standard Google GenAI framework. It shows how to convert Toolbox tools to GenAI format, set up the GenAI client, load tools, and process function calls. ```go // This sample demonstrates integration with the standard Google GenAI framework. package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/googleapis/mcp-toolbox-sdk-go/core" "google.golang.org/genai" ) // ConvertToGenaiTool translates a ToolboxTool into the genai.FunctionDeclaration format. func ConvertToGenaiTool(toolboxTool *core.ToolboxTool) *genai.Tool { inputschema, err := toolboxTool.InputSchema() if err != nil { return &genai.Tool{} } var schema *genai.Schema _ = json.Unmarshal(inputschema, &schema) // First, create the function declaration. funcDeclaration := &genai.FunctionDeclaration{ Name: toolboxTool.Name(), Description: toolboxTool.Description(), Parameters: schema, } // Then, wrap the function declaration in a genai.Tool struct. return &genai.Tool{ FunctionDeclarations: []*genai.FunctionDeclaration{funcDeclaration}, } } // printResponse extracts and prints the relevant parts of the model's response. func printResponse(resp *genai.GenerateContentResponse) { for _, cand := range resp.Candidates { if cand.Content != nil { for _, part := range cand.Content.Parts { fmt.Println(part.Text) } } } } func main() { // Setup ctx := context.Background() apiKey := os.Getenv("GOOGLE_API_KEY") toolboxURL := "http://localhost:5000" // Initialize the Google GenAI client using the explicit ClientConfig. client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: apiKey, }) if err != nil { log.Fatalf("Failed to create Google GenAI client: %v", err) } // Initialize the MCP Toolbox client. toolboxClient, err := core.NewToolboxClient(toolboxURL) if err != nil { log.Fatalf("Failed to create Toolbox client: %v", err) } // Load the tools using the MCP Toolbox SDK. tools, err := toolboxClient.LoadToolset("my-toolset", ctx) if err != nil { log.Fatalf("Failed to load tools: %v\nMake sure your Toolbox server is running and the tool is configured.", err) } genAITools := make([]*genai.Tool, len(tools)) tolsMap := make(map[string]*core.ToolboxTool, len(tools)) for i, tool := range tools { // Convert the tools into usable format genAITools[i] = ConvertToGenaiTool(tool) // Add tool to a map for lookup later tolsMap[tool.Name()] = tool } // Set up the generative model with the available tool. modelName := "gemini-2.0-flash" query := "Find hotels in Basel with Basel in it\'s name and share the names with me" // Create the initial content prompt for the model. contents := []*genai.Content{ genai.NewContentFromText(query, genai.RoleUser), } config := &genai.GenerateContentConfig{ Tools: genAITools, ToolConfig: &genai.ToolConfig{ FunctionCallingConfig: &genai.FunctionCallingConfig{ Mode: genai.FunctionCallingConfigModeAny, }, }, } genContentResp, _ := client.Models.GenerateContent(ctx, modelName, contents, config) printResponse(genContentResp) functionCalls := genContentResp.FunctionCalls() if len(functionCalls) == 0 { log.Println("No function call returned by the AI. The model likely answered directly.") return } // Process the first function call (the example assumes one for simplicity). fc := functionCalls[0] log.Printf("--- Gemini requested function call: %s --- ", fc.Name) log.Printf("--- Arguments: %+v --- ", fc.Args) var toolResultString string if fc.Name == "search-hotels-by-name" { tool := toolsMap["search-hotels-by-name"] toolResult, err := tool.Invoke(ctx, fc.Args) toolResultString = fmt.Sprintf("%v", toolResult) if err != nil { log.Fatalf("Failed to execute tool '%s': %v", fc.Name, err) } } else { log.Println("LLM did not request our tool") } resultContents := []*genai.Content{ genai.NewContentFromText("The tool returned this result, share it with the user based of their previous querys"+toolResultString, genai.RoleUser), } finalResponse, err := client.Models.GenerateContent(ctx, modelName, resultContents, &genai.GenerateContentConfig{}) if err != nil { log.Fatalf("Error calling GenerateContent (with function result): %v", err) } log.Println("=== Final Response from Model (after processing function result) ===") printResponse(finalResponse) } ``` -------------------------------- ### Verify kubectl Installation Source: https://github.com/googleapis/mcp-toolbox/blob/main/docs/en/documentation/deploy-to/kubernetes/_index.md Check the installed version of the kubectl client. ```bash kubectl version --client ``` -------------------------------- ### Use Prebuilt Tools with MCP Toolbox Source: https://github.com/googleapis/mcp-toolbox/blob/main/npm/server/README.md Exposes standard database operations instantly using the --prebuilt flag. Requires relevant environment variables for data source connection. ```bash npx @toolbox-sdk/server --prebuilt --stdio ```