Skip to content

Commit f2e9128

Browse files
author
wenhaozhao
committed
feat: add mcp-tools-java.md
1 parent 48a4abf commit f2e9128

File tree

1 file changed

+160
-0
lines changed

1 file changed

+160
-0
lines changed

docs/tools/mcp-tools-java.md

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
# Model Context Protocol Tools
2+
3+
This guide walks you through two ways of integrating Model Context Protocol (MCP) with ADK.
4+
5+
## What is Model Context Protocol (MCP)?
6+
7+
The Model Context Protocol (MCP) is an open standard designed to standardize how Large Language Models (LLMs) like Gemini and Claude communicate with external applications, data sources, and tools. Think of it as a universal connection mechanism that simplifies how LLMs obtain context, execute actions, and interact with various systems.
8+
9+
MCP follows a client-server architecture, defining how **data** (resources), **interactive templates** (prompts), and **actionable functions** (tools) are exposed by an **MCP server** and consumed by an **MCP client** (which could be an LLM host application or an AI agent).
10+
11+
This guide covers two primary integration patterns:
12+
13+
1. **Using Existing MCP Servers within ADK:** An ADK agent acts as an MCP client, leveraging tools provided by external MCP servers.
14+
2. **Exposing ADK Tools via an MCP Server:** Building an MCP server that wraps ADK tools, making them accessible to any MCP client.
15+
16+
## Prerequisites
17+
18+
Before you begin, ensure you have the following set up:
19+
20+
* **Set up ADK:** Follow the standard ADK [setup instructions](../get-started/quickstart.md/#venv-install) in the quickstart.
21+
* **Install/update Python/Java:** MCP requires Python version of 3.9 or higher for Python or Java 17+.
22+
* **Setup Node.js and npx:** Many community MCP servers are distributed as Node.js packages and run using `npx`. Install Node.js (which includes npx) if you haven't already. For details, see [https://nodejs.org/en](https://nodejs.org/en).
23+
* **Verify Installations:** Confirm `adk` and `npx` are in your PATH within the activated virtual environment:
24+
25+
```shell
26+
# Both commands should print the path to the executables.
27+
which adk
28+
which npx
29+
```
30+
31+
## 1. Using MCP servers with ADK agents (ADK as an MCP client) in `adk web`
32+
33+
This section demonstrates how to integrate tools from external MCP (Model Context Protocol) servers into your ADK agents. This is the **most common** integration pattern when your ADK agent needs to use capabilities provided by an existing service that exposes an MCP interface. You will see how the `MCPToolset` class can be directly added to your agent's `tools` list, enabling seamless connection to an MCP server, discovery of its tools, and making them available for your agent to use. These examples primarily focus on interactions within the `adk web` development environment.
34+
35+
### `MCPToolset` class
36+
37+
The `MCPToolset` class is ADK's primary mechanism for integrating tools from an MCP server. When you include an `MCPToolset` instance in your agent's `tools` list, it automatically handles the interaction with the specified MCP server. Here's how it works:
38+
39+
1. **Connection Management:** On initialization, `MCPToolset` establishes and manages the connection to the MCP server. This can be a local server process (using `StdioServerParameters` for communication over standard input/output) or a remote server (using `SseServerParams` for Server-Sent Events). The toolset also handles the graceful shutdown of this connection when the agent or application terminates.
40+
2. **Tool Discovery & Adaptation:** Once connected, `MCPToolset` queries the MCP server for its available tools (via the `list_tools` MCP method). It then converts the schemas of these discovered MCP tools into ADK-compatible `BaseTool` instances.
41+
3. **Exposure to Agent:** These adapted tools are then made available to your `LlmAgent` as if they were native ADK tools.
42+
4. **Proxying Tool Calls:** When your `LlmAgent` decides to use one of these tools, `MCPToolset` transparently proxies the call (using the `call_tool` MCP method) to the MCP server, sends the necessary arguments, and returns the server's response back to the agent.
43+
5. **Filtering (Optional):** You can use the `tool_filter` parameter when creating an `MCPToolset` to select a specific subset of tools from the MCP server, rather than exposing all of them to your agent.
44+
45+
The following examples demonstrate how to use `MCPToolset` within the `adk web` development environment. For scenarios where you need more fine-grained control over the MCP connection lifecycle or are not using `adk web`, refer to the "Using MCP Tools in your own Agent out of `adk web`" section later in this page.
46+
47+
### Example 1: STDIO MCP Server
48+
49+
This example demonstrates connecting to a local MCP server that provides file system operations.
50+
51+
Create an `McpToolsExample.java` file. The `MCPToolset` is instantiated directly within the `tools` list of your `LlmAgent`.
52+
53+
* **Important:** Replace `"/path/to/your/folder"` in the `args` list with the **absolute path** to an actual folder on your local system that the MCP server can access.
54+
55+
```java
56+
package com.google.adk.examples;
57+
58+
import com.google.adk.agents.LlmAgent;
59+
import com.google.adk.tools.ToolPredicate;
60+
import com.google.adk.tools.mcp.McpToolset;
61+
import io.modelcontextprotocol.client.transport.ServerParameters;
62+
63+
import java.util.Optional;
64+
65+
public class McpToolsExample {
66+
67+
/**
68+
* IMPORTANT: This MUST be an ABSOLUTE path to a folder the
69+
* npx process can access.
70+
* Replace with a valid absolute path on your system.
71+
* For example: "/Users/youruser/accessible_mcp_files"
72+
* or use a dynamically constructed absolute path:
73+
*/
74+
private static final String TARGET_FOLDER_PATH = "/path/to/your/folder";
75+
76+
public static void main(String[] args) {
77+
ServerParameters serverParameters = ServerParameters.builder("npx")
78+
.args(
79+
"-y", // Argument for npx to auto-confirm install
80+
"@modelcontextprotocol/server-filesystem",
81+
TARGET_FOLDER_PATH
82+
)
83+
.build();
84+
var tools = new McpToolset(
85+
serverParameters,
86+
// Optional: Filter which tools from the MCP server are exposed
87+
Optional.of((ToolPredicate) (tool, readonlyContext) -> true)
88+
);
89+
LlmAgent llmAgent = LlmAgent.builder()
90+
.name("filesystem_assistant_agent")
91+
.description("Help the user manage their files. You can list files, read files, etc.")
92+
.model("gemini-2.5-flash")
93+
.tools(tools)
94+
.build();
95+
}
96+
}
97+
98+
```
99+
100+
101+
### Example 2: SSE MCP Server
102+
103+
This example demonstrates connecting to the SSE MCP server.
104+
105+
Create an `McpToolsExample.java` file. The `MCPToolset` is instantiated directly within the `tools` list of your `LlmAgent`.
106+
107+
```java
108+
package com.google.adk.examples;
109+
110+
import com.google.adk.agents.LlmAgent;
111+
import com.google.adk.tools.ToolPredicate;
112+
import com.google.adk.tools.mcp.McpToolset;
113+
import com.google.adk.tools.mcp.SseServerParameters;
114+
115+
import java.time.Duration;
116+
import java.util.Map;
117+
import java.util.Optional;
118+
119+
public class McpToolsExample {
120+
121+
public static void main(String[] args) {
122+
SseServerParameters sseServerParameters = SseServerParameters.builder()
123+
.url("https://your.sse-mcp.server/sse")
124+
.headers(Map.of(
125+
"Authorization", "Bearer your-mcp-api-key" // Optional: pass headers to you sse server
126+
))
127+
.timeout(Duration.ofSeconds(10L)) // timeout to connect to sse server
128+
.sseReadTimeout(Duration.ofSeconds(30L)) // timeout to tool call
129+
.build();
130+
var tools = new McpToolset(
131+
sseServerParameters,
132+
// Optional: Filter which tools from the MCP server are exposed
133+
Optional.of((ToolPredicate) (tool, readonlyContext) -> true)
134+
);
135+
LlmAgent llmAgent = LlmAgent.builder()
136+
.name("...")
137+
.description("...")
138+
.model("gemini-2.5-flash")
139+
.tools(tools)
140+
.build();
141+
}
142+
}
143+
144+
```
145+
146+
## Key considerations
147+
148+
When working with MCP and ADK, keep these points in mind:
149+
150+
* **Protocol vs. Library:** MCP is a protocol specification, defining communication rules. ADK is a Python/Java library/framework for building agents. MCPToolset bridges these by implementing the client side of the MCP protocol within the ADK framework. Conversely, building an MCP server using the model-context-protocol library.
151+
* **ADK Tools vs. MCP Tools:**
152+
* ADK Tools (BaseTool, FunctionTool, AgentTool, etc.) are Python/Java objects designed for direct use within the ADK's LlmAgent and Runner.
153+
* MCP Tools are capabilities exposed by an MCP Server according to the protocol's schema. MCPToolset makes these look like ADK tools to an LlmAgent.
154+
* Langchain/CrewAI Tools are specific implementations within those libraries, often simple functions or classes, lacking the server/protocol structure of MCP. ADK offers wrappers (LangchainTool, CrewaiTool) for some interoperability.
155+
156+
## Further Resources
157+
158+
* [Model Context Protocol Documentation](https://modelcontextprotocol.io/ )
159+
* [MCP Specification](https://modelcontextprotocol.io/specification/)
160+
* [MCP Python SDK & Examples](https://github.com/modelcontextprotocol/)

0 commit comments

Comments
 (0)