|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import base64 |
| 18 | +import json |
| 19 | +import logging |
| 20 | +from typing import Any |
| 21 | +from typing import TYPE_CHECKING |
| 22 | + |
| 23 | +from google.genai import types |
| 24 | +from typing_extensions import override |
| 25 | + |
| 26 | +from ..features import FeatureName |
| 27 | +from ..features import is_feature_enabled |
| 28 | +from ..models.llm_request import LlmRequest |
| 29 | +from .base_tool import BaseTool |
| 30 | + |
| 31 | +if TYPE_CHECKING: |
| 32 | + from mcp_toolset import McpToolset |
| 33 | + |
| 34 | + from .tool_context import ToolContext |
| 35 | + |
| 36 | +logger = logging.getLogger("google_adk." + __name__) |
| 37 | + |
| 38 | + |
| 39 | +class LoadMcpResourceTool(BaseTool): |
| 40 | + """A tool that loads the MCP resources and adds them to the session.""" |
| 41 | + |
| 42 | + def __init__(self, mcp_toolset: McpToolset): |
| 43 | + super().__init__( |
| 44 | + name="load_mcp_resource", |
| 45 | + description="""Loads resources from the MCP server. |
| 46 | +
|
| 47 | +NOTE: Call when you need access to resources.""", |
| 48 | + ) |
| 49 | + self._mcp_toolset = mcp_toolset |
| 50 | + |
| 51 | + def _get_declaration(self) -> types.FunctionDeclaration | None: |
| 52 | + if is_feature_enabled(FeatureName.JSON_SCHEMA_FOR_FUNC_DECL): |
| 53 | + return types.FunctionDeclaration( |
| 54 | + name=self.name, |
| 55 | + description=self.description, |
| 56 | + parameters_json_schema={ |
| 57 | + "type": "object", |
| 58 | + "properties": { |
| 59 | + "resource_names": { |
| 60 | + "type": "array", |
| 61 | + "items": {"type": "string"}, |
| 62 | + }, |
| 63 | + }, |
| 64 | + }, |
| 65 | + ) |
| 66 | + return types.FunctionDeclaration( |
| 67 | + name=self.name, |
| 68 | + description=self.description, |
| 69 | + parameters=types.Schema( |
| 70 | + type=types.Type.OBJECT, |
| 71 | + properties={ |
| 72 | + "resource_names": types.Schema( |
| 73 | + type=types.Type.ARRAY, |
| 74 | + items=types.Schema( |
| 75 | + type=types.Type.STRING, |
| 76 | + ), |
| 77 | + ) |
| 78 | + }, |
| 79 | + ), |
| 80 | + ) |
| 81 | + |
| 82 | + @override |
| 83 | + async def run_async( |
| 84 | + self, *, args: dict[str, Any], tool_context: ToolContext |
| 85 | + ) -> Any: |
| 86 | + resource_names: list[str] = args.get("resource_names", []) |
| 87 | + return { |
| 88 | + "resource_names": resource_names, |
| 89 | + "status": ( |
| 90 | + "resource contents temporarily inserted and removed. to access" |
| 91 | + " these resources, call load_mcp_resource tool again." |
| 92 | + ), |
| 93 | + } |
| 94 | + |
| 95 | + @override |
| 96 | + async def process_llm_request( |
| 97 | + self, *, tool_context: ToolContext, llm_request: LlmRequest |
| 98 | + ) -> None: |
| 99 | + await super().process_llm_request( |
| 100 | + tool_context=tool_context, |
| 101 | + llm_request=llm_request, |
| 102 | + ) |
| 103 | + await self._append_resources_to_llm_request( |
| 104 | + tool_context=tool_context, llm_request=llm_request |
| 105 | + ) |
| 106 | + |
| 107 | + async def _append_resources_to_llm_request( |
| 108 | + self, *, tool_context: ToolContext, llm_request: LlmRequest |
| 109 | + ): |
| 110 | + try: |
| 111 | + resource_names = await self._mcp_toolset.list_resources() |
| 112 | + if resource_names: |
| 113 | + llm_request.append_instructions([f"""You have a list of MCP resources: |
| 114 | +{json.dumps(resource_names)} |
| 115 | +
|
| 116 | +When the user asks questions about any of the resources, you should call the |
| 117 | +`load_mcp_resource` function to load the resource. Always call load_mcp_resource |
| 118 | +before answering questions related to the resources. |
| 119 | +"""]) |
| 120 | + except Exception as e: |
| 121 | + logger.warning("Failed to list MCP resources: %s", e) |
| 122 | + |
| 123 | + # Attach content |
| 124 | + if llm_request.contents and llm_request.contents[-1].parts: |
| 125 | + function_response = llm_request.contents[-1].parts[0].function_response |
| 126 | + if function_response and function_response.name == self.name: |
| 127 | + response = function_response.response or {} |
| 128 | + resource_names = response.get("resource_names", []) |
| 129 | + for resource_name in resource_names: |
| 130 | + try: |
| 131 | + contents = await self._mcp_toolset.read_resource(resource_name) |
| 132 | + |
| 133 | + for content in contents: |
| 134 | + part = self._mcp_content_to_part(content, resource_name) |
| 135 | + llm_request.contents.append( |
| 136 | + types.Content( |
| 137 | + role="user", |
| 138 | + parts=[ |
| 139 | + types.Part.from_text( |
| 140 | + text=f"Resource {resource_name} is:" |
| 141 | + ), |
| 142 | + part, |
| 143 | + ], |
| 144 | + ) |
| 145 | + ) |
| 146 | + except Exception as e: |
| 147 | + logger.warning( |
| 148 | + "Failed to read MCP resource '%s': %s", resource_name, e |
| 149 | + ) |
| 150 | + continue |
| 151 | + |
| 152 | + def _mcp_content_to_part( |
| 153 | + self, content: Any, resource_name: str |
| 154 | + ) -> types.Part: |
| 155 | + if hasattr(content, "text") and content.text is not None: |
| 156 | + return types.Part.from_text(text=content.text) |
| 157 | + elif hasattr(content, "blob") and content.blob is not None: |
| 158 | + try: |
| 159 | + data = base64.b64decode(content.blob) |
| 160 | + # Basic check for mime type or default |
| 161 | + mime_type = content.mimeType or "application/octet-stream" |
| 162 | + return types.Part.from_bytes(data=data, mime_type=mime_type) |
| 163 | + except Exception: |
| 164 | + return types.Part.from_text( |
| 165 | + text=f"[Binary content for {resource_name} could not be decoded]" |
| 166 | + ) |
| 167 | + else: |
| 168 | + return types.Part.from_text( |
| 169 | + text=f"[Unknown content type for {resource_name}]" |
| 170 | + ) |
0 commit comments