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,
cdinto theadk-trainingproject 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.
-
Navigate to your
adk-trainingworkspace directory:cd /path/to/your/adk-training -
Install the MCP extra:
mcpis not part of ADK's base install โ installing it via ADK's[mcp]extra pins a tested, compatiblemcpSDK version in your workspace.venv:uv add "google-adk[mcp]" -
Scaffold the agent project:
uv run adk create mcp_agent
cd mcp_agentuv run adk create mcp_agentgenerates four files insidemcp_agent/:__init__.py(from . import agent as agent), which registersmcp_agentas a discoverable Python package foradk 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.envand.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/.
-
Create a directory for the tool to access:
mkdir test_files -
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โ
-
Verify
__init__.pyand.env: Confirm thatadk creategenerated both__init__.pyand.envinsidemcp_agent/:ls -la __init__.py .env -
Complete the
agent.pyscript: Exercise: Openmcp_agent/agent.py, replace the generated template with the starter skeleton below, and complete each# TODOsection. 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โ
-
Return to the parent
adk-trainingworkspace directory and launch the ADK Dev UI:cd ..
uv run adk webImportant: Always launch
uv run adk webfrom the parentadk-trainingdirectory (not from insidemcp_agent/), so ADK discoversmcp_agentas an agent package and loadsmcp_agent/.env.When the agent runs,
npxwill download and launch@modelcontextprotocol/server-filesystemas a local subprocess.Note: If your very first request fails with an MCP session initialization timeout while
npxdownloads the package for the first time, simply send the message again โ subsequent runs start immediately from your local npm cache. -
Interact with the agent:
- Open
http://127.0.0.1:8000in your browser. - Select
mcp_agentfrom 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(orlist_allowed_directoriesif unfiltered) and reportshello.txt.
- User:
- Turn 2 โ Read the file:
- User:
"Great, can you read the content of hello.txt for me?" - Expected Response: The agent calls
read_fileand returns"Hello from the MCP world!".
- User:
- Open
-
Examine the Trace View:
- Inspect the trace for both turns in the Dev UI. Notice the
execute_toolspans forlist_directoryandread_fileโ tools that were dynamically discovered from the external Node.js MCP server viaMcpToolset.
- Inspect the trace for both turns in the Dev UI. Notice the
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
McpToolsetto dynamically discover and expose external MCP tools to an ADKAgent. - Configured
StdioConnectionParamsandStdioServerParametersto manage a local MCP server subprocess. - Sandboxed filesystem access to an explicit directory (
TARGET_FOLDER_PATH) and restricted exposed capabilities withtool_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.
-
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.
-
Scaffold
github_agentfrom the parentadk-trainingworkspace directory: Make sure you are inadk-training/(not insidemcp_agent/), then run:cd /path/to/your/adk-training
uv run adk create github_agentJust like before,
uv run adk create github_agentautomatically creates:github_agent/__init__.py(from . import agent as agent) so ADK discovers the package.github_agent/.envpre-populated with your Gemini backend configuration (GOOGLE_API_KEYor Vertex AI settings).github_agent/agent.pyandgithub_agent/.gitignore.
-
Add
GITHUB_TOKENtogithub_agent/.env: Append your GitHub token togithub_agent/.env(keeping your existing Gemini credentials intact):GITHUB_TOKEN=YOUR_GITHUB_TOKEN -
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",
},
),
)
],
) -
Launch
adk webfrom the parentadk-trainingdirectory and test it:cd /path/to/your/adk-training
uv run adk webSelect
github_agentfrom the Dev UI dropdown and ask: "What are the open issues on google/adk-python?" โ nonpx, 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
McpToolsetdynamically 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_filesdirectory between tool calls. How does this differ from the stateless calculator tools you built in earlier modules? - The
StdioConnectionParamslaunches 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 specificTARGET_FOLDER_PATH?
๐ Reference Solution Vaultโ
Official Solution Vault โ Module 27
Locked Challenge โ Active Pedagogical Socratic Gate