Skip to main content

Lab 27: Using a Stateful File System Tool Challenge

Goalโ€‹

In this lab, you will learn how to connect your ADK agent to an external, stateful tool using the Model Context Protocol (MCP). You will use McpToolset to connect to a pre-built, open-source MCP server that provides file system operations, allowing your agent to list files and read their contents from a sandboxed local directory.

Prerequisitesโ€‹

  • Node.js and npx: The MCP server we will use is distributed as a Node.js package. If you don't have it installed, install Node.js (which includes npx) from the official website.

Step 1: Create the Agent Projectโ€‹

Environment setup:

  • 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
  • Local machine: If you're continuing the course in sequence, cd into the adk-training project you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:
    uv init adk-training --python 3.10 && cd adk-training
    uv add "google-adk>=2.1.0" python-dotenv
  • DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11, uv, gcloud, and all core ADK dependencies are pre-installed in your container environment.
  1. Navigate to your adk-training workspace directory:

    cd /path/to/your/adk-training
  2. Install the MCP extra: mcp is not part of ADK's base install โ€” installing it via ADK's [mcp] extra pins a tested, compatible mcp SDK version in your workspace .venv:

    uv add "google-adk[mcp]"
  3. Scaffold the agent project:

    uv run adk create mcp_agent
    cd mcp_agent

    uv run adk create mcp_agent generates four files inside mcp_agent/:

    • __init__.py (from . import agent as agent), which registers mcp_agent as a discoverable Python package for adk web.
    • agent.py, a starter agent script that you will replace in Step 3.
    • .env, containing the Google AI Studio (GOOGLE_API_KEY) or Vertex AI (GOOGLE_GENAI_USE_ENTERPRISE=1, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION) credentials you selected during the prompt.
    • .gitignore, ensuring .env and .adk/ are excluded from version control.

Step 2: Create a Sandboxed Test Directory and Fileโ€‹

The MCP file system server requires an explicit directory path that acts as its sandbox boundary. Let's create one inside mcp_agent/.

  1. Create a directory for the tool to access:

    mkdir test_files
  2. Create a sample file inside test_files:

    echo "Hello from the MCP world!" > test_files/hello.txt

Step 3: Configure the Agent to Use the MCP Toolsetโ€‹

  1. Verify __init__.py and .env: Confirm that adk create generated both __init__.py and .env inside mcp_agent/:

    ls -la __init__.py .env
  2. Complete the agent.py script: Exercise: Open mcp_agent/agent.py, replace the generated template with the starter skeleton below, and complete each # TODO section. Refer to the MCP Connection Types section in the Theory page if you need a refresher on the exact import paths.

    import os
    from google.adk import Agent

    # TODO: 1. Import the required MCP classes:
    # - `McpToolset` and `StdioConnectionParams` from `google.adk.tools.mcp_tool`
    # - `StdioServerParameters` from `mcp`


    # -- Configuration --
    # TODO: 2. Define TARGET_FOLDER_PATH pointing to the `test_files` directory
    # next to this `agent.py` file (use os.path.dirname(os.path.abspath(__file__))).
    TARGET_FOLDER_PATH = ...

    # -- Agent Definition --
    # TODO: 3. Define `root_agent` as an Agent with:
    # - model: 'gemini-3.8-flash'
    # - name: 'filesystem_agent'
    # - instruction: 'You are a helpful assistant that can interact with a user\'s local file system. You can list files and read their content.'
    # - tools: A list containing a configured `McpToolset`.
    #
    # Inside `McpToolset(...)`:
    # connection_params=StdioConnectionParams(
    # server_params=StdioServerParameters(
    # # TODO: 4. Set `command` to 'npx'.
    # # TODO: 5. Set `args` to ["-y", "@modelcontextprotocol/server-filesystem", os.path.abspath(TARGET_FOLDER_PATH)].
    # command=...,
    # args=[...],
    # ),
    # ),
    # # TODO: 6. Restrict exposed tools using `tool_filter` to ['list_directory', 'read_file'].
    # tool_filter=[...]

    root_agent = ...

Step 4: Test the Stateful Toolโ€‹

  1. Return to the parent adk-training workspace directory and launch the ADK Dev UI:

    cd ..
    uv run adk web

    Important: Always launch uv run adk web from the parent adk-training directory (not from inside mcp_agent/), so ADK discovers mcp_agent as an agent package and loads mcp_agent/.env.

    When the agent runs, npx will download and launch @modelcontextprotocol/server-filesystem as a local subprocess.

    Note: If your very first request fails with an MCP session initialization timeout while npx downloads the package for the first time, simply send the message again โ€” subsequent runs start immediately from your local npm cache.

  2. Interact with the agent:

    • Open http://127.0.0.1:8000 in your browser.
    • Select mcp_agent from the agent dropdown in the top-left corner.
    • Turn 1 โ€” List the files:
      • User: "List the files in the directory you have access to." (Or "What files are in my directory?" โ€” if the model asks which path to check, reply "the allowed directory" or ".".)
      • Expected Response: The agent calls list_directory (or list_allowed_directories if unfiltered) and reports hello.txt.
    • Turn 2 โ€” Read the file:
      • User: "Great, can you read the content of hello.txt for me?"
      • Expected Response: The agent calls read_file and returns "Hello from the MCP world!".
  3. Examine the Trace View:

    • Inspect the trace for both turns in the Dev UI. Notice the execute_tool spans for list_directory and read_file โ€” tools that were dynamically discovered from the external Node.js MCP server via McpToolset.

Having Trouble?โ€‹

If you get stuck, check the complete reference implementation in lab-solution.md or unlock the Solution Vault at the bottom of this page.

Lab Summaryโ€‹

You have connected an ADK agent to an external, stateful tool server over the Model Context Protocol:

  • Used McpToolset to dynamically discover and expose external MCP tools to an ADK Agent.
  • Configured StdioConnectionParams and StdioServerParameters to manage a local MCP server subprocess.
  • Sandboxed filesystem access to an explicit directory (TARGET_FOLDER_PATH) and restricted exposed capabilities with tool_filter.

Bonus: Connecting to a Remote MCP Server (github_agent)โ€‹

So far you connected to a local MCP server launched as a subprocess (StdioConnectionParams). Most production integrations instead connect to a remote MCP server over HTTPS using StreamableHTTPConnectionParams โ€” the exact same McpToolset, just a different transport.

  1. Create a GitHub Personal Access Token: Generate a fine-grained token at github.com/settings/personal-access-tokens/new with read-only public repository access.

  2. Scaffold github_agent from the parent adk-training workspace directory: Make sure you are in adk-training/ (not inside mcp_agent/), then run:

    cd /path/to/your/adk-training
    uv run adk create github_agent

    Just like before, uv run adk create github_agent automatically creates:

    • github_agent/__init__.py (from . import agent as agent) so ADK discovers the package.
    • github_agent/.env pre-populated with your Gemini backend configuration (GOOGLE_API_KEY or Vertex AI settings).
    • github_agent/agent.py and github_agent/.gitignore.
  3. Add GITHUB_TOKEN to github_agent/.env: Append your GitHub token to github_agent/.env (keeping your existing Gemini credentials intact):

    GITHUB_TOKEN=YOUR_GITHUB_TOKEN
  4. Replace github_agent/agent.py:

    import os
    from google.adk import Agent
    from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams

    GITHUB_TOKEN = os.environ["GITHUB_TOKEN"]

    root_agent = Agent(
    model="gemini-3.8-flash",
    name="github_agent",
    instruction="Help users get information from GitHub repositories.",
    tools=[
    McpToolset(
    connection_params=StreamableHTTPConnectionParams(
    url="https://api.githubcopilot.com/mcp/",
    headers={
    "Authorization": f"Bearer {GITHUB_TOKEN}",
    "X-MCP-Readonly": "true",
    },
    ),
    )
    ],
    )
  5. Launch adk web from the parent adk-training directory and test it:

    cd /path/to/your/adk-training
    uv run adk web

    Select github_agent from the Dev UI dropdown and ask: "What are the open issues on google/adk-python?" โ€” no npx, no subprocess, and no local filesystem exposure; tool calls travel directly over HTTPS to GitHub's hosted MCP server.

Notice what shifts when moving from local stdio to remote HTTP: there is no subprocess lifecycle to manage, network failure modes (timeouts, rate limits, expired tokens) must be accounted for, and your primary security boundary moves from directory sandboxing to least-privilege token scoping (X-MCP-Readonly: true and loading GITHUB_TOKEN from github_agent/.env rather than hardcoding secrets).

Self-Reflection Questionsโ€‹

  • The McpToolset dynamically discovers the tools from the server. What are the advantages of this approach compared to manually defining each tool on the agent side?
  • The file system server is "stateful" because it remembers the state of the test_files directory between tool calls. How does this differ from the stateless calculator tools you built in earlier modules?
  • The StdioConnectionParams launches the MCP server as a subprocess. What are the security implications of this, and why is it important that the server is sandboxed to a specific TARGET_FOLDER_PATH?

๐Ÿ” Reference Solution Vaultโ€‹

๐Ÿงช

27: Intro to Model Context Protocol(Challenge Lab)

Part 5: Advanced Integrations & UI โ€ข Module 27

Overall Course Progress:
0%(0/98)
Next: 28: Building MCP Servers ๐Ÿ“– โ†’