Connect a read-only MCP server to an ADK agent
Connect a local read-only MCP server, restrict which tools are exposed, and replace it with a mock in tests.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.
In short
The Model Context Protocol (MCP) is an open standard for giving AI apps tools and data through a separate server process. In ADK you attach an MCP server with McpToolset, which discovers the server's tools and offers them to the agent. You stay in charge: filter which tools are exposed, make sure the server itself can only read, set timeouts, and swap the server for a fake in tests.
Think of it like this: McpToolset is a power strip: the MCP server may have many sockets, but tool_filter decides which ones are actually wired to your agent.
Explained simply
Your support agent already has Python function tools. Sometimes the tool you need already exists as a separate program that speaks MCP, the Model Context Protocol. MCP is an open standard: one side is a client (your agent app), the other side is a server that offers tools, files or prompts.
ADK connects to an MCP server with a class called McpToolset. You tell it how to reach the server, for example start python docs_server.py as a child process, and it asks the server which tools it has. Those tools then show up for your agent like any other tool.
The risk is that an MCP server may offer more than you want. A file server might be able to write and delete as well as read. So you pass a tool_filter with the exact tool names you allow, and you run the server with permissions that can only read.
For this course you build a tiny local MCP server over the public product docs, with two read-only tools: search_docs and get_doc. Nothing paid is needed. In tests you do not start the server at all; you give the agent a fake tool with the same name and fixed answers.
Press Play on a diagram to walk through it one step at a time.
- 1LlmAgent
Sees only the tools the toolset hands it
- 2McpToolset with tool_filter
Allow-list of tool names, or a predicate
- 3Connection params
Stdio or Streamable HTTP, with a timeout
- 4MCP server process
Defines the tools and validates arguments
- 5Data source
Read-only file folder or read-only DB role
- Code lives in your app
- Typed in Python, easy to unit test
- No extra process
- Best for logic you own
- Code lives in a separate server
- Shared by many apps and clients
- Extra process or network hop
- Best for tools other teams maintain
In depth
How an MCP connection works
MCP has three roles. The host is your application, here the ADK agent app. Inside it, an MCP client keeps one connection to one MCP server. The server offers three kinds of things: tools (functions the model can call), resources (data such as files) and prompts (reusable templates).
A session starts with an initialize handshake, where both sides agree on a protocol version and capabilities. Then the client calls tools/list to discover tools, each with a name, description and JSON Schema for its input. When the model picks a tool, the client sends tools/call with arguments and gets a result back.
There are two common transports. Stdio starts the server as a child process and talks over its standard input and output; it is simple and local. Streamable HTTP talks to a server over the network, which is how hosted MCP servers work. In ADK, constructing McpToolset does not connect yet; it opens the session the first time the tools are needed.
- McpToolset client to MCP server: initialize (version, capabilities)1initialize (version, capabilities)
- McpToolset client to MCP server: tools/list2tools/list
- MCP server to McpToolset client: search_docs, get_doc, delete_doc3search_docs, get_doc, delete_doc
- McpToolset client to ADK agent: Only search_docs and get_doc after filter4Only search_docs and get_doc after filter
- ADK agent to McpToolset client: Model picks search_docs(query)5Model picks search_docs(query)
- McpToolset client to MCP server: tools/call search_docs6tools/call search_docs
- MCP server to McpToolset client: Matching doc IDs and snippets7Matching doc IDs and snippets
Filtering tools: list or predicate
In google-adk 2.15.1, McpToolset takes tool_filter as either a list of tool names or a predicate. A list is the clearest: only tools whose names appear are offered. A predicate is a callable that receives each tool and an optional read-only context and returns True to keep it; use it when the rule depends on a name prefix or on something in session state.
There is also tool_name_prefix, which adds a prefix such as docs_ to each tool name. That avoids clashes when two servers both have a tool called search, and it makes traces easier to read.
Prefer an allow-list to a block-list. If the server owner adds an export_all tool next month, an allow-list keeps it out until you review it. A block-list lets it in by default.
- tool_filter=["search_docs", "get_doc"]: explicit allow-list
- tool_filter=lambda tool, ctx=None: tool.name.startswith("get_")
- tool_name_prefix="docs_" to avoid name clashes
- Review the allow-list whenever the server version changes
Making read-only real
A filter controls what the agent may call. It does not control what the server process can do. If the server runs with your developer credentials and has a write tool, a bug or a future change could still use them. Real limits sit below the agent.
For a docs server, give the process a folder of public docs and nothing else, ideally mounted read-only. For a database-backed server, connect with a role that only has SELECT on the tables it needs. For a remote server, use a token whose scopes allow reading only. MCP tool annotations such as readOnlyHint describe intent, but the spec treats them as hints from the server, not guarantees, so do not rely on them as your control.
Finally, treat tool results as untrusted text. A doc page could contain words that look like instructions. The next module covers how to keep such text from widening what the agent may do.
Lifecycle, timeouts and testing
Set a timeout on the connection params, for example StdioConnectionParams(..., timeout=5), so a server that fails to start does not hang your app. The ADK docs ask you to define McpToolset synchronously in agent.py, so adk web and deployment tools can load it.
When you run the agent with your own Runner rather than adk web, close the toolset on shutdown with await toolset.close(), for example in a FastAPI lifespan handler. Otherwise child processes can be left behind.
For tests, do not start the real server. Replace the toolset with plain function tools that have the same names and return fixed results from a fixture file. Your tests then check agent behaviour, filters and error handling quickly. Keep one separate integration test that starts the real local server, lists its tools and asserts that the filtered list is exactly what you expect.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Run a local MCP server~35m
- 2Attach it with an MCP toolset~35m
- 3Filter the exposed tools~35m
- 4Keep permissions read-only~35m
- 5Mock the server in tests~35m
Key points
- Install the extra: pip install "google-adk[mcp]==2.15.1"; McpToolset lives in google.adk.tools.mcp_tool.
- Use StdioConnectionParams for a local server process and StreamableHTTPConnectionParams for a remote one.
- tool_filter takes a list of tool names or a predicate; anything not allowed never reaches the model.
- A filter limits what the agent can call, but only server-side permissions make the data truly read-only.
- Outside adk web, close the toolset with await toolset.close() when your app shuts down.
Key terms
Tap a card to flip it. 0/6 known
Examples
from google.adk.agents import Agent
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from mcp import StdioServerParameters
docs_mcp = McpToolset(
connection_params=StdioConnectionParams(
server_params=StdioServerParameters(command="python", args=["docs_server.py"]),
timeout=5,
),
tool_filter=["search_docs", "get_doc"], # nothing else is exposed
)
root_agent = Agent(name="support_agent", model="gemini-flash-latest",
instruction="Answer from product docs only.", tools=[docs_mcp])docs_server.py is your own local MCP server; the model name is a placeholder for the one your project uses.
A tiny read-only docs MCP server
Prerequisites: pip install "google-adk[mcp]==2.15.1", which brings the mcp package, and a docs folder with a few public Markdown files. The server below uses FastMCP from the official MCP Python SDK and offers two read-only tools. Steps: save it as docs_server.py next to your agent, run the agent with adk web, and ask about a feature. Evidence: the trace shows a search_docs call and a get_doc call with a doc ID. Cleanup: stop adk web; the child process stops with it.
from pathlib import Path
from mcp.server.fastmcp import FastMCP
DOCS = Path("docs") # public product docs only
mcp = FastMCP("product-docs")
@mcp.tool()
def search_docs(query: str) -> list[str]:
"""Return IDs of docs whose text contains the query."""
return [p.stem for p in DOCS.glob("*.md") if query.lower() in p.read_text().lower()][:5]
@mcp.tool()
def get_doc(doc_id: str) -> str:
"""Return one doc by ID."""
return (DOCS / f"{Path(doc_id).name}.md").read_text()
if __name__ == "__main__":
mcp.run() # stdio transport by defaultProving the filter in a test
This integration test starts the real server once, asks the toolset for its tools and checks that only the allowed names come back. If the server gains a new tool, the test still passes because the filter hides it; if someone widens the filter, the test fails and forces a review. Run it in CI separately from the fast unit tests, which use fakes. Cleanup is the close() call in finally.
import pytest
from support_agent.agent import docs_mcp
@pytest.mark.asyncio
async def test_only_read_tools_exposed():
try:
tools = await docs_mcp.get_tools()
assert sorted(t.name for t in tools) == ["get_doc", "search_docs"]
finally:
await docs_mcp.close()Quick reference
- pip install "google-adk[mcp]==2.15.1" adds the MCP client libraries
- from google.adk.tools.mcp_tool import McpToolset
- Local server: StdioConnectionParams(server_params=StdioServerParameters(...), timeout=5)
- Remote server: StreamableHTTPConnectionParams(url=..., headers=...)
- tool_filter: list of names or predicate(tool, readonly_context) -> bool
- Outside adk web, call await toolset.close() on shutdown
- readOnlyHint is a hint from the server, not an access control
Common mistakes
- Connecting a broad server (full file system, database admin) and trusting the model to only read.
- No tool_filter, so new tools added to the server later appear in your agent without review.
- Tests that start the real server, making them slow and flaky; test with a fake toolset or fixture server.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Attach the docs MCP server to your agent with a filter that allows only search_docs.
- Exercise 2medium
Replace the MCP toolset with fakes in unit tests so no server process starts, and check the agent cites the fixture doc ID.
- Exercise 3hard
Write a predicate filter that only exposes tools whose names start with get_ or search_, and a test that a server tool called delete_doc is hidden.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is MCP specific to Google or ADK?
- No. MCP is an open protocol used by many AI apps and frameworks. ADK is one client; your MCP server could also be used by other MCP clients.
- Can ADK agents be MCP servers too?
- You can expose ADK tools through an MCP server you write with the MCP SDK. This topic only covers the client side: using an MCP server from an ADK agent.
- Should I use stdio or HTTP?
- Use stdio for a local server that ships with your app, as in this course. Use Streamable HTTP when the server runs elsewhere and is shared, and then add authentication headers and network limits.