-
Notifications
You must be signed in to change notification settings - Fork 2.4k
fix(tools): Add proper cleanup for AgentTool to prevent MCP session errors #3411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+325
−0
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| # AgentTool with MCP Demo (SSE Mode) | ||
|
|
||
| This demo shows how `AgentTool` works with MCP (Model Context Protocol) toolsets using **SSE mode**. | ||
|
|
||
| ## SSE vs Stdio Mode | ||
|
|
||
| This demo uses **SSE (Server-Sent Events) mode** where the MCP server runs as a separate HTTP server: | ||
| - **Remote connection** - Connects to server via HTTP | ||
| - **Separate process** - Server must be started manually | ||
| - **Network communication** - Uses HTTP/SSE for messaging | ||
|
|
||
| For the **stdio (subprocess) version**, see [mcp_in_agent_tool_stdio](../mcp_in_agent_tool_stdio/). | ||
|
|
||
| ## Setup | ||
|
|
||
| **Start the MCP simple-tool server in SSE mode** (in a separate terminal): | ||
| ```bash | ||
| # Run the server using uvx (no installation needed) | ||
| # Port 3000 avoids conflict with adk web (which uses 8000) | ||
| uvx --from 'git+https://github.com/modelcontextprotocol/python-sdk.git#subdirectory=examples/servers/simple-tool' \ | ||
| mcp-simple-tool --transport sse --port 3000 | ||
| ``` | ||
|
|
||
| The server should be accessible at `http://localhost:3000/sse`. | ||
|
|
||
| ## Running the Demo | ||
|
|
||
| ```bash | ||
| adk web contributing/samples | ||
| ``` | ||
|
|
||
| Then select **mcp_in_agent_tool_remote** from the list and interact with the agent. | ||
|
|
||
| ## Try These Prompts | ||
|
|
||
| This demo uses **Gemini 2.5 Flash** as the model. Try these prompts: | ||
|
|
||
| 1. **Check available tools:** | ||
| ``` | ||
| What tools do you have access to? | ||
| ``` | ||
|
|
||
| 2. **Fetch and summarize JSON Schema specification:** | ||
| ``` | ||
| Use the mcp_helper to fetch https://json-schema.org/specification and summarize the key features of JSON Schema | ||
| ``` | ||
|
|
||
| ## Architecture | ||
|
|
||
| ``` | ||
| main_agent (root_agent) | ||
| │ | ||
| └── AgentTool wrapping: | ||
| │ | ||
| └── mcp_helper (sub_agent) | ||
| │ | ||
| └── McpToolset (SSE connection) | ||
| │ | ||
| └── http://localhost:3000/sse | ||
| │ | ||
| └── MCP simple-tool server | ||
| │ | ||
| └── Website Fetcher Tool | ||
| ``` | ||
|
|
||
| ## Related | ||
|
|
||
| - **Issue:** [#1112 - Using agent as tool outside of adk web doesn't exit cleanly](https://github.com/google/adk-python/issues/1112) | ||
| - **Related Issue:** [#929 - LiteLLM giving error with OpenAI models and Grafana's MCP server](https://github.com/google/adk-python/issues/929) | ||
| - **Stdio Version:** [mcp_in_agent_tool_stdio](../mcp_in_agent_tool_stdio/) - Uses local subprocess connection |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from . import agent |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from google.adk.agents import Agent | ||
| from google.adk.tools import AgentTool | ||
| from google.adk.tools.mcp_tool import McpToolset | ||
| from google.adk.tools.mcp_tool.mcp_session_manager import SseConnectionParams | ||
|
|
||
| # Create MCP toolset | ||
| # This uses the simple-tool MCP server via SSE | ||
| # You need to start the MCP server separately (see README.md) | ||
| mcp_toolset = McpToolset( | ||
| connection_params=SseConnectionParams( | ||
| url="http://localhost:3000/sse", | ||
| timeout=10.0, | ||
| sse_read_timeout=300.0, | ||
| ) | ||
| ) | ||
|
|
||
| # Create sub-agent with MCP tools | ||
| # This agent has direct access to MCP tools | ||
| sub_agent = Agent( | ||
| name="mcp_helper", | ||
| model="gemini-2.5-flash", | ||
| description=( | ||
| "A helpful assistant with access to MCP tools for fetching websites." | ||
| ), | ||
| instruction="""You are a helpful assistant with access to MCP tools. | ||
| When the user asks for help: | ||
| 1. Explain what tools you have available (website fetching) | ||
| 2. Use the appropriate tool if needed | ||
| 3. Provide clear and helpful responses | ||
| You have access to a website fetcher tool via MCP. Use it to fetch and return website content.""", | ||
| tools=[mcp_toolset], | ||
| ) | ||
|
|
||
| # Wrap sub-agent as an AgentTool | ||
| # This allows the main agent to delegate tasks to the sub-agent | ||
| # The sub-agent has access to MCP tools for fetching websites | ||
| mcp_agent_tool = AgentTool(agent=sub_agent) | ||
|
|
||
| # Create main agent | ||
| # This agent can delegate to the sub-agent via AgentTool | ||
| root_agent = Agent( | ||
| name="main_agent", | ||
| model="gemini-2.5-flash", | ||
| description="Main agent that can delegate to a sub-agent with MCP tools.", | ||
| instruction="""You are a helpful assistant. You have access to a sub-agent (mcp_helper) | ||
| that has MCP tools for fetching websites. | ||
| When the user asks for help: | ||
| - If they need to fetch a website, call the mcp_helper tool | ||
| - Otherwise, respond directly | ||
| Always be helpful and explain what you're doing.""", | ||
| tools=[mcp_agent_tool], | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| # AgentTool with MCP Demo (Stdio Mode) | ||
|
|
||
| This demo shows how `AgentTool` works with MCP (Model Context Protocol) toolsets using **stdio mode**. | ||
|
|
||
| ## Stdio vs SSE Mode | ||
|
|
||
| This demo uses **stdio mode** where the MCP server runs as a subprocess: | ||
| - **Simpler setup** - No need to start a separate server | ||
| - **Auto-launched** - Server starts automatically when agent runs | ||
| - **Local process** - Uses stdin/stdout for communication | ||
|
|
||
| For the **SSE (remote server) version**, see [mcp_in_agent_tool_remote](../mcp_in_agent_tool_remote/). | ||
|
|
||
| ## Setup | ||
|
|
||
| **No installation required!** The MCP server will be launched automatically using `uvx` when you run the agent. | ||
|
|
||
| The demo uses `uvx` to fetch and run the MCP simple-tool server directly from the GitHub repository's subdirectory: | ||
| ```bash | ||
| uvx --from 'git+https://github.com/modelcontextprotocol/python-sdk.git#subdirectory=examples/servers/simple-tool' \ | ||
| mcp-simple-tool | ||
| ``` | ||
|
|
||
| This happens automatically via the stdio connection when the agent starts. | ||
|
|
||
| ## Running the Demo | ||
|
|
||
| ```bash | ||
| adk web contributing/samples | ||
| ``` | ||
|
|
||
| Then select **mcp_in_agent_tool_stdio** from the list and interact with the agent. | ||
|
|
||
| ## Try These Prompts | ||
|
|
||
| This demo uses **Gemini 2.5 Flash** as the model. Try these prompts: | ||
|
|
||
| 1. **Check available tools:** | ||
| ``` | ||
| What tools do you have access to? | ||
| ``` | ||
|
|
||
| 2. **Fetch and summarize JSON Schema specification:** | ||
| ``` | ||
| Use the mcp_helper to fetch https://json-schema.org/specification and summarize the key features of JSON Schema | ||
| ``` | ||
|
|
||
| ## Architecture | ||
|
|
||
| ``` | ||
| main_agent (root_agent) | ||
| │ | ||
| └── AgentTool wrapping: | ||
| │ | ||
| └── mcp_helper (sub_agent) | ||
| │ | ||
| └── McpToolset (stdio connection) | ||
| │ | ||
| └── MCP Server (subprocess via uvx) | ||
| │ | ||
| └── uvx --from git+...#subdirectory=... mcp-simple-tool | ||
| │ | ||
| └── Website Fetcher Tool | ||
| ``` | ||
|
|
||
| ## Related | ||
|
|
||
| - **Issue:** [#1112 - Using agent as tool outside of adk web doesn't exit cleanly](https://github.com/google/adk-python/issues/1112) | ||
| - **Related Issue:** [#929 - LiteLLM giving error with OpenAI models and Grafana's MCP server](https://github.com/google/adk-python/issues/929) | ||
| - **SSE Version:** [mcp_in_agent_tool_remote](../mcp_in_agent_tool_remote/) - Uses remote server connection |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from . import agent |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from google.adk.agents import Agent | ||
| from google.adk.tools import AgentTool | ||
| from google.adk.tools.mcp_tool import McpToolset | ||
| from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams | ||
| from mcp import StdioServerParameters | ||
|
|
||
| # Create MCP toolset | ||
| # This uses the simple-tool MCP server via stdio | ||
| # The server will be launched automatically using uvx from the subdirectory | ||
| mcp_toolset = McpToolset( | ||
| connection_params=StdioConnectionParams( | ||
| server_params=StdioServerParameters( | ||
| command="uvx", | ||
| args=[ | ||
| "--from", | ||
| "git+https://github.com/modelcontextprotocol/python-sdk.git#subdirectory=examples/servers/simple-tool", | ||
| "mcp-simple-tool", | ||
| ], | ||
| ), | ||
| timeout=10.0, | ||
| ) | ||
| ) | ||
|
Comment on lines
+24
to
+36
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To improve readability and make the configuration easier to manage, consider extracting hardcoded values like the Git repository URL, command arguments, and model name into constants. For example: # At the top of the file
_MCP_SIMPLE_TOOL_REPO = "git+https://github.com/modelcontextprotocol/python-sdk.git#subdirectory=examples/servers/simple-tool"
_MCP_SIMPLE_TOOL_COMMAND = "mcp-simple-tool"
_CONNECTION_TIMEOUT = 10.0
_MODEL_NAME = "gemini-2.5-flash"
# In the McpToolset definition
mcp_toolset = McpToolset(
connection_params=StdioConnectionParams(
server_params=StdioServerParameters(
command="uvx",
args=[
"--from",
_MCP_SIMPLE_TOOL_REPO,
_MCP_SIMPLE_TOOL_COMMAND,
],
),
timeout=_CONNECTION_TIMEOUT,
)
)
# In agent definitions
sub_agent = Agent(
model=_MODEL_NAME,
# ...
)
root_agent = Agent(
model=_MODEL_NAME,
# ...
) |
||
|
|
||
| # Create sub-agent with MCP tools | ||
| # This agent has direct access to MCP tools | ||
| sub_agent = Agent( | ||
| name="mcp_helper", | ||
| model="gemini-2.5-flash", | ||
| description=( | ||
| "A helpful assistant with access to MCP tools for fetching websites." | ||
| ), | ||
| instruction="""You are a helpful assistant with access to MCP tools. | ||
| When the user asks for help: | ||
| 1. Explain what tools you have available (website fetching) | ||
| 2. Use the appropriate tool if needed | ||
| 3. Provide clear and helpful responses | ||
| You have access to a website fetcher tool via MCP. Use it to fetch and return website content.""", | ||
| tools=[mcp_toolset], | ||
| ) | ||
|
|
||
| # Wrap sub-agent as an AgentTool | ||
| # This allows the main agent to delegate tasks to the sub-agent | ||
| # The sub-agent has access to MCP tools for fetching websites | ||
| mcp_agent_tool = AgentTool(agent=sub_agent) | ||
|
|
||
| # Create main agent | ||
| # This agent can delegate to the sub-agent via AgentTool | ||
| root_agent = Agent( | ||
| name="main_agent", | ||
| model="gemini-2.5-flash", | ||
| description="Main agent that can delegate to a sub-agent with MCP tools.", | ||
| instruction="""You are a helpful assistant. You have access to a sub-agent (mcp_helper) | ||
| that has MCP tools for fetching websites. | ||
| When the user asks for help: | ||
| - If they need to fetch a website, call the mcp_helper tool | ||
| - Otherwise, respond directly | ||
| Always be helpful and explain what you're doing.""", | ||
| tools=[mcp_agent_tool], | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To improve maintainability and readability, consider extracting hardcoded values like the URL, timeouts, and the model name (
'gemini-2.5-flash') into module-level constants. This centralizes configuration, making it easier to manage and update.For example: