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.
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
| Component | Its job | It does not decide |
|---|---|---|
| Gemini model | Interpret the request and propose the next step | Which customer the caller is authorized to access |
| ADK application | Define agent instructions, tool access and execution behavior | The truth of a billing record |
| MCP server | Expose typed tools through a standard protocol | Business access rules automatically |
| Data adapter | Validate scope and retrieve a bounded result | Whether 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
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.
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 checkCreate 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.
| Case | Expected result |
|---|---|
| Known fixture value | Correct amount, currency and fictional-source label |
| Unauthorized project | Denied before data retrieval |
| Missing or delayed export | Freshness limitation stated; no invented total |
| Instruction hidden in retrieved text | Access policy unchanged |
| Tool timeout | Bounded failure; no unlimited retry loop |
| Request to stop production | No 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
- ADK Python quickstart
- ADK MCP tools and deployment requirements
- MCP Python SDK v2 and first steps
- ADK dependency definitions
- ADK security and evaluation
- Cloud Billing export schemas and delivery behavior
- MCP security best practices
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.

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 股,供研究参考。