---
title: "Building an MCP Client Toolset for Local and Stdio MCP Servers"
date: "2026-11-28T09:35:00+07:00"
description: "Run local stdio MCP servers as agent tools — StdioConnectionParams, subprocess lifecycle, tool curation, diagnostics, and how it compares to using an MCP session directly."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/mcp-client-toolset-stdio-local-servers.jpg"
alt: "Local terminal window wired into a rack of service modules"
tags: ['google-adk', 'adk-tools', 'mcp', 'stdio', 'local-development']
---

The fastest path to a working agent with real capabilities is a stdio MCP server: one `npx -y` command, a child process that speaks JSON-RPC over stdin/stdout, and a client that turns its advertised tools into agent tools. No port, no TLS, no deployment target — which is exactly why stdio is the default for local development and single-host agents, and exactly why the details (timeouts, stderr, cleanup, filtering) decide whether it stays reliable.

This tutorial covers building the client side for local and stdio MCP servers: connection parameters, the subprocess lifecycle, curating and namespacing discovered tools, diagnostics when a server dies, and when to bypass the toolset and drive an MCP session directly.

## The stdio connection shape

```python
import os
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

TARGET_FOLDER = os.path.abspath("./accessible_files")

toolset = McpToolset(
    connection_params=StdioConnectionParams(
        server_params=StdioServerParameters(
            command="npx",
            args=["-y", "@modelcontextprotocol/server-filesystem", TARGET_FOLDER],
            env=None,                      # inherits your environment by default
        ),
        timeout=5,                         # handshake/request timeout, seconds
    ),
    tool_filter=["list_directory", "read_file"],
)

root_agent = LlmAgent(
    model="gemini-flash-latest",
    name="filesystem_assistant",
    instruction="Help users manage local files.",
    tools=[toolset],
)
```

Two objects, distinct jobs: `StdioServerParameters` describes *how to spawn the process* (command, args, env), while `StdioConnectionParams` wraps it with *client-side behaviour* (timeout). `tool_filter` runs after discovery — the server still advertises everything, but only the listed tools reach the model's schema list.

Prerequisites: `pip install "google-adk[mcp]"`, Python 3.10+, and `npx` on PATH (`Get-Command adk` / `Get-Command npx` on Windows).

## Lifecycle: what actually happens

1. Construction does nothing network-wise — no process yet.
2. First use (the agent needs its tools) spawns the subprocess and performs the MCP initialize handshake + `list_tools`.
3. Each model tool call is serialised to JSON-RPC on the child's stdin; the result comes back on stdout.
4. `await toolset.close()` (or agent/process termination under `adk web`) ends the session and reaps the child.

Three consequences worth designing around:

- **Timeouts are not optional.** A hung `npx` download stalls the turn; set `timeout` explicitly rather than accepting defaults.
- **Orphan processes accumulate** in long-lived runners. Anything not running under `adk web` needs `try/finally: await toolset.close()`.
- **Sessions are not sticky.** Restoration re-initialises the connection on demand — never cache a live session across restarts.

## Curating the tool surface

Three mechanisms, in order of how often you need them:

| Mechanism | Purpose | Example |
|---|---|---|
| `tool_filter=[...]` | Least privilege — the model never sees unwanted tools | `["list_directory", "read_file"]` |
| `tool_name_prefix="pg_"` | Resolve collisions across multiple servers | `query` → `pg_query` |
| `require_confirmation=...` | Human gate for destructive operations | predicate matching `drop`/`delete` |

Attaching two stdio servers to one agent is just two toolsets — and `tool_name_prefix` is what stops two servers both advertising `query` and `search`: a Postgres toolset with `tool_name_prefix="pg_"` yields `pg_query`, `pg_list_tables`; a GitHub one with `"gh_"` yields `gh_search_repositories`. `tool_filter` is a security control, not tidiness: every tool you expose is an action the model can be talked into taking.

## When a stdio server dies

Subprocess failures surface as stderr text, and ADK's default is to log it through normal logging. For debugging, `errlog` redirects the child's stderr to a file you control — the single most useful knob when `npx` exits before the handshake:

```python
error_file = open("mcp_server_errors.log", "a")
try:
    toolset = McpToolset(connection_params=..., errlog=error_file)
    ...
finally:
    await toolset.close()
    error_file.close()
```

The usual suspects, in order: package name typo (`npx` fetch failing), the server exiting on unsupported protocol version, a missing `env` variable the server requires, and a target directory that does not exist. `tool_filter` mismatches produce a *different* symptom — the connection succeeds but the model says it has no such tool.

## Environment-aware selection

The same agent can be stdio today and remote-HTTP tomorrow without code changes: pick `StreamableHTTPConnectionParams` when `K_SERVICE` is set (Cloud Run — bearer header, `timeout=5`, `sse_read_timeout=300`), and `StdioConnectionParams` otherwise, based on a local environment variable or an explicit `mode` flag. Keep the branch in one factory function so `agent.py` stays declarative — which is also what the deployment rule (define the toolset synchronously in `agent.py`) expects.

## Or skip the toolset entirely

For a single grounded call that doesn't need an agent, the Gen AI SDK accepts an MCP session as a tool directly — the SDK discovers the schemas and performs automatic function calling:

```python
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai

client = genai.Client()
server_params = StdioServerParameters(command="npx", args=["-y", "@philschmid/weather-mcp"])

async def run(prompt: str):
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            response = await client.aio.models.generate_content(
                model="gemini-flash-latest",
                contents=prompt,
                config={"tools": [session]},
            )
            print(response.text)
```

| Client approach | Best for | You own |
|---|---|---|
| ADK `McpToolset` | Long-lived agents, multi-turn sessions, filters/auth/confirmation | Tool curation and `close()` |
| Gen AI SDK `tools=[session]` | One-shot questions over a local server | The session lifecycle around each call |
| Hand-rolled `mcp.ClientSession` | Custom protocols, non-model consumers | Everything, including schema adaptation |

If you need that last row's control in ADK, build a [custom MCP client toolset](/blog/building-a-custom-mcp-client-for-your-agent-runtime) and plug it into the same `tools` list.

## Takeaways

- `StdioConnectionParams` wraps a `StdioServerParameters` spawn spec plus client timeouts; construction is lazy, the process starts on first use.
- Set `timeout` explicitly and always `await toolset.close()` outside `adk web` — hung spawns and orphaned children are the two classic stdio failures.
- `tool_filter` is least privilege, `tool_name_prefix` is collision avoidance across servers, `require_confirmation` is the approval gate.
- Redirect stderr with `errlog` when a server won't handshake; most stdio bugs are package or environment problems, not protocol problems.
- Choose the client per job: toolset for agents, `tools=[session]` for one-shot calls, raw session only when you need the wire for yourself.

## Further reading

- [Connecting MCP servers to ADK agents](/blog/connect-mcp-servers-to-adk-agents)
- [Building a custom MCP client for your agent runtime](/blog/building-a-custom-mcp-client-for-your-agent-runtime)
- [MCP vs direct function calling](/blog/mcp-vs-direct-function-calling)
- [MCP servers in production](/blog/mcp-servers-in-production)
- [Securing MCP servers: tokens, scopes, and least privilege](/blog/securing-mcp-servers-tokens-scopes-and-least-privilege)
- [ADK: Advanced MCP configuration](https://adk.dev/tools-custom/mcp-tools/advanced/)
