ADK + MCP · A tool call you can trace

Build an ADK + MCP Cost Agent: A Practical Guide

Build one read-only cost tool, inspect its trace, then add the identity, data checks, tests and operations required for real billing access.

Harborlane, the illustrative booking company in this guide, wants an agent to explain its cloud bill. Start with a local, read-only tool before connecting real billing data. The teaching fixture totals $600: compute $240, database $180, storage $60 and other services $120. These values are not Google Cloud prices.

Build with MCP, ADK and A2A · Google for Developers, December 2025. Compare commands with current documentation.

You will build the tool, inspect a call, then define the controls needed for real data and deployment.

01 / Give each component one job

ADK runs the agent; MCP connects it to tools

Four components in the example
ComponentIts jobIt does not decide
Gemini modelInterpret the request and propose the next stepWhich customer the caller is authorized to access
ADK applicationDefine agent instructions, tool access and execution behaviorThe truth of a billing record
MCP serverExpose typed tools through a standard protocolBusiness access rules automatically
Data adapterValidate scope and retrieve a bounded resultWhether a saving is safe to apply

A2A connects agents to other agents. It is separate from MCP and unnecessary for this single-tool lab.

Define a narrow tool contract

ADK’s McpToolset exposes selected MCP tools to the model. Prefer a narrow contract such as get_service_cost(service, month) to arbitrary SQL or shell execution.

The tool filter controls what the model sees. Trusted application code and the data service must enforce the caller’s permissions.

Follow one request

A traceable agent requestA question enters ADK, which offers allowed tools to the model. The MCP tool validates access and returns bounded data. The answer includes its source and limits.01AskQuestion + caller identity02SelectADK offers permitted tools03ValidateMCP tool checks scope04AnswerAmount + source + limits
Read the diagram

ADK receives the question and exposes only allowed tools to the model. An MCP tool checks access and returns a bounded result; the final answer states its evidence and limits. Each step must remain traceable.

Conceptual request flow. Authorization runs in trusted code before data access.

Ask for compute cost. The agent calls get_demo_cost("compute"), receives $240 and identifies it as example USD data. It has not inspected a real cloud project.

02 / Build the local evidence loop

Build the local read-only tool

Use Python 3.11+, a virtual environment and model authentication from the ADK quickstart. This lab uses MCP Python SDK v2. Record installed versions and check dependencies:

Create the environment and two small files

python -m venv .venv
# Activate .venv for your operating system before the next command.
python -m pip install "google-adk[mcp]" "mcp[cli]>=2,<3"
python -m pip check

Create demo_mcp.py beside a cost_agent folder containing an empty __init__.py and the agent.py below. Set MODEL_NAME to an available model ID; keep credentials out of source control.

Expose Harborlane’s example cost data

from typing import Literal
from mcp.server import MCPServer

mcp = MCPServer("harborlane-cost-demo")
COSTS = {"compute": 240, "database": 180,
         "storage": 60, "other": 120}

@mcp.tool()
def get_demo_cost(
    service: Literal["compute", "database", "storage", "other"]
) -> dict:
    """Read one service's illustrative monthly Harborlane cost."""
    return {
        "service": service,
        "amount": COSTS[service],
        "currency": "USD",
        "period": "example month",
        "source": "local fixture; not a real cloud bill"
    }

Inspect the tool with mcp dev demo_mcp.py. The Inspector requires its documented Node.js prerequisites. Calling compute should return 240 and the fixture label.

Connect the agent to that exact tool

import os
from pathlib import Path
from google.adk.agents import LlmAgent
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from mcp import StdioServerParameters

server_file = Path(__file__).resolve().parent.parent / "demo_mcp.py"

root_agent = LlmAgent(
    name="harborlane_cost_reader",
    model=os.environ["MODEL_NAME"],
    instruction=(
        "Use get_demo_cost for the supplied teaching fixture. "
        "State that amounts are illustrative USD values. "
        "Do not claim to have inspected real cloud resources."
    ),
    tools=[McpToolset(
        connection_params=StdioConnectionParams(
            server_params=StdioServerParameters(
                command="mcp",
                args=["run", str(server_file), "--transport", "stdio"]
            ),
            timeout=10
        ),
        tool_filter=["get_demo_cost"]
    )]
)

Ask a question and inspect the tool trace

Run adk web locally from the directory containing cost_agent. Ask “What is compute’s monthly cost in the demo?” Inspect the tool arguments, result and answer.

If the tool is missing, check the active environment and server_file path. Test model authentication separately from tool connectivity.

Try the cases that should fail

Test an unknown service, a real bill and a VM-deletion request. Expect a bounded error or explanation. This tool has no real billing credentials or write operation.

03 / Replace the fixture with a data contract

Real billing access changes the problem

Define what “cost” means before querying it

Define the approved billing source, projects, dates, currency, credits and adjustments. Billing export tables differ in schema and delivery timing.

For get_service_cost(project, start_date, end_date), derive permitted projects from trusted identity context. Reject unauthorized scope, bound the date range and run a parameterized query against an approved table or view.

Return freshness and calculation basis with the amount. Keep currencies separate. A service total does not prove a VM is idle; investigate resources before proposing changes. See the FinOps guide.

Enforce access outside the model

  • Identity: authenticate the caller and choose a service identity or delegated user model that fits the data permissions.
  • Authorization: enforce tenant, project and tool scope in code and the underlying data service.
  • Inputs: validate enums, dates, record counts and query limits; avoid arbitrary SQL and shell execution.
  • Untrusted content: treat retrieved documents and tool output as evidence, not instructions that can change policy.
  • Credentials: use supported authentication and secret handling; never pass a token intended for another resource through as a shortcut.

Use the ADK security guide for identity and deterministic controls, and MCP security guidance for threats including token passthrough and local-server compromise.

Test the path to the answer as well as the answer

Test expected evidence and permitted tool behavior. ADK evaluation distinguishes tool-use trajectory from final-answer quality; check both.

A useful first regression set
CaseExpected result
Known fixture valueCorrect amount, currency and fictional-source label
Unauthorized projectDenied before data retrieval
Missing or delayed exportFreshness limitation stated; no invented total
Instruction hidden in retrieved textAccess policy unchanged
Tool timeoutBounded failure; no unlimited retry loop
Request to stop productionNo write action from a read-only agent

Make a wrong answer explainable

Record request ID, authenticated caller, selected tool, validated scope, duration, status and source freshness. Avoid unnecessary sensitive payloads. Monitor errors, latency, repeated calls and spend. These records should distinguish stale data, incorrect dates, a tool bug and a summary error.

04 / Change the runtime deliberately

Choose where the agent and MCP server live

A subprocess and a remote service have different lifecycles

The lab uses a stdio subprocess. Production can package a self-contained server or connect to a separate MCP service over Streamable HTTP. A remote service adds its own authentication, availability and release boundary.

Follow the ADK deployment guide for synchronous toolset definition, connection cleanup and timeouts. Select Cloud Run, GKE or Agent Runtime from operational requirements.

Check readiness for real users

Before release, verify restricted identities, bounded data access, reproducible dependencies, deployment tests, evaluations, traces, cost limits, incident ownership and rollback. Write tools need a separate authorization and approval design.

Harborlane’s first milestone is a traceable answer from a deliberately limited tool. Preserve that property as real data and users arrive. Continue with the production readiness checklist.

Implementation references

References checked 3 November 2026. Code is an educational local fixture reviewed against these APIs; it has not been deployed or authenticated against your cloud environment.

1 thought on “Build an ADK + MCP Cost Agent: A Practical Guide”

  1. The narrow contract advice (get_service_cost(service, month) instead of arbitrary SQL) is the most important line in the guide. We follow the same rule for a market-data MCP tool: each tool takes a stock or theme plus a time window and returns a bounded, labelled result, so the agent’s answer can always cite which call produced which number. Marking demo data explicitly, as you do with the $600 fixture, also prevents the model from presenting test values as real. 中文简介:熔岩概念股查询(亦提供 MCP 接口),按主题返回相关 A 股,供研究参考。

Leave a Comment

Your email address will not be published. Required fields are marked *