Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat: Add configure service account auth for google_api_tool_set #120

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

Merged
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
17 changes: 16 additions & 1 deletion src/google/adk/tools/google_api_tool/google_api_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

from typing import Any
from typing import Dict
from typing import Optional
Expand All @@ -23,7 +25,9 @@
from ...auth import AuthCredential
from ...auth import AuthCredentialTypes
from ...auth import OAuth2Auth
from ...auth.auth_credential import ServiceAccount
from ..openapi_tool import RestApiTool
from ..openapi_tool.auth.auth_helpers import service_account_scheme_credential
from ..tool_context import ToolContext


Expand All @@ -34,14 +38,18 @@ def __init__(
rest_api_tool: RestApiTool,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__(
name=rest_api_tool.name,
description=rest_api_tool.description,
is_long_running=rest_api_tool.is_long_running,
)
self._rest_api_tool = rest_api_tool
self.configure_auth(client_id, client_secret)
if service_account is not None:
self.configure_sa_auth(service_account)
else:
self.configure_auth(client_id, client_secret)

@override
def _get_declaration(self) -> FunctionDeclaration:
Expand All @@ -63,3 +71,10 @@ def configure_auth(self, client_id: str, client_secret: str):
client_secret=client_secret,
),
)

def configure_sa_auth(self, service_account: ServiceAccount):
auth_scheme, auth_credential = service_account_scheme_credential(
service_account
)
self._rest_api_tool.auth_scheme = auth_scheme
self._rest_api_tool.auth_credential = auth_credential
16 changes: 9 additions & 7 deletions src/google/adk/tools/google_api_tool/google_api_toolset.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,15 @@

from __future__ import annotations

import inspect
import os
from typing import Any
from typing import List
from typing import Optional
from typing import Type
from typing import Union

from typing_extensions import override

from ...agents.readonly_context import ReadonlyContext
from ...auth import OpenIdConnectWithConfig
from ...auth.auth_credential import ServiceAccount
from ...tools.base_toolset import BaseToolset
from ...tools.base_toolset import ToolPredicate
from ..openapi_tool import OpenAPIToolset
Expand All @@ -48,11 +45,13 @@ def __init__(
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
self.api_name = api_name
self.api_version = api_version
self._client_id = client_id
self._client_secret = client_secret
self._service_account = service_account
self._openapi_toolset = self._load_toolset_with_oidc_auth()
self.tool_filter = tool_filter

Expand All @@ -61,10 +60,10 @@ async def get_tools(
self, readonly_context: Optional[ReadonlyContext] = None
) -> List[GoogleApiTool]:
"""Get all tools in the toolset."""
tools = []

return [
GoogleApiTool(tool, self._client_id, self._client_secret)
GoogleApiTool(
tool, self._client_id, self._client_secret, self._service_account
)
for tool in await self._openapi_toolset.get_tools(readonly_context)
if self._is_tool_selected(tool, readonly_context)
]
Expand Down Expand Up @@ -106,6 +105,9 @@ def configure_auth(self, client_id: str, client_secret: str):
self._client_id = client_id
self._client_secret = client_secret

def configure_sa_auth(self, service_account: ServiceAccount):
self._service_account = service_account

@override
async def close(self):
if self._openapi_toolset:
Expand Down
61 changes: 41 additions & 20 deletions src/google/adk/tools/google_api_tool/google_api_toolsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import logging
from typing import List
from typing import Optional
from typing import Union

from ...auth.auth_credential import ServiceAccount
from ..base_toolset import ToolPredicate
from .google_api_toolset import GoogleApiToolset

Expand All @@ -29,69 +31,85 @@ class BigQueryToolset(GoogleApiToolset):

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("bigquery", "v2", client_id, client_secret, tool_filter)
super().__init__(
"bigquery", "v2", client_id, client_secret, tool_filter, service_account
)


class CalendarToolset(GoogleApiToolset):
"""Auto-generated Calendar toolset based on Google Calendar API v3 spec exposed by Google API discovery API"""

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("calendar", "v3", client_id, client_secret, tool_filter)
super().__init__(
"calendar", "v3", client_id, client_secret, tool_filter, service_account
)


class GmailToolset(GoogleApiToolset):
"""Auto-generated Gmail toolset based on Google Gmail API v1 spec exposed by Google API discovery API"""

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("gmail", "v1", client_id, client_secret, tool_filter)
super().__init__(
"gmail", "v1", client_id, client_secret, tool_filter, service_account
)


class YoutubeToolset(GoogleApiToolset):
"""Auto-generated Youtube toolset based on Youtube API v3 spec exposed by Google API discovery API"""

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("youtube", "v3", client_id, client_secret, tool_filter)
super().__init__(
"youtube", "v3", client_id, client_secret, tool_filter, service_account
)


class SlidesToolset(GoogleApiToolset):
"""Auto-generated Slides toolset based on Google Slides API v1 spec exposed by Google API discovery API"""

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("slides", "v1", client_id, client_secret, tool_filter)
super().__init__(
"slides", "v1", client_id, client_secret, tool_filter, service_account
)


class SheetsToolset(GoogleApiToolset):
"""Auto-generated Sheets toolset based on Google Sheets API v4 spec exposed by Google API discovery API"""

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("sheets", "v4", client_id, client_secret, tool_filter)

Expand All @@ -101,8 +119,11 @@ class DocsToolset(GoogleApiToolset):

def __init__(
self,
client_id: str = None,
client_secret: str = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
tool_filter: Optional[Union[ToolPredicate, List[str]]] = None,
service_account: Optional[ServiceAccount] = None,
):
super().__init__("docs", "v1", client_id, client_secret, tool_filter)
super().__init__(
"docs", "v1", client_id, client_secret, tool_filter, service_account
)
145 changes: 145 additions & 0 deletions tests/unittests/tools/google_api_tool/test_google_api_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# 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 unittest import mock

from google.adk.auth.auth_credential import AuthCredentialTypes
from google.adk.auth.auth_credential import ServiceAccount
from google.adk.auth.auth_credential import ServiceAccountCredential
from google.adk.tools.google_api_tool.google_api_tool import GoogleApiTool
from google.adk.tools.openapi_tool import RestApiTool
from google.adk.tools.tool_context import ToolContext
from google.genai.types import FunctionDeclaration
import pytest


@pytest.fixture
def mock_rest_api_tool():
"""Fixture for a mock RestApiTool."""
mock_tool = mock.MagicMock(spec=RestApiTool)
mock_tool.name = "test_tool"
mock_tool.description = "Test Tool Description"
mock_tool.is_long_running = False
mock_tool._get_declaration.return_value = FunctionDeclaration(
name="test_function", description="Test function description"
)
mock_tool.run_async.return_value = {"result": "success"}
return mock_tool


@pytest.fixture
def mock_tool_context():
"""Fixture for a mock ToolContext."""
return mock.MagicMock(spec=ToolContext)


class TestGoogleApiTool:
"""Test suite for the GoogleApiTool class."""

def test_init(self, mock_rest_api_tool):
"""Test GoogleApiTool initialization."""
tool = GoogleApiTool(mock_rest_api_tool)

assert tool.name == "test_tool"
assert tool.description == "Test Tool Description"
assert tool.is_long_running is False
assert tool._rest_api_tool == mock_rest_api_tool

def test_get_declaration(self, mock_rest_api_tool):
"""Test _get_declaration method."""
tool = GoogleApiTool(mock_rest_api_tool)

declaration = tool._get_declaration()

assert isinstance(declaration, FunctionDeclaration)
assert declaration.name == "test_function"
assert declaration.description == "Test function description"
mock_rest_api_tool._get_declaration.assert_called_once()

@pytest.mark.asyncio
async def test_run_async(self, mock_rest_api_tool, mock_tool_context):
"""Test run_async method."""
tool = GoogleApiTool(mock_rest_api_tool)
args = {"param1": "value1"}

result = await tool.run_async(args=args, tool_context=mock_tool_context)

assert result == {"result": "success"}
mock_rest_api_tool.run_async.assert_called_once_with(
args=args, tool_context=mock_tool_context
)

def test_configure_auth(self, mock_rest_api_tool):
"""Test configure_auth method."""
tool = GoogleApiTool(mock_rest_api_tool)
client_id = "test_client_id"
client_secret = "test_client_secret"

tool.configure_auth(client_id=client_id, client_secret=client_secret)

# Check that auth_credential was set correctly on the rest_api_tool
assert mock_rest_api_tool.auth_credential is not None
assert (
mock_rest_api_tool.auth_credential.auth_type
== AuthCredentialTypes.OPEN_ID_CONNECT
)
assert mock_rest_api_tool.auth_credential.oauth2.client_id == client_id
assert (
mock_rest_api_tool.auth_credential.oauth2.client_secret == client_secret
)

@mock.patch(
"google.adk.tools.google_api_tool.google_api_tool.service_account_scheme_credential"
)
def test_configure_sa_auth(
self, mock_service_account_scheme_credential, mock_rest_api_tool
):
"""Test configure_sa_auth method."""
# Setup mock return values
mock_auth_scheme = mock.MagicMock()
mock_auth_credential = mock.MagicMock()
mock_service_account_scheme_credential.return_value = (
mock_auth_scheme,
mock_auth_credential,
)

service_account = ServiceAccount(
service_account_credential=ServiceAccountCredential(
type="service_account",
project_id="project_id",
private_key_id="private_key_id",
private_key="private_key",
client_email="client_email",
client_id="client_id",
auth_uri="auth_uri",
token_uri="token_uri",
auth_provider_x509_cert_url="auth_provider_x509_cert_url",
client_x509_cert_url="client_x509_cert_url",
universe_domain="universe_domain",
),
scopes=["scope1", "scope2"],
)

# Create tool and call method
tool = GoogleApiTool(mock_rest_api_tool)
tool.configure_sa_auth(service_account=service_account)

# Verify service_account_scheme_credential was called correctly
mock_service_account_scheme_credential.assert_called_once_with(
service_account
)

# Verify auth_scheme and auth_credential were set correctly on the rest_api_tool
assert mock_rest_api_tool.auth_scheme == mock_auth_scheme
assert mock_rest_api_tool.auth_credential == mock_auth_credential
Loading