Skip to main content

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, 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 and install the mcp extra:

    cd /path/to/your/adk-training
    uv add "google-adk[mcp]"

    Installing mcp via ADK's [mcp] extra guarantees a version compatible with google-adk, rather than an unconstrained standalone release.

  2. 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 stdout in a stdio MCP server! When mcp.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 regular print("...") without file=sys.stderr, Python writes plain text straight into stdout, corrupting the JSON-RPC stream and crashing the MCP handshake! Always log to sys.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)โ€‹

  1. Complete custom_mcp_server/agent.py: Create agent.py inside custom_mcp_server/ and connect to cart_server.py using McpToolset and StdioConnectionParams.

    Why sys.executable instead of 'python3'? Hardcoding command='python3' resolves to whatever global python3 binary appears first on the OS PATH, which often lacks your project's .venv packages and crashes with ModuleNotFoundError: No module named 'mcp'. Using sys.executable guarantees the subprocess launches with the exact .venv Python 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(...)
    ],
    )
  2. Create custom_mcp_server/__init__.py: Expose agent so ADK discovers custom_mcp_server as an agent package:

    echo "from . import agent as agent" > __init__.py
  3. Configure custom_mcp_server/.env: Create a .env file inside custom_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

Step 4: Test the Full Systemโ€‹

  1. Return to the parent adk-training directory and start the ADK Dev UI:
    cd ..
    uv run adk web
  2. Open the Dev UI (http://127.0.0.1:8000) and select custom_mcp_server from the agent dropdown.
  3. Interact with your stateful shopping cart across multiple turns:
    • "Please add 'milk' to my cart."
    • "Also add 'eggs'."
    • "What is in my shopping cart?"
  4. Inspect the terminal logs: Watch your [Server]: ... diagnostic lines stream cleanly via stderr in the terminal as list_tools and call_tool execute without interfering with the stdout JSON-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() using from mcp.server.lowlevel import Server to advertise JSON Schema tool definitions.
  • Implemented @app.call_tool() to mutate and read server-side state across turns.
  • Kept stdio JSON-RPC framing intact by routing server logs to sys.stderr, and used sys.executable so subprocesses inherit the active .venv.

Self-Reflection Questionsโ€‹

  • In our cart_server.py, we used a global list CART to 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 capabilities in its InitializationOptions. 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โ€‹

๐Ÿงช

28: Building MCP Servers(Challenge Lab)

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