Lab 28: Building a "Shopping Cart" MCP Server Challenge
Goalโ
In this lab, you will build your own standalone MCP server from scratch in Python. This server will manage a stateful shopping cart, allowing clients to add items and inspect the cart's contents across multiple conversation turns. You will then connect an ADK agent to your custom server.
Step 1: Install MCP and Create the Agent Packageโ
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 and install themcpextra:cd /path/to/your/adk-training
uv add "google-adk[mcp]"Installing
mcpvia ADK's[mcp]extra guarantees a version compatible withgoogle-adk, rather than an unconstrained standalone release. -
Create the agent directory inside
adk-training:mkdir custom_mcp_server
cd custom_mcp_server
Step 2: Implement the MCP Server (cart_server.py)โ
Critical โ Never write logs to
stdoutin astdioMCP server! Whenmcp.server.stdio.stdio_server()runs, your server communicates with the ADK client by sending JSON-RPC frames over standard output (stdout). If you call a regularprint("...")withoutfile=sys.stderr, Python writes plain text straight intostdout, corrupting the JSON-RPC stream and crashing the MCP handshake! Always log tosys.stderr(print(..., file=sys.stderr, flush=True)).
Exercise: Inside custom_mcp_server/, create a file named cart_server.py and implement the @app.list_tools() and @app.call_tool() handlers by completing # TODO: 1 through # TODO: 4.
# custom_mcp_server/cart_server.py (Starter Code)
import asyncio
import json
import sys
from mcp import types as mcp_types
from mcp.server.lowlevel import Server, NotificationOptions
from mcp.server.models import InitializationOptions
import mcp.server.stdio
# --- Server State ---
# In production, persist state in a database (e.g., Redis or Firestore) keyed by
# user/session. Here, an in-memory list demonstrates cross-turn statefulness.
CART = []
# --- MCP Server Setup ---
app = Server("shopping_cart_mcp_server")
@app.list_tools()
async def list_mcp_tools() -> list[mcp_types.Tool]:
"""Defines the 'menu' of tools our server offers."""
print("[Server]: Client asked for the list of tools.", file=sys.stderr, flush=True)
# TODO: 1. Define the `add_item_to_cart` tool using `mcp_types.Tool(...)`.
# Provide:
# - name: "add_item_to_cart"
# - description: Clear description of what the tool does
# - inputSchema: JSON Schema object with a required string property "item"
add_item_tool = mcp_types.Tool(...)
# TODO: 2. Define the `view_cart` tool using `mcp_types.Tool(...)`.
# Provide a name, description, and an empty object inputSchema
# ({"type": "object", "properties": {}}).
view_cart_tool = mcp_types.Tool(...)
return [add_item_tool, view_cart_tool]
@app.call_tool()
async def call_mcp_tool(name: str, arguments: dict) -> list[mcp_types.Content]:
"""Handles the execution of our tools."""
print(f"[Server]: Client called tool '{name}'.", file=sys.stderr, flush=True)
# TODO: 3. Implement the logic for "add_item_to_cart":
# - Read `item = arguments.get("item")`.
# - If present, append `item` to `CART` and return a JSON status message
# wrapped in `[mcp_types.TextContent(type="text", text=response_text)]`.
# TODO: 4. Implement the logic for "view_cart":
# - Return a JSON payload containing `"cart": CART` wrapped in
# `[mcp_types.TextContent(type="text", text=response_text)]`.
response_text = json.dumps({"status": "error", "message": f"Tool '{name}' not implemented."})
return [mcp_types.TextContent(type="text", text=response_text)]
# --- MCP Server Runner (Provided for you) ---
async def run_mcp_stdio_server():
"""Runs the server, listening for JSON-RPC connections over stdio."""
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
print("[Server]: Waiting for a client to connect...", file=sys.stderr, flush=True)
await app.run(
read_stream,
write_stream,
InitializationOptions(
server_name=app.name,
server_version="0.1.0",
capabilities=app.get_capabilities(NotificationOptions(), {}),
),
)
print("[Server]: Client disconnected.", file=sys.stderr, flush=True)
if __name__ == "__main__":
print("[Server]: Starting Shopping Cart MCP Server...", file=sys.stderr, flush=True)
try:
asyncio.run(run_mcp_stdio_server())
except KeyboardInterrupt:
print("\n[Server]: Shutting down.", file=sys.stderr, flush=True)
Step 3: Create the ADK Client Agent (agent.py)โ
-
Complete
custom_mcp_server/agent.py: Createagent.pyinsidecustom_mcp_server/and connect tocart_server.pyusingMcpToolsetandStdioConnectionParams.Why
sys.executableinstead of'python3'? Hardcodingcommand='python3'resolves to whatever globalpython3binary appears first on the OSPATH, which often lacks your project's.venvpackages and crashes withModuleNotFoundError: No module named 'mcp'. Usingsys.executableguarantees the subprocess launches with the exact.venvPython interpreter running ADK!# custom_mcp_server/agent.py (Starter Code)
import pathlib
import sys
from google.adk import Agent
from google.adk.tools.mcp_tool import McpToolset, StdioConnectionParams
from mcp import StdioServerParameters
# TODO: 1. Compute the absolute path to 'cart_server.py' relative to this file
# (pathlib.Path(__file__).parent / "cart_server.py") โ do NOT use os.getcwd(),
# because `uv run adk web` is launched from the parent `adk-training` folder!
PATH_TO_SERVER = ...
# TODO: 2. Define `root_agent` and configure `McpToolset` with `StdioConnectionParams`
# and `StdioServerParameters(command=sys.executable, args=[PATH_TO_SERVER])`.
root_agent = Agent(
model='gemini-3.8-flash',
name='shopping_agent',
instruction='You are a shopping assistant. Help the user by adding items to their cart and showing them their cart contents.',
tools=[
McpToolset(...)
],
) -
Create
custom_mcp_server/__init__.py: Exposeagentso ADK discoverscustom_mcp_serveras an agent package:echo "from . import agent as agent" > __init__.py -
Configure
custom_mcp_server/.env: Create a.envfile insidecustom_mcp_server/matching your preferred Gemini backend:- Option A โ Google AI Studio (API Key):
GOOGLE_API_KEY=<your_google_ai_studio_api_key> - Option B โ Google Cloud Vertex AI (ADC):
GOOGLE_GENAI_USE_ENTERPRISE=1
GOOGLE_CLOUD_PROJECT=<your_gcp_project>
GOOGLE_CLOUD_LOCATION=global
- Option A โ Google AI Studio (API Key):
Step 4: Test the Full Systemโ
- Return to the parent
adk-trainingdirectory and start the ADK Dev UI:cd ..
uv run adk web - Open the Dev UI (
http://127.0.0.1:8000) and selectcustom_mcp_serverfrom the agent dropdown. - Interact with your stateful shopping cart across multiple turns:
- "Please add 'milk' to my cart."
- "Also add 'eggs'."
- "What is in my shopping cart?"
- Inspect the terminal logs: Watch your
[Server]: ...diagnostic lines stream cleanly viastderrin the terminal aslist_toolsandcall_toolexecute without interfering with thestdoutJSON-RPC channel!
Having Trouble?โ
If you get stuck, you can find the complete, working code in lab-solution.md or unlock the Solution Vault below.
Lab Summaryโ
You have built and consumed your own stateful MCP server in Python:
- Implemented
@app.list_tools()usingfrom mcp.server.lowlevel import Serverto advertise JSON Schema tool definitions. - Implemented
@app.call_tool()to mutate and read server-side state across turns. - Kept
stdioJSON-RPC framing intact by routing server logs tosys.stderr, and usedsys.executableso subprocesses inherit the active.venv.
Self-Reflection Questionsโ
- In our
cart_server.py, we used a global listCARTto store the state. Why is this approach not suitable for a production environment with multiple server instances or multiple concurrent users? What would be a better solution? - The server declares
capabilitiesin itsInitializationOptions. What role does this capability negotiation play during the MCP handshake, and what might happen if a client expects a capability the server never declared? - By building an MCP server, you have decoupled your tool's logic from the agent. What are the long-term benefits of this separation for maintaining and scaling your application?
๐ Reference Solution Vaultโ
Official Solution Vault โ Module 28
Locked Challenge โ Active Pedagogical Socratic Gate