|
| 1 | +/* |
| 2 | + * Copyright 2025 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.adk.tools.mcp; |
| 18 | + |
| 19 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; |
| 20 | + |
| 21 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 22 | +import com.google.adk.JsonBaseModel; |
| 23 | +import com.google.adk.tools.BaseTool; |
| 24 | +import com.google.adk.tools.ToolContext; |
| 25 | +import com.google.common.collect.ImmutableMap; |
| 26 | +import com.google.genai.types.FunctionDeclaration; |
| 27 | +import com.google.genai.types.Schema; |
| 28 | +import io.modelcontextprotocol.client.McpAsyncClient; |
| 29 | +import io.modelcontextprotocol.spec.McpSchema; |
| 30 | +import io.modelcontextprotocol.spec.McpSchema.CallToolRequest; |
| 31 | +import io.modelcontextprotocol.spec.McpSchema.JsonSchema; |
| 32 | +import io.modelcontextprotocol.spec.McpSchema.Tool; |
| 33 | +import io.reactivex.rxjava3.core.Maybe; |
| 34 | +import io.reactivex.rxjava3.core.Single; |
| 35 | +import java.util.Map; |
| 36 | +import java.util.Optional; |
| 37 | +import org.slf4j.Logger; |
| 38 | +import org.slf4j.LoggerFactory; |
| 39 | + |
| 40 | +// TODO(b/413489523): Add support for auth. This is a TODO for Python as well. |
| 41 | + |
| 42 | +/** |
| 43 | + * Initializes a MCP tool. |
| 44 | + * |
| 45 | + * <p>This wraps a MCP Tool interface and an active MCP Session. It invokes the MCP Tool through |
| 46 | + * executing the tool from remote MCP Session. |
| 47 | + */ |
| 48 | +public final class McpAsyncTool extends BaseTool { |
| 49 | + |
| 50 | + private static final Logger logger = LoggerFactory.getLogger(McpAsyncTool.class); |
| 51 | + |
| 52 | + Tool mcpTool; |
| 53 | + // Volatile ensures write visibility in the asynchronous chain. |
| 54 | + volatile McpAsyncClient mcpSession; |
| 55 | + McpSessionManager mcpSessionManager; |
| 56 | + ObjectMapper objectMapper; |
| 57 | + |
| 58 | + /** |
| 59 | + * Creates a new McpAsyncTool with the default ObjectMapper. |
| 60 | + * |
| 61 | + * @param mcpTool The MCP tool to wrap. |
| 62 | + * @param mcpSession The MCP session to use to call the tool. |
| 63 | + * @param mcpSessionManager The MCP session manager to use to create new sessions. |
| 64 | + * @throws IllegalArgumentException If mcpTool or mcpSession are null. |
| 65 | + */ |
| 66 | + public McpAsyncTool( |
| 67 | + Tool mcpTool, McpAsyncClient mcpSession, McpSessionManager mcpSessionManager) { |
| 68 | + this(mcpTool, mcpSession, mcpSessionManager, JsonBaseModel.getMapper()); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Creates a new McpAsyncTool |
| 73 | + * |
| 74 | + * @param mcpTool The MCP tool to wrap. |
| 75 | + * @param mcpSession The MCP session to use to call the tool. |
| 76 | + * @param mcpSessionManager The MCP session manager to use to create new sessions. |
| 77 | + * @param objectMapper The ObjectMapper to use to convert JSON schemas. |
| 78 | + * @throws IllegalArgumentException If mcpTool or mcpSession are null. |
| 79 | + */ |
| 80 | + public McpAsyncTool( |
| 81 | + Tool mcpTool, |
| 82 | + McpAsyncClient mcpSession, |
| 83 | + McpSessionManager mcpSessionManager, |
| 84 | + ObjectMapper objectMapper) { |
| 85 | + super( |
| 86 | + mcpTool == null ? "" : mcpTool.name(), |
| 87 | + mcpTool == null ? "" : (mcpTool.description().isEmpty() ? "" : mcpTool.description())); |
| 88 | + |
| 89 | + if (mcpTool == null) { |
| 90 | + throw new IllegalArgumentException("mcpTool cannot be null"); |
| 91 | + } |
| 92 | + if (mcpSession == null) { |
| 93 | + throw new IllegalArgumentException("mcpSession cannot be null"); |
| 94 | + } |
| 95 | + if (objectMapper == null) { |
| 96 | + throw new IllegalArgumentException("objectMapper cannot be null"); |
| 97 | + } |
| 98 | + this.mcpTool = mcpTool; |
| 99 | + this.mcpSession = mcpSession; |
| 100 | + this.mcpSessionManager = mcpSessionManager; |
| 101 | + this.objectMapper = objectMapper; |
| 102 | + } |
| 103 | + |
| 104 | + public McpAsyncClient getMcpSession() { |
| 105 | + return this.mcpSession; |
| 106 | + } |
| 107 | + |
| 108 | + public Schema toGeminiSchema(JsonSchema openApiSchema) { |
| 109 | + return Schema.fromJson(objectMapper.valueToTree(openApiSchema).toString()); |
| 110 | + } |
| 111 | + |
| 112 | + private Single<McpSchema.InitializeResult> reintializeSession() { |
| 113 | + McpAsyncClient client = this.mcpSessionManager.createAsyncSession(); |
| 114 | + return Single.fromCompletionStage( |
| 115 | + client |
| 116 | + .initialize() |
| 117 | + .doOnSuccess( |
| 118 | + initResult -> { |
| 119 | + logger.debug("Initialize McpAsyncClient Result: {}", initResult); |
| 120 | + }) |
| 121 | + .doOnError( |
| 122 | + e -> { |
| 123 | + logger.error("Initialize McpAsyncClient Failed: {}", e.getMessage(), e); |
| 124 | + }) |
| 125 | + .doOnNext( |
| 126 | + _initResult -> { |
| 127 | + this.mcpSession = client; |
| 128 | + }) |
| 129 | + .toFuture()); |
| 130 | + } |
| 131 | + |
| 132 | + @Override |
| 133 | + public Optional<FunctionDeclaration> declaration() { |
| 134 | + return Optional.of( |
| 135 | + FunctionDeclaration.builder() |
| 136 | + .name(this.name()) |
| 137 | + .description(this.description()) |
| 138 | + .parameters(toGeminiSchema(this.mcpTool.inputSchema())) |
| 139 | + .build()); |
| 140 | + } |
| 141 | + |
| 142 | + @Override |
| 143 | + public Single<Map<String, Object>> runAsync(Map<String, Object> args, ToolContext toolContext) { |
| 144 | + return Single.defer( |
| 145 | + () -> |
| 146 | + Maybe.fromCompletionStage( |
| 147 | + this.mcpSession |
| 148 | + .callTool(new CallToolRequest(this.name(), ImmutableMap.copyOf(args))) |
| 149 | + .toFuture()) |
| 150 | + .map( |
| 151 | + callResult -> |
| 152 | + McpTool.wrapCallResult(this.objectMapper, this.name(), callResult)) |
| 153 | + .switchIfEmpty( |
| 154 | + Single.fromCallable( |
| 155 | + () -> McpTool.wrapCallResult(this.objectMapper, this.name(), null)))) |
| 156 | + .retryWhen( |
| 157 | + errors -> |
| 158 | + errors |
| 159 | + .delay(100, MILLISECONDS) |
| 160 | + .take(3) |
| 161 | + .doOnNext( |
| 162 | + error -> |
| 163 | + logger.error("Retrying callTool due to: {}", error.getMessage(), error)) |
| 164 | + .flatMapSingle(_ignore -> this.reintializeSession())); |
| 165 | + } |
| 166 | +} |
0 commit comments