Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 161 additions & 0 deletions core/src/main/java/com/google/adk/tools/mcp/AbstractMcpTool.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* 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.
*/

package com.google.adk.tools.mcp;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.adk.tools.BaseTool;
import com.google.common.collect.ImmutableMap;
import com.google.genai.types.FunctionDeclaration;
import com.google.genai.types.Schema;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.Content;
import io.modelcontextprotocol.spec.McpSchema.JsonSchema;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
* Base class for MCP tools.
*
* @param <T> The type of the MCP session client.
*/
public abstract class AbstractMcpTool<T> extends BaseTool {

protected final Tool mcpTool;
protected final McpSessionManager mcpSessionManager;
protected final ObjectMapper objectMapper;

// Volatile ensures write visibility in the asynchronous chain for McpAsyncTool.
protected volatile T mcpSession;

protected AbstractMcpTool(
Tool mcpTool, T mcpSession, McpSessionManager mcpSessionManager, ObjectMapper objectMapper) {
super(
mcpTool == null ? "" : mcpTool.name(),
mcpTool == null ? "" : (mcpTool.description().isEmpty() ? "" : mcpTool.description()));

if (mcpTool == null) {
throw new IllegalArgumentException("mcpTool cannot be null");
}
if (mcpSession == null) {
throw new IllegalArgumentException("mcpSession cannot be null");
}
if (mcpSessionManager == null) {
throw new IllegalArgumentException("mcpSessionManager cannot be null");
}
if (objectMapper == null) {
throw new IllegalArgumentException("objectMapper cannot be null");
}
this.mcpTool = mcpTool;
this.mcpSession = mcpSession;
this.mcpSessionManager = mcpSessionManager;
this.objectMapper = objectMapper;
}

public T getMcpSession() {
return this.mcpSession;
}

protected Schema toGeminiSchema(JsonSchema openApiSchema) {
try {
return GeminiSchemaUtil.toGeminiSchema(openApiSchema, this.objectMapper);
} catch (IOException | IllegalArgumentException e) {
throw new IllegalArgumentException(
"Error generating function declaration for tool '" + this.name() + "': " + e.getMessage(),
e);
}
}

@Override
public Optional<FunctionDeclaration> declaration() {
try {
Schema schema = toGeminiSchema(this.mcpTool.inputSchema());
return Optional.ofNullable(schema)
.map(
value ->
FunctionDeclaration.builder()
.name(this.name())
.description(this.description())
.parameters(value)
.build());
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
return Optional.empty();
}
}

@SuppressWarnings("PreferredInterfaceType") // BaseTool.runAsync() returns Map<String, Object>
protected static Map<String, Object> wrapCallResult(
ObjectMapper objectMapper, String mcpToolName, CallToolResult callResult) {
if (callResult == null) {
return ImmutableMap.of("error", "MCP framework error: CallToolResult was null");
}

List<Content> contents = callResult.content();
Boolean isToolError = callResult.isError();

if (isToolError != null && isToolError) {
String errorMessage = "Tool execution failed.";
if (contents != null
&& !contents.isEmpty()
&& contents.get(0) instanceof TextContent textContent) {
if (textContent.text() != null && !textContent.text().isEmpty()) {
errorMessage += " Details: " + textContent.text();
}
}
return ImmutableMap.of("error", errorMessage);
}

if (contents == null || contents.isEmpty()) {
return ImmutableMap.of();
}

List<String> textOutputs = new ArrayList<>();
for (Content content : contents) {
if (content instanceof TextContent textContent) {
if (textContent.text() != null) {
textOutputs.add(textContent.text());
}
}
}

if (textOutputs.isEmpty()) {
return ImmutableMap.of(
"error",
"Tool '" + mcpToolName + "' returned content that is not TextContent.",
"content_details",
contents.toString());
}

List<Map<String, Object>> resultMaps = new ArrayList<>();
for (String textOutput : textOutputs) {
try {
resultMaps.add(
objectMapper.readValue(textOutput, new TypeReference<Map<String, Object>>() {}));
} catch (JsonProcessingException e) {
resultMaps.add(ImmutableMap.of("text", textOutput));
}
}
return ImmutableMap.of("text_output", resultMaps);
}
}
57 changes: 5 additions & 52 deletions core/src/main/java/com/google/adk/tools/mcp/McpAsyncTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,15 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.adk.JsonBaseModel;
import com.google.adk.tools.BaseTool;
import com.google.adk.tools.ToolContext;
import com.google.common.collect.ImmutableMap;
import com.google.genai.types.FunctionDeclaration;
import com.google.genai.types.Schema;
import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import io.modelcontextprotocol.spec.McpSchema.JsonSchema;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Single;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -45,16 +40,10 @@
* <p>This wraps a MCP Tool interface and an active MCP Session. It invokes the MCP Tool through
* executing the tool from remote MCP Session.
*/
public final class McpAsyncTool extends BaseTool {
public final class McpAsyncTool extends AbstractMcpTool<McpAsyncClient> {

private static final Logger logger = LoggerFactory.getLogger(McpAsyncTool.class);

Tool mcpTool;
// Volatile ensures write visibility in the asynchronous chain.
volatile McpAsyncClient mcpSession;
McpSessionManager mcpSessionManager;
ObjectMapper objectMapper;

/**
* Creates a new McpAsyncTool with the default ObjectMapper.
*
Expand All @@ -65,7 +54,7 @@ public final class McpAsyncTool extends BaseTool {
*/
public McpAsyncTool(
Tool mcpTool, McpAsyncClient mcpSession, McpSessionManager mcpSessionManager) {
this(mcpTool, mcpSession, mcpSessionManager, JsonBaseModel.getMapper());
super(mcpTool, mcpSession, mcpSessionManager, JsonBaseModel.getMapper());
}

/**
Expand All @@ -82,31 +71,7 @@ public McpAsyncTool(
McpAsyncClient mcpSession,
McpSessionManager mcpSessionManager,
ObjectMapper objectMapper) {
super(
mcpTool == null ? "" : mcpTool.name(),
mcpTool == null ? "" : (mcpTool.description().isEmpty() ? "" : mcpTool.description()));

if (mcpTool == null) {
throw new IllegalArgumentException("mcpTool cannot be null");
}
if (mcpSession == null) {
throw new IllegalArgumentException("mcpSession cannot be null");
}
if (objectMapper == null) {
throw new IllegalArgumentException("objectMapper cannot be null");
}
this.mcpTool = mcpTool;
this.mcpSession = mcpSession;
this.mcpSessionManager = mcpSessionManager;
this.objectMapper = objectMapper;
}

public McpAsyncClient getMcpSession() {
return this.mcpSession;
}

public Schema toGeminiSchema(JsonSchema openApiSchema) {
return Schema.fromJson(objectMapper.valueToTree(openApiSchema).toString());
super(mcpTool, mcpSession, mcpSessionManager, objectMapper);
}

private Single<McpSchema.InitializeResult> reintializeSession() {
Expand All @@ -129,16 +94,6 @@ private Single<McpSchema.InitializeResult> reintializeSession() {
.toFuture());
}

@Override
public Optional<FunctionDeclaration> declaration() {
return Optional.of(
FunctionDeclaration.builder()
.name(this.name())
.description(this.description())
.parameters(toGeminiSchema(this.mcpTool.inputSchema()))
.build());
}

@Override
public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContext toolContext) {
return Single.defer(
Expand All @@ -147,12 +102,10 @@ public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContex
this.mcpSession
.callTool(new CallToolRequest(this.name(), ImmutableMap.copyOf(args)))
.toFuture())
.map(
callResult ->
McpTool.wrapCallResult(this.objectMapper, this.name(), callResult))
.map(callResult -> wrapCallResult(this.objectMapper, this.name(), callResult))
.switchIfEmpty(
Single.fromCallable(
() -> McpTool.wrapCallResult(this.objectMapper, this.name(), null))))
() -> wrapCallResult(this.objectMapper, this.name(), null))))
.retryWhen(
errors ->
errors
Expand Down
Loading