### Setup Project Environment and Run Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/INDEX.md This bash script outlines the setup steps for the project, including creating a virtual environment, installing dependencies, configuring environment variables, and running the database initialization and agent scripts. ```bash # Create virtual environment python3 -m venv .venv source .venv/bin/activate # Install dependencies pip install -r requirements.txt # Configure environment export GOOGLE_API_KEY=your_key export NOTION_API_KEY=your_key # If using Notion # Initialize database cd local_mcp && python3 create_db.py && cd .. # Run agent python3 local_mcp/agent.py ``` -------------------------------- ### Environment Setup Script Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md A bash script to automate the setup of the project environment, including virtual environment creation, dependency installation, and .env file configuration. ```bash #!/bin/bash # Create virtual environment python3 -m venv .venv source .venv/bin/activate # Install dependencies pip install -r requirements.txt # Create .env file cat > .env << EOF GOOGLE_API_KEY=your_key_here NOTION_API_KEY=your_key_here EOF # Initialize database cd local_mcp python3 create_db.py cd .. echo "Setup complete!" ``` -------------------------------- ### Example Agent Behavior: Query all users Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/prompts.md Illustrates how the agent, guided by DB_MCP_PROMPT, proactively uses the `query_db_table` tool to fetch all users without explicit column or filter details. ```text User: "Show me all users" Agent: Uses query_db_table("users", "*", "1=1") without asking for column or filter details ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Install all necessary Python packages listed in the requirements.txt file using pip. Ensure your virtual environment is activated. ```bash pip install -r requirements.txt ``` -------------------------------- ### Bash Command: Setup Instructions from project root Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/database-utilities.md Details the steps to set up the database by running the `create_db.py` script from the project's root directory. ```bash cd local_mcp python3 create_db.py cd .. ``` -------------------------------- ### Verify Node.js, npm, and npx Installation Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Check if Node.js, npm, and npx are installed and accessible in your system's PATH. Open a new terminal after installation. ```bash node -v npm -v npx -v ``` -------------------------------- ### Python Example: Initialize the database Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/database-utilities.md Demonstrates how to import and call the `create_database` function to initialize the SQLite database. This function is safe to call multiple times. ```python from local_mcp.create_db import create_database # Initialize the database (safe to call multiple times) create_database() ``` -------------------------------- ### Example Tool Execution Flow Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Illustrates the request and response cycle when a client executes a tool via the MCP server. ```json Client Request: { "name": "query_db_table", "arguments": { "table_name": "users", "columns": "*", "condition": "id = 1" } } Server Processing: 1. Find tool: ADK_DB_TOOLS["query_db_table"] 2. Execute: await tool.run_async(args=arguments) 3. Encode result as JSON 4. Return TextContent Client Response: { "type": "text", "text": "[{\"id\": 1, \"username\": \"alice\", \"email\": \"alice@example.com\"}]" } ``` -------------------------------- ### Insert Data Request Example (Users) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a request to insert a new user record into the 'users' table. ```json { "table_name": "users", "data": { "username": "diana", "email": "diana@example.com" } } ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/remote-mcp-agent.md Commands to verify if Node.js, npm, and npx are installed on your system. These are required for the Notion MCP server. ```bash node -v # Verify Node.js is installed npm -v # Verify npm is installed npx -v # Verify npx is available ``` -------------------------------- ### Python Module-Level Execution to create database Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/database-utilities.md Shows how to run the `create_db.py` module directly as a script to initialize the database. This is the recommended method for first-time setup. ```python if __name__ == "__main__": create_database() ``` -------------------------------- ### Node.js Server Configuration Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of configuring StdioServerParameters for a Node.js-based MCP server using npx. ```python # Node.js server StdioServerParameters( command="npx", args=["-y", "@notionhq/notion-mcp-server"] ) ``` -------------------------------- ### list_db_tables Success Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of a successful response when listing database tables. Includes a list of table names. ```python # list_db_tables success { "success": True, "message": "Tables listed successfully.", "tables": ["users", "todos"] } ``` -------------------------------- ### Python Server Configuration Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of configuring StdioServerParameters for a Python-based MCP server. ```python # Python server StdioServerParameters( command="python3", args=["server.py"] ) ``` -------------------------------- ### Insert Data Request Example (Todos) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a request to insert a new todo item into the 'todos' table. ```json { "table_name": "todos", "data": { "user_id": 1, "task": "Buy groceries", "completed": 0 } } ``` -------------------------------- ### MCPToolset with Tool Filter Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of initializing MCPToolset with a specific list of tools to be exposed to the agent. This limits the available functionality. ```python MCPToolset( connection_params=StdioServerParameters( command="python3", args=["server.py"] ), tool_filter=["list_db_tables", "query_db_table"] # Only these tools ) ``` -------------------------------- ### Insert Data Error Response Example (No Data) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of an error response when no data is provided for insertion. ```json { "success": false, "message": "No data provided for insertion." } ``` -------------------------------- ### Get Table Schema Error Response (Table Not Found) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md This example shows an error response when the requested table is not found. The `success` field is false, and the `message` provides details about the error. ```json { "success": false, "message": "Table 'invalid_table' not found or no schema information." } ``` -------------------------------- ### Docker Server with Environment Variables Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of configuring StdioServerParameters for a Dockerized MCP server, including environment variables. ```python # Docker server with environment StdioServerParameters( command="docker", args=["run", "-i", "--rm", "my-mcp-server"], env={"API_KEY": "token_here"} ) ``` -------------------------------- ### Delete Data Request Example (Todos) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a request to delete completed todos from the 'todos' table. ```json { "table_name": "todos", "condition": "user_id = 1 AND completed = 1" } ``` -------------------------------- ### Example Agent Behavior: List tables Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/prompts.md Shows the agent using the `list_db_tables` tool with a default parameter, as instructed by DB_MCP_PROMPT, when asked about existing tables. ```text User: "What tables exist?" Agent: Uses list_db_tables("default_list_request") without asking for the dummy_param ``` -------------------------------- ### Verify Docker Installation Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Confirm that Docker is installed and operational by checking its version. A test container can also be run to ensure full functionality. ```bash docker --version # You can also run a test container to ensure Docker is working correctly: # docker run hello-world ``` -------------------------------- ### run_mcp_stdio_server() Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-server.md Starts the MCP server listening on standard input/output. This is used for running the server as a subprocess launched by agents. ```APIDOC ## run_mcp_stdio_server() ### Description Starts the MCP server listening on standard input/output. This function is used for running the server as a subprocess launched by agents. It creates a stdio server instance, performs a handshake with the client, runs the app with initialization options, and logs connection lifecycle events. ### Method Not applicable (this is a server startup function). ### Endpoint Not applicable (this function starts a server process). ### Usage Used For: Running the server as a subprocess launched by agents. ``` -------------------------------- ### Delete Data Request Example (Users) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a request to delete a user from the 'users' table based on ID. ```json { "table_name": "users", "condition": "id = 3" } ``` -------------------------------- ### Usage Example: Querying the Database Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-agent.md Shows how to use the pre-configured `root_agent` to send a natural language query to the local MCP server. The response from the agent, which includes database information, is then printed. ```python from local_mcp.agent import root_agent # The agent is pre-configured and ready to use # Send it a query about the database response = root_agent.generate_content( "List all tables in the database and show me the schema for the users table" ) print(response.text) ``` -------------------------------- ### Missing Data Error Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of an error response indicating that no data was provided for an insertion operation. ```python # Missing data for insert { "success": False, "message": "No data provided for insertion." } ``` -------------------------------- ### Example Usage of random_number Tool Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/demo-agents.md Demonstrates how to call the traditional `random_number` tool and print the result. Ensure the tool is imported from the correct module. ```python from demo_comparison.traditional_agent import random_number result = random_number() print(f"Random number: {result['number']}") ``` -------------------------------- ### Query All Users Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example request to query all columns from the 'users' table without any specific conditions. ```json { "table_name": "users", "columns": "*", "condition": "1=1" } ``` -------------------------------- ### Use GITHUB_PERSONAL_ACCESS_TOKEN in Python Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Example of how to pass the GITHUB_PERSONAL_ACCESS_TOKEN as an environment variable in a Python script, specifically for the demo_comparison/mcp_agent.py. ```python env={"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."} ``` -------------------------------- ### delete_data Success Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of a successful response after deleting data. Indicates the number of rows deleted. ```python # delete_data success { "success": True, "message": "3 row(s) deleted successfully from table 'todos'.", "rows_deleted": 3 } ``` -------------------------------- ### Delete Data Success Response Example (No Matching Rows) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a successful response when no rows matched the deletion condition. ```json { "success": true, "message": "0 row(s) deleted successfully from table 'users'.", "rows_deleted": 0 } ``` -------------------------------- ### Insert Data Success Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a successful response after inserting data, including the new row ID. ```json { "success": true, "message": "Data inserted successfully. Row ID: 42", "row_id": 42 } ``` -------------------------------- ### Generate Content with Remote MCP Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/remote-mcp-agent.md Example of sending a request to the pre-configured agent to generate content. Ensure the agent is imported and ready to use. ```python from remote_mcp_agent.agent import root_agent # The agent is pre-configured and ready to use # Send it a request about Notion response = root_agent.generate_content( "List all databases in my Notion workspace" ) print(response.text) ``` -------------------------------- ### Run ADK Agent and Local MCP Server Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Execute the agent script to start both the agent and the local MCP server. Ensure your virtual environment is active and you are in the project root. ```bash python3 local_mcp/agent.py ``` -------------------------------- ### insert_data Success Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of a successful response after inserting data. Includes the ID of the newly inserted row. ```python # insert_data success { "success": True, "message": "Data inserted successfully. Row ID: 42", "row_id": 42 } ``` -------------------------------- ### Delete Data Success Response Example (Rows Deleted) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a successful response after deleting rows, showing the count of deleted rows. ```json { "success": true, "message": "3 row(s) deleted successfully from table 'todos'.", "rows_deleted": 3 } ``` -------------------------------- ### Example Agent Behavior: Find users by email Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/prompts.md Demonstrates the agent's ability to infer a specific condition for `query_db_table` based on a user's request, such as finding users with Gmail addresses. ```text User: "Get all users with gmail addresses" Agent: Uses query_db_table("users", "*", "email LIKE '%@gmail.com'") directly ``` -------------------------------- ### Run MCP Standard I/O Server Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-server.md Starts the MCP server listening on standard input/output. Used for running the server as a subprocess launched by agents. It performs a handshake with the client and runs the app with initialization options. ```python async def run_mcp_stdio_server() ``` -------------------------------- ### Query Users by Email Domain Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example request to query 'id' and 'username' from the 'users' table, filtering for users whose email addresses end with '@example.com'. ```json { "table_name": "users", "columns": "id, username", "condition": "email LIKE '%@example.com'" } ``` -------------------------------- ### Successful Query Response Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of a successful response from the query_db_table tool, returning an array of user objects. ```json [ { "id": 1, "username": "alice", "email": "alice@example.com" }, { "id": 2, "username": "bob", "email": "bob@example.com" } ] ``` -------------------------------- ### Connecting to a Custom MCP Server via Docker Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/remote-mcp-agent.md Example of how to configure the MCPToolset to connect to a custom MCP server running inside a Docker container. This allows for flexible deployment and management of MCP servers. ```python # Example: connecting to a custom MCP server via Docker MCPToolset( connection_params=StdioServerParameters( command="docker", args=["run", "-i", "--rm", "my-custom-mcp-server"], env={"API_KEY": "token_here"} ) ) ``` -------------------------------- ### Example Usage of get_weather Tool Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/demo-agents.md Demonstrates calling the traditional `get_weather` tool with a city name and printing the mock weather result. The behavior is hardcoded to always return 'sunny'. ```python from demo_comparison.traditional_agent import get_weather result = get_weather("New York") print(f"Weather in New York: {result['weather']}") # Output: Weather in New York: sunny ``` -------------------------------- ### Get Notion API Key Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/remote-mcp-agent.md Retrieves the Notion API key from the environment variables. Raises a ValueError if the NOTION_API_KEY is not set, ensuring proper authentication setup. ```python NOTION_API_KEY = os.getenv("NOTION_API_KEY") if NOTION_API_KEY is None: raise ValueError("NOTION_API_KEY is not set") ``` -------------------------------- ### Query Specific Todo Items Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example request to query specific columns ('id', 'task', 'completed') from the 'todos' table, filtered by 'user_id' and 'completed' status. ```json { "table_name": "todos", "columns": "id, task, completed", "condition": "user_id = 1 AND completed = 0" } ``` -------------------------------- ### Instantiating the Notion MCP Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/prompts.md Demonstrates how to use the NOTION_PROMPT when initializing the remote Notion MCP agent. Ensure necessary imports are included. ```python from remote_mcp_agent.agent import root_agent from remote_mcp_agent.prompt import NOTION_PROMPT # NOTION_PROMPT is passed as the instruction parameter root_agent = Agent( model="gemini-2.0-flash", name="Notion_MCP_Agent", instruction=NOTION_PROMPT, tools=[MCPToolset(...)] ) ``` -------------------------------- ### Database Error Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of an error response indicating a problem during a database query. ```python # Database error { "success": False, "message": "Error querying table 'users': no such table" } ``` -------------------------------- ### Print Output when creating a new database Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/database-utilities.md Shows the expected console output when the `create_database` function successfully initializes a new database. ```text Creating new database at /absolute/path/to/local_mcp/database.db... Created 'users' table. Created 'todos' table. Inserted 3 dummy users. Inserted 5 dummy todos. Database created and populated successfully. ``` -------------------------------- ### Create a Database Query Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/INDEX.md This snippet demonstrates how to create a root agent and use it to generate content by querying the database. ```python from local_mcp.agent import root_agent response = root_agent.generate_content("Show me all users") print(response.text) ``` -------------------------------- ### Instantiating Local MCP Agent with DB_MCP_PROMPT Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/prompts.md Demonstrates how to use the DB_MCP_PROMPT when initializing the local MCP agent. The prompt is passed as the 'instruction' parameter to the LlmAgent constructor. ```python from local_mcp.agent import root_agent from local_mcp.prompt import DB_MCP_PROMPT # DB_MCP_PROMPT is passed as the instruction parameter root_agent = LlmAgent( model="gemini-2.0-flash", name="db_mcp_client_agent", instruction=DB_MCP_PROMPT, tools=[...] ) ``` -------------------------------- ### Initialize the Database Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/INDEX.md Use this snippet to create the necessary database. It is safe to call this function multiple times. ```python from local_mcp.create_db import create_database create_database() # Safe to call multiple times ``` -------------------------------- ### Safety Violation Error Response Example Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Example of an error response triggered by a safety violation, such as an empty deletion condition. ```python # Safety violation (empty deletion condition) { "success": False, "message": "Deletion condition cannot be empty. This is a safety measure to prevent accidental deletion of all rows." } ``` -------------------------------- ### Configuring MCP Agent with Tool Filtering Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/remote-mcp-agent.md Demonstrates how to initialize the MCPToolset with specific tool filters. This restricts the agent to use only the allowed tools, which is useful for controlling agent behavior and resource usage. ```python MCPToolset( connection_params=StdioServerParameters( command="npx", args=["-y", "@notionhq/notion-mcp-server"], env={"OPENAPI_MCP_HEADERS": NOTION_MCP_HEADERS}, ), tool_filter=["list_databases", "get_page"] # Optional: filter tools ) ``` -------------------------------- ### StdioServerParameters Constructor Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Defines how to connect to an MCP server via standard input/output. Specify the command, arguments, and optional environment variables. ```python StdioServerParameters( command: str, args: list[str], env: dict[str, str] | None = None ) ``` -------------------------------- ### Delete Data Error Response Example (SQL Error) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of an error response when a SQL error occurs during data deletion. ```json { "success": false, "message": "Error deleting data from table 'users': [SQL error details]" } ``` -------------------------------- ### Delete Data Error Response Example (Empty Condition) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of an error response when the deletion condition is empty, as a safety measure. ```json { "success": false, "message": "Deletion condition cannot be empty. This is a safety measure to prevent accidental deletion of all rows." } ``` -------------------------------- ### Initialize MCP Agent with Multiple Toolsets Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/demo-agents.md Instantiates an Agent with various MCP Toolsets for different services. Each Toolset is configured with StdioServerParameters specifying the command and arguments to run the respective MCP server. ```python root_agent = Agent( model="gemini-2.0-flash", name="MCP_Agent", instruction=""" You are a helpful assistant that can help with a variety of tasks. """, tools=[ MCPToolset( connection_params=StdioServerParameters( command="python", args=["absolute_path_to_server.py"] ) ), MCPToolset( connection_params=StdioServerParameters( command="npx", args=["-y", "@notionhq/notion-mcp-server"] ) ), MCPToolset( connection_params=StdioServerParameters( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem-adapter"], ) ), MCPToolset( connection_params=StdioServerParameters( command="docker", args=[ "run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "ghcr.io/github/github-mcp-server", ], env={"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."}, ) ), ], ) ``` -------------------------------- ### Insert Data Error Response Example (Constraint Violation) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of an error response when a unique constraint is violated during data insertion. ```json { "success": false, "message": "Error inserting data into table 'users': UNIQUE constraint failed: username" } ``` -------------------------------- ### Configure Filesystem Adapter MCP Toolset Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/demo-agents.md Sets up an MCP Toolset for filesystem operations using the official MCP filesystem adapter. This enables the agent to read, write, and list files. ```python MCPToolset( connection_params=StdioServerParameters( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem-adapter"], ) ) ``` -------------------------------- ### get_table_schema Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/INDEX.md Gets column definitions for a table. ```APIDOC ## get_table_schema ### Description Gets column definitions for a table. ### Method GET ### Endpoint /db/tables/{table_name}/schema ### Parameters #### Path Parameters - **table_name** (str) - Required - The name of the table. ### Response #### Success Response (200) - **table_name** (str) - The name of the table. - **columns** (list[dict]) - A list of column definitions, where each column has a 'name' (str) and 'type' (str). ``` -------------------------------- ### Bash Command: Run create_db.py from local_mcp directory Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/database-utilities.md Provides the command to execute the `create_db.py` script from within the `local_mcp` directory to initialize the database. ```bash cd local_mcp python3 create_db.py ``` -------------------------------- ### Configure Local LlmAgent with Tool Filtering Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Sets up a local LlmAgent with an optional tool filter to restrict access to specific tools. This is useful for limiting the agent's capabilities. ```python MCPToolset( connection_params=StdioServerParameters( command="python3", args=[PATH_TO_YOUR_MCP_SERVER_SCRIPT], ), tool_filter=['list_db_tables', 'query_db_table'] # Only these tools ) ``` -------------------------------- ### Empty Query Result Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of an empty result set when no rows match the query condition. ```json [] ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/00-START-HERE.md Overview of the directory structure for the ADK MCP Tutorial project documentation. ```markdown output/ ├── 00-START-HERE.md ← You are here ├── INDEX.md ← Navigation hub (start after this) ├── README.md ← Project overview ├── types.md ← Type definitions (13 types) ├── configuration.md ← Config & env vars ├── endpoints.md ← MCP endpoints (5 tools) ├── MANIFEST.md ← What was generated └── api-reference/ ├── local-mcp-agent.md ← ADK agent config ├── local-mcp-server.md ← MCP server impl (largest) ├── remote-mcp-agent.md ← Notion agent ├── database-utilities.md ← DB setup ├── prompts.md ← System prompts └── demo-agents.md ← Comparison agents ``` -------------------------------- ### StdioServerParameters Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Configuration for connecting to an MCP server via standard input/output. It specifies the command to execute, its arguments, and optional environment variables. ```APIDOC ## StdioServerParameters ### Description Configuration for connecting to an MCP server via standard input/output. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (str) - Yes - Command to execute (e.g., "python3", "npx", "docker") - **args** (list[str]) - Yes - Command-line arguments - **env** (dict[str, str] | None) - No - Environment variables to pass to the process ### Request Example ```json { "command": "python3", "args": ["server.py"] } ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Print Output when database already exists Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/database-utilities.md Shows the expected console output when the `create_database` function is called and the database already exists. ```text Database already exists at /absolute/path/to/local_mcp/database.db. No changes made. ``` -------------------------------- ### Query Error Response Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Example of an error response when the query execution fails, typically due to syntax errors in the SQL condition. ```json { "success": false, "message": "Error querying table 'users': [SQL error details]" } ``` -------------------------------- ### Required Imports for MCP Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/remote-mcp-agent.md These are the essential Python imports needed to run the remote MCP agent. Ensure these libraries are installed in your environment. ```python import json import os from google.adk.agents.llm_agent import Agent from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters from remote_mcp_agent.prompt import NOTION_PROMPT ``` -------------------------------- ### Initialize MCP Server Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Initializes the MCP server with a unique name used for handshakes and logs. ```python app = Server("sqlite-db-mcp-server") ``` -------------------------------- ### Get Table Schema Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-server.md Retrieves the schema (column names and types) for a specified table. Throws ValueError if the table is not found or has no schema information. ```python def get_table_schema(table_name: str) -> dict: ``` ```python schema = get_table_schema("users") print(f"Table: {schema['table_name']}") for col in schema['columns']: print(f" {col['name']}: {col['type']}") ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Use this command to create a new virtual environment for managing project dependencies. This is a standard Python practice. ```bash python3 -m venv .venv ``` -------------------------------- ### Run Local MCP Server Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-server.md Execute the local MCP server directly from the command line. ```bash cd local_mcp python3 server.py ``` -------------------------------- ### Get Table Schema Request Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Send this JSON payload to retrieve the schema for a specified table. Ensure the `table_name` parameter is set to the desired table. ```json { "table_name": "users" } ``` -------------------------------- ### List Available MCP Tools Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Clients call this endpoint to discover available tools. The response is an array of Tool objects, each detailing the tool's name, description, and expected input schema. ```json [ { "name": "list_db_tables", "description": "Lists all tables in the SQLite database.", "inputSchema": { "type": "object", "properties": { "dummy_param": {"type": "string"} }, "required": ["dummy_param"] } }, { "name": "get_table_schema", "description": "Gets the schema (column names and types) of a specific table.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"} }, "required": ["table_name"] } }, { "name": "query_db_table", "description": "Queries a table with an optional condition.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"}, "columns": {"type": "string"}, "condition": {"type": "string"} }, "required": ["table_name", "columns", "condition"] } }, { "name": "insert_data", "description": "Inserts a new row of data into the specified table.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"}, "data": {"type": "object"} }, "required": ["table_name", "data"] } }, { "name": "delete_data", "description": "Deletes rows from a table based on a given SQL WHERE clause condition.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"}, "condition": {"type": "string"} }, "required": ["table_name", "condition"] } } ] ``` -------------------------------- ### Use a Different MCP Server Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Replace 'StdioServerParameters' with custom connection parameters to integrate a different MCP server. This allows for flexible server configurations. ```python MCPToolset( connection_params=StdioServerParameters( command="npx", args=["-y", "@myorg/my-mcp-server"], env={"API_KEY": os.getenv("MY_API_KEY")} ) ) ``` -------------------------------- ### Set GITHUB_PERSONAL_ACCESS_TOKEN Environment Variable Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Export the GITHUB_PERSONAL_ACCESS_TOKEN environment variable, a PAT starting with 'ghp_', for GitHub API access. This is required only for GitHub MCP integration. ```bash export GITHUB_PERSONAL_ACCESS_TOKEN=ghp_your_token_here ``` -------------------------------- ### Configure GitHub MCP Server Toolset Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/demo-agents.md Configures an MCP Toolset to interact with the GitHub MCP server using Docker. Requires a GITHUB_PERSONAL_ACCESS_TOKEN environment variable for authentication. ```python MCPToolset( connection_params=StdioServerParameters( command="docker", args=[ "run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "ghcr.io/github/github-mcp-server", ], env={"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."}, ) ) ``` -------------------------------- ### Set NOTION_API_KEY Environment Variable Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Export the NOTION_API_KEY environment variable, a bearer token starting with 'notiond_', for accessing Notion's API. This is required for the remote_mcp_agent. ```bash export NOTION_API_KEY=notiond_your_token_here ``` -------------------------------- ### List SQLite Database Tables Error Response Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md This is an example of an error response when listing tables. It indicates failure with a boolean flag and provides error details in the message field. ```json { "success": false, "message": "Error listing tables: [error details]", "tables": [] } ``` -------------------------------- ### Configure File Handler for Logging Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Sets up a file handler to write logs to a specified file. The default mode 'w' overwrites the log file on each server startup. To preserve logs, change the mode to 'a' for append. ```python logging.FileHandler(LOG_FILE_PATH, mode="w") ``` -------------------------------- ### List SQLite Database Tables Success Response Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md This is an example of a successful response when listing tables. It includes a boolean success flag, a status message, and an array of table names. ```json { "success": true, "message": "Tables listed successfully.", "tables": ["users", "todos"] } ``` -------------------------------- ### Activate Virtual Environment (macOS/Linux) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Activate the previously created virtual environment on macOS or Linux systems. This ensures project dependencies are isolated. ```bash source .venv/bin/activate ``` -------------------------------- ### Get Local SQLite Database Connection Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-server.md Creates and returns a connection to the local SQLite database. Ensure to close the connection after use. Configured with row factory for column-by-name access. ```python def get_db_connection() -> sqlite3.Connection: pass ``` ```python conn = get_db_connection() cursor = conn.cursor() cursor.execute("SELECT * FROM users") rows = cursor.fetchall() conn.close() ``` -------------------------------- ### LlmAgent Constructor Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Defines the LlmAgent with model, name, instruction, and available tools. Used for LLM-based reasoning and tool selection. ```python LlmAgent( model: str, name: str, instruction: str, tools: list[Callable | MCPToolset] ) ``` -------------------------------- ### Activate Virtual Environment (Windows) Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/readme.md Activate the previously created virtual environment on Windows systems. This ensures project dependencies are isolated. ```bash .venv\Scripts\activate ``` -------------------------------- ### Project Structure Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/README.md This snippet outlines the directory structure of the ADK MCP Tutorial project. It shows the organization of Python modules for local and remote MCP interactions, comparison agents, and utility scripts. ```tree adk-mcp-tutorial/ ├── local_mcp/ │ ├── agent.py # ADK agent client │ ├── server.py # MCP server exposing database tools │ ├── create_db.py # Database initialization utility │ ├── prompt.py # Agent system prompt │ └── __init__.py ├── remote_mcp_agent/ │ ├── agent.py # Agent for remote MCP (Notion example) │ ├── prompt.py # Agent system prompt │ └── __init__.py ├── demo_comparison/ │ ├── traditional_agent.py # Traditional tool-based agent │ └── mcp_agent.py # MCP-based multi-tool agent ├── requirements.txt # Python dependencies └── readme.md # User-facing documentation ``` -------------------------------- ### Instantiate Local MCP Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-agent.md Configures the main LlmAgent instance for interacting with the local SQLite database MCP server. It specifies the LLM model, agent name, system prompt, and MCP toolset with stdio connection parameters. ```python root_agent = LlmAgent( model="gemini-2.0-flash", name="db_mcp_client_agent", instruction=DB_MCP_PROMPT, tools=[ MCPToolset( connection_params=StdioServerParameters( command="python3", args=[PATH_TO_YOUR_MCP_SERVER_SCRIPT], ) ) ], ) ``` -------------------------------- ### Required Imports for Local MCP Agent Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-agent.md Lists the necessary imports for the local MCP agent, including `Path` for path manipulation, `LlmAgent` for agent creation, `MCPToolset` and `StdioServerParameters` for MCP server interaction, and `DB_MCP_PROMPT` for the system instruction. ```python from pathlib import Path from google.adk.agents import LlmAgent from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters from local_mcp.prompt import DB_MCP_PROMPT ``` -------------------------------- ### list_mcp_tools() Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/local-mcp-server.md Advertises all available tools to clients. It converts ADK FunctionTools to MCP format, assigns tool names, and logs each advertised tool. ```APIDOC ## list_mcp_tools() ### Description MCP handler that advertises all available tools to clients. It wraps each ADK FunctionTool with `adk_to_mcp_tool_type()` to convert to MCP format, assigns tool names if not already set, and logs each advertised tool. ### Method POST (inferred from `@app.list_tools()` decorator) ### Endpoint /list_tools ### Returns List of MCP Tool objects with names, descriptions, and input schemas for all database tools. ``` -------------------------------- ### Accessing sqlite3 Row Data by Column Name Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md Demonstrates how to access data from a sqlite3.Row object using column names. This is useful for retrieving specific fields from a database query result. The example also shows how to convert the row object into a standard Python dictionary. ```python row = cursor.fetchone() # Access by column name username = row["username"] email = row["email"] # Convert to dict row_dict = dict(row) ``` -------------------------------- ### list_tools() Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/endpoints.md Clients call this endpoint to discover available tools on the MCP server. It returns an array of Tool objects, each detailing a tool's name, description, and input schema. ```APIDOC ## list_tools() ### Description Clients call this endpoint to discover available tools. It returns an array of Tool objects, each detailing a tool's name, description, and input schema. ### Method Not specified (MCP Handler) ### Endpoint `@app.list_tools()` ### Parameters #### Request Body None (no parameters) ### Response #### Success Response - **Array of Tool objects** #### Response Example ```json [ { "name": "list_db_tables", "description": "Lists all tables in the SQLite database.", "inputSchema": { "type": "object", "properties": { "dummy_param": {"type": "string"} }, "required": ["dummy_param"] } }, { "name": "get_table_schema", "description": "Gets the schema (column names and types) of a specific table.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"} }, "required": ["table_name"] } }, { "name": "query_db_table", "description": "Queries a table with an optional condition.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"}, "columns": {"type": "string"}, "condition": {"type": "string"} }, "required": ["table_name", "columns", "condition"] } }, { "name": "insert_data", "description": "Inserts a new row of data into the specified table.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"}, "data": {"type": "object"} }, "required": ["table_name", "data"] } }, { "name": "delete_data", "description": "Deletes rows from a table based on a given SQL WHERE clause condition.", "inputSchema": { "type": "object", "properties": { "table_name": {"type": "string"}, "condition": {"type": "string"} }, "required": ["table_name", "condition"] } } ] ``` ``` -------------------------------- ### Add GOOGLE_API_KEY to .env File Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/configuration.md Add the GOOGLE_API_KEY to the .env file in the project root for automatic loading by server scripts and agent scripts using Gemini models. ```env GOOGLE_API_KEY=your_api_key_here ``` -------------------------------- ### Project File Organization Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/MANIFEST.md This tree structure shows the layout of the project's files and directories, indicating the purpose of each file. ```text /workspace/home/output/ ├── INDEX.md # Navigation hub (start here) ├── README.md # Project overview ├── types.md # Type definitions ├── configuration.md # Configuration reference ├── endpoints.md # MCP endpoints ├── MANIFEST.md # This file └── api-reference/ ├── local-mcp-agent.md # Agent configuration ├── local-mcp-server.md # Server implementation (largest) ├── remote-mcp-agent.md # Remote server agent ├── database-utilities.md # Database setup ├── prompts.md # System prompts └── demo-agents.md # Comparison agents ``` -------------------------------- ### Agent Constructor Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/types.md A simplified Agent constructor for creating agents with model, name, instruction, and tools. Suitable for simpler agent creation interfaces. ```python Agent( model: str, name: str, instruction: str, tools: list[Callable | MCPToolset] ) ``` -------------------------------- ### Configure Custom SQLite Database MCP Toolset Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/demo-agents.md Sets up an MCP Toolset to connect to a custom Python-based MCP server for database operations. Ensure 'absolute_path_to_server.py' is replaced with the correct path to your server script. ```python MCPToolset( connection_params=StdioServerParameters( command="python", args=["absolute_path_to_server.py"] ) ) ``` -------------------------------- ### Full Text of DB_MCP_PROMPT Source: https://github.com/bhancockio/adk-mcp-tutorial/blob/main/_autodocs/api-reference/prompts.md This is the complete system prompt for the local SQLite database MCP agent. It outlines principles for proactive tool use, smart defaults for query parameters, minimizing clarification questions, and efficient output formatting. ```text You are a highly proactive and efficient assistant for interacting with a local SQLite database. Your primary goal is to fulfill user requests by directly using the available database tools. Key Principles: - Prioritize Action: When a user's request implies a database operation, use the relevant tool immediately. - Smart Defaults: If a tool requires parameters not explicitly provided by the user: - For querying tables (e.g., the `query_db_table` tool): - If columns are not specified, default to selecting all columns (e.g., by providing "*" for the `columns` parameter). - If a filter condition is not specified, default to selecting all rows (e.g., by providing a universally true condition like "1=1" for the `condition` parameter). - For listing tables (e.g., `list_db_tables`): If it requires a dummy parameter, provide a sensible default value like "default_list_request". - Minimize Clarification: Only ask clarifying questions if the user's intent is highly ambiguous and reasonable defaults cannot be inferred. Strive to act on the request using your best judgment. - Efficiency: Provide concise and direct answers based on the tool's output. - Make sure you return information in an easy to read format. ```