From a1d5e4610f92e7956d4465b9f6b90e79e88570c7 Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Fri, 13 Feb 2026 16:41:00 +0000 Subject: [PATCH 01/10] Google ADK Plugin for StackOne --- .gitignore | 43 ++++++ LICENSE | 190 ++++++++++++++++++++++++++ README.md | 243 +++++++++++++++++++++++++++++++++ examples/calendly_agent.py | 83 +++++++++++ examples/hris_agent.py | 86 ++++++++++++ pyproject.toml | 62 +++++++++ stackone_adk/__init__.py | 5 + stackone_adk/plugin.py | 189 +++++++++++++++++++++++++ stackone_adk/py.typed | 0 stackone_adk/tools.py | 146 ++++++++++++++++++++ tests/__init__.py | 0 tests/test_plugin.py | 273 +++++++++++++++++++++++++++++++++++++ tests/test_tools.py | 260 +++++++++++++++++++++++++++++++++++ 13 files changed, 1580 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 examples/calendly_agent.py create mode 100644 examples/hris_agent.py create mode 100644 pyproject.toml create mode 100644 stackone_adk/__init__.py create mode 100644 stackone_adk/plugin.py create mode 100644 stackone_adk/py.typed create mode 100644 stackone_adk/tools.py create mode 100644 tests/__init__.py create mode 100644 tests/test_plugin.py create mode 100644 tests/test_tools.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ececc9b --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +*.egg-info/ +*.egg +dist/ +build/ +.eggs/ + +# Virtual environments +.venv/ +venv/ +env/ + +# IDE +.idea/ +.vscode/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Type checking +.mypy_cache/ +.dmypy.json +dmypy.json + +# Environment +.env +.env.local + +# Reference (development only) +Reference/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6630acf --- /dev/null +++ b/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Support. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2025 StackOne + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..56315a9 --- /dev/null +++ b/README.md @@ -0,0 +1,243 @@ +# stackone-adk + +Google ADK plugin for connecting agents to 200+ SaaS providers via [StackOne](https://stackone.com). + +StackOne provides a unified API gateway for HRIS, ATS, CRM, scheduling, and more. This plugin dynamically discovers available tools from StackOne's API and exposes them as native Google ADK tools, no hardcoded tool definitions needed. + +## Installation + +```bash +pip install stackone-adk +``` + +Or with uv: + +```bash +uv add stackone-adk +``` + +## Configuration + +### StackOne API Key + +Get your API key from the [StackOne Dashboard](https://app.stackone.com). + +```bash +# Environment variable (recommended) +export STACKONE_API_KEY="your-stackone-api-key" +``` + +Or pass directly: + +```python +plugin = StackOnePlugin(api_key="your-stackone-api-key") +``` + +### Google API Key + +Get your API key from [Google AI Studio](https://aistudio.google.com/apikey). This key is required to access Google's Gemini models. + +```bash +export GOOGLE_API_KEY="your-google-api-key" +``` + +## Quick Start + +In standard ADK, you define tools as Python functions: + +```python +# Standard ADK — manual tool functions +def get_current_time(city: str) -> dict: + """Returns the current time in a specified city.""" + return {"status": "success", "city": city, "time": "10:30 AM"} + +root_agent = Agent( + model="gemini-3.0-flash", + name="root_agent", + tools=[get_current_time], +) +``` + +With StackOne, tools are discovered dynamically from your connected providers — no manual tool definitions needed: + +```python +import asyncio +from google.adk.agents import Agent +from google.adk.apps import App +from google.adk.runners import InMemoryRunner +from stackone_adk import StackOnePlugin + +async def main(): + # StackOne replaces manual tool functions + plugin = StackOnePlugin() # reads STACKONE_API_KEY from env + + agent = Agent( + model="gemini-3.0-flash", + name="calendly_agent", # replace with your agent name + instruction="You are a scheduling assistant with access to Calendly.", + tools=plugin.get_tools(), # instead of: tools=[get_current_time] + ) + + app = App(name="calendly_app", root_agent=agent, plugins=[plugin]) + + async with InMemoryRunner(app=app) as runner: + response = await runner.run_debug("What event types do I have?") + print(response) + +asyncio.run(main()) +``` + +## Usage Patterns + +### With App (Recommended) + +```python +from google.adk.apps import App +from google.adk.runners import InMemoryRunner + +plugin = StackOnePlugin(providers=["calendly"]) + +agent = Agent( + model="gemini-3.0-flash", + name="calendly_agent", # replace with your agent name + tools=plugin.get_tools(), +) + +app = App(name="calendly_app", root_agent=agent, plugins=[plugin]) + +async with InMemoryRunner(app=app) as runner: + response = await runner.run_debug("List my events") +``` + +### With Runner Directly + +```python +from google.adk.runners import InMemoryRunner + +plugin = StackOnePlugin(providers=["calendly"]) + +agent = Agent( + model="gemini-3.0-flash", + name="calendly_agent", # replace with your agent name + tools=plugin.get_tools(), +) + +async with InMemoryRunner(app_name="calendly_app", agent=agent) as runner: + response = await runner.run_debug("List my events") +``` + +## Plugin Configuration + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `api_key` | `str \| None` | `None` | StackOne API key. Falls back to `STACKONE_API_KEY` env var. | +| `account_id` | `str \| None` | `None` | Default account ID for all tools. | +| `base_url` | `str \| None` | `None` | API URL override (default: `https://api.stackone.com`). | +| `plugin_name` | `str` | `"stackone_plugin"` | Plugin identifier for ADK. | +| `providers` | `list[str] \| None` | `None` | Filter by provider names. | +| `actions` | `list[str] \| None` | `None` | Filter by action patterns (supports globs). | +| `account_ids` | `list[str] \| None` | `None` | Scope tools to specific account IDs. | + +## Tool Filtering + +### By Provider + +Filter tools to specific SaaS providers: + +```python +# Single provider +plugin = StackOnePlugin(providers=["calendly"]) + +# Multiple providers +plugin = StackOnePlugin(providers=["hibob", "bamboohr"]) +``` + +### By Action Pattern + +Use glob patterns to filter specific actions: + +```python +# Read-only operations +plugin = StackOnePlugin(actions=["*_list_*", "*_get_*"]) + +# Specific actions +plugin = StackOnePlugin(actions=["calendly_list_events", "calendly_get_event_*"]) +``` + +### By Account ID + +Scope tools to specific connected accounts: + +```python +# Multiple accounts +plugin = StackOnePlugin(account_ids=["acct-hibob-1", "acct-bamboohr-1"]) +``` + +### Combining Filters + +```python +plugin = StackOnePlugin( + providers=["hibob", "bamboohr"], + actions=["*_list_*", "*_get_*"], + account_ids=["acct-hibob-1", "acct-bamboohr-1"], +) +``` + +## Available Tools + +Unlike plugins with a fixed set of tools, StackOne tools are **dynamically discovered** from your connected providers via the StackOne API. The available tools depend on which SaaS providers you have connected in your [StackOne Dashboard](https://app.stackone.com). +Print discovered tools: + +```python +plugin = StackOnePlugin(providers=["calendly"]) +for tool in plugin.get_tools(): + print(f"{tool.name}: {tool.description}") +``` + +## Examples + +See the [`examples/`](examples/) directory: + +| Example | Description | +|---------|-------------| +| [`calendly_agent.py`](examples/calendly_agent.py) | Calendly scheduling agent — single provider | +| [`hris_agent.py`](examples/hris_agent.py) | Multi-provider HRIS agent (HiBob, BambooHR) | + +## Development + +```bash +git clone https://github.com/StackOneHQ/stackone-adk-plugin.git +cd stackone-adk-plugin +pip install -e ".[dev]" +``` + +Run tests: + +```bash +pytest +``` + +Lint and type check: + +```bash +ruff check stackone_adk/ tests/ +mypy stackone_adk/ +``` + +Try an example (requires a Calendly account connected in your [StackOne Dashboard](https://app.stackone.com)): + +```bash +export STACKONE_API_KEY="your-stackone-api-key" +export GOOGLE_API_KEY="your-google-api-key" +python examples/calendly_agent.py +``` + +## License + +Apache 2.0 — see [LICENSE](LICENSE). + +## References + +- [StackOne Documentation](https://docs.stackone.com/) +- [StackOne Python SDK](https://github.com/StackOneHQ/stackone-ai-python) +- [Google ADK Documentation](https://google.github.io/adk-docs/) diff --git a/examples/calendly_agent.py b/examples/calendly_agent.py new file mode 100644 index 0000000..a1a64f0 --- /dev/null +++ b/examples/calendly_agent.py @@ -0,0 +1,83 @@ +"""Calendly scheduling agent using StackOne plugin for Google ADK. + +StackOne dynamically discovers tools from your connected SaaS providers, +so you don't need to define tool functions manually. Just connect your +Calendly account and the tools are ready to use: + + plugin = StackOnePlugin() + agent = Agent( + model="gemini-2.5-flash", + name="calendly_agent", + tools=plugin.get_tools(), + ) + +Setup: + 1. Get your StackOne API key from https://app.stackone.com + 2. Connect your Calendly account in the StackOne dashboard + 3. Set environment variables: + export STACKONE_API_KEY="your-stackone-api-key" + export GOOGLE_API_KEY="your-google-api-key" + 4. Run: python examples/calendly_agent.py +""" + +import asyncio +import logging + +from google.adk.agents import Agent +from google.adk.apps import App +from google.adk.runners import InMemoryRunner + +from stackone_adk import StackOnePlugin + +# Suppress "non-text parts" warning from the Gemini SDK +_genai_logger = logging.getLogger("google.genai") +_genai_logger.addFilter(lambda r: "non-text parts" not in r.getMessage()) + + +async def main() -> None: + # Discovers tools from your connected providers + plugin = StackOnePlugin() + + # Optionally filter by provider or scope to a specific account: + # plugin = StackOnePlugin(providers=["calendly"], account_id="your-account-id") + + tools = plugin.get_tools() + print(f"Discovered {len(tools)} Calendly tools\n") + + # Create agent with StackOne tools + agent = Agent( + model="gemini-2.5-flash", + name="calendly_agent", # replace with your agent name + description="Manages scheduling via Calendly through StackOne.", + instruction=( + "You are a scheduling assistant powered by StackOne and Calendly. " + "You help users manage their scheduling by listing event types " + "and checking scheduled events.\n\n" + "When asked about scheduled events, always use the tools directly " + "to fetch the data — do not ask the user for URIs or parameters. " + "First call calendly_get_current_user to get the user URI, then " + "use that URI in subsequent calls.\n\n" + "Always be helpful and provide clear, organized responses." + ), + tools=tools, + ) + + # Recommended: use App to register the plugin + app = App(name="calendly_app", root_agent=agent, plugins=[plugin]) + + async with InMemoryRunner(app=app) as runner: + prompt = "Get my most recent scheduled meeting from Calendly." + print(f"User: {prompt}") + print("=" * 60) + events = await runner.run_debug(prompt, quiet=True) + # Extract the agent's final text response + for event in reversed(events): + if event.content and event.content.parts: + text_parts = [p.text for p in event.content.parts if p.text] + if text_parts: + print(f"Agent: {''.join(text_parts)}\n") + break + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/hris_agent.py b/examples/hris_agent.py new file mode 100644 index 0000000..7780091 --- /dev/null +++ b/examples/hris_agent.py @@ -0,0 +1,86 @@ +"""Multi-provider HRIS agent using StackOne plugin for Google ADK. + +StackOne lets you combine tools from multiple SaaS providers and filter +by action type — all discovered dynamically from your connected accounts: + + plugin = StackOnePlugin( + providers=["hibob", "bamboohr"], + actions=["*_list_*", "*_get_*"], # read-only operations only + ) + agent = Agent( + model="gemini-2.5-flash", + name="hris_agent", + tools=plugin.get_tools(), # tools from both providers + ) + +Setup: + 1. Get your StackOne API key from https://app.stackone.com + 2. Connect your HRIS providers in the StackOne dashboard + 3. Set environment variables: + export STACKONE_API_KEY="your-stackone-api-key" + export GOOGLE_API_KEY="your-google-api-key" + 4. Run: python examples/hris_agent.py +""" + +import asyncio +import logging + +from google.adk.agents import Agent +from google.adk.apps import App +from google.adk.runners import InMemoryRunner + +from stackone_adk import StackOnePlugin + +# Suppress "non-text parts" warning from the Gemini SDK +_genai_logger = logging.getLogger("google.genai") +_genai_logger.addFilter(lambda r: "non-text parts" not in r.getMessage()) + + +async def main() -> None: + # Combine multiple providers with optional action filtering + plugin = StackOnePlugin( + providers=["hibob", "bamboohr"], + actions=["*_list_*", "*_get_*"], # read-only operations only + ) + + tools = plugin.get_tools() + print(f"Discovered {len(tools)} HRIS tools\n") + + if not tools: + print("No HRIS tools found. Connect HiBob or BambooHR in your StackOne dashboard.") + return + + # Create agent with tools from multiple providers + agent = Agent( + model="gemini-2.5-flash", + name="hris_agent", # replace with your agent name + description="Agent to answer questions using HiBob and BambooHR data.", + instruction=( + "You are a read-only HRIS assistant with access to multiple providers " + "via StackOne. You can list and retrieve data from HiBob and BambooHR, " + "but you cannot create, update, or delete anything.\n\n" + "When asked to list employees or retrieve data, use the tools directly " + "— do not ask the user for additional parameters.\n\n" + "Always clarify which provider the data comes from in your responses." + ), + tools=tools, + ) + + app = App(name="hris_app", root_agent=agent, plugins=[plugin]) + + async with InMemoryRunner(app=app) as runner: + prompt = "List employees from HiBob" + print(f"User: {prompt}") + print("=" * 60) + events = await runner.run_debug(prompt, quiet=True) + # Extract the agent's final text response + for event in reversed(events): + if event.content and event.content.parts: + text_parts = [p.text for p in event.content.parts if p.text] + if text_parts: + print(f"Agent: {''.join(text_parts)}\n") + break + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..0271d90 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,62 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "stackone-adk" +version = "0.1.0" +description = "StackOne plugin for Google ADK: Connect agents to 200+ SaaS providers" +readme = "README.md" +requires-python = ">=3.10" +license = {text = "Apache-2.0"} +authors = [ + {name = "StackOne", email = "support@stackone.com"}, +] +keywords = ["adk", "stackone", "saas", "plugin", "google-adk", "agents"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] + +dependencies = [ + "google-adk>=1.25.0", + "stackone-ai[mcp]>=2.3.1", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0.0", + "pytest-asyncio>=0.25.0", + "ruff>=0.9.0", + "mypy>=1.0.0", +] + +[project.urls] +Homepage = "https://github.com/StackOneHQ/stackone-adk-plugin" +Repository = "https://github.com/StackOneHQ/stackone-adk-plugin" +Documentation = "https://github.com/StackOneHQ/stackone-adk-plugin#readme" + +[tool.hatch.build.targets.wheel] +packages = ["stackone_adk"] + +[tool.ruff] +line-length = 110 +target-version = "py310" + +[tool.ruff.lint] +select = ["E", "W", "F", "I", "B", "C4", "UP"] + +[tool.mypy] +python_version = "3.10" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = true + +[tool.pytest.ini_options] +asyncio_mode = "auto" diff --git a/stackone_adk/__init__.py b/stackone_adk/__init__.py new file mode 100644 index 0000000..f7a5c5f --- /dev/null +++ b/stackone_adk/__init__.py @@ -0,0 +1,5 @@ +from stackone_adk.plugin import StackOnePlugin +from stackone_adk.tools import StackOneAdkTool + +__version__ = "0.1.0" +__all__ = ["StackOnePlugin", "StackOneAdkTool"] diff --git a/stackone_adk/plugin.py b/stackone_adk/plugin.py new file mode 100644 index 0000000..cbfce34 --- /dev/null +++ b/stackone_adk/plugin.py @@ -0,0 +1,189 @@ +"""StackOne Plugin for Google ADK. + +Provides dynamic tool discovery from 200+ SaaS providers via StackOne's +AI Integration Gateway, with lifecycle hooks for monitoring and customization. +""" + +from __future__ import annotations + +import base64 +import logging +import os +from typing import Any + +import httpx +from google.adk.agents.base_agent import BaseAgent +from google.adk.agents.callback_context import CallbackContext +from google.adk.plugins import BasePlugin +from google.adk.tools import BaseTool, ToolContext +from google.genai import types +from stackone_ai import StackOneToolSet + +from stackone_adk.tools import StackOneAdkTool + +logger = logging.getLogger(__name__) + +DEFAULT_BASE_URL = "https://api.stackone.com" + + +def _discover_account_ids( + api_key: str, + base_url: str, + providers: list[str] | None = None, +) -> list[str]: + """Auto-discover connected account IDs from the StackOne API. + + Args: + api_key: StackOne API key. + base_url: StackOne API base URL. + providers: Optional provider filter (case-insensitive). + + Returns: + List of account IDs. + """ + token = base64.b64encode(f"{api_key}:".encode()).decode() + headers = {"Authorization": f"Basic {token}"} + resp = httpx.get(f"{base_url.rstrip('/')}/accounts", headers=headers) + resp.raise_for_status() + + body = resp.json() + accounts = body.get("data", body) if isinstance(body, dict) else body + if providers: + provider_set = {p.lower() for p in providers} + accounts = [a for a in accounts if a.get("provider", "").lower() in provider_set] + + return [a["id"] for a in accounts if a.get("id")] + + +class StackOnePlugin(BasePlugin): + """Plugin for connecting ADK agents to 200+ SaaS providers via StackOne. + + Dynamically discovers tools from StackOne's MCP endpoint and exposes them + as native ADK tools. All authentication, RPC execution, and HTTP calls + are handled by the StackOne AI SDK. + + When no account_id or account_ids are provided, the plugin automatically + discovers connected accounts from the StackOne API. + + Args: + api_key: StackOne API key. Falls back to STACKONE_API_KEY env var. + account_id: Default account ID for all tools. + base_url: API URL override (default: https://api.stackone.com). + plugin_name: Plugin identifier for ADK. + providers: Filter by provider names (e.g., ["calendly", "hibob"]). + actions: Filter by action patterns with globs (e.g., ["*_list_*"]). + account_ids: Scope tools to specific account IDs. + """ + + def __init__( + self, + api_key: str | None = None, + account_id: str | None = None, + base_url: str | None = None, + plugin_name: str = "stackone_plugin", + providers: list[str] | None = None, + actions: list[str] | None = None, + account_ids: list[str] | None = None, + ) -> None: + super().__init__(name=plugin_name) + + resolved_api_key = api_key if api_key is not None else os.getenv("STACKONE_API_KEY", "") + resolved_base_url = base_url or DEFAULT_BASE_URL + + # Auto-discover account IDs if none provided + if not account_id and not account_ids: + account_ids = _discover_account_ids(resolved_api_key, resolved_base_url, providers) + logger.info(f"Auto-discovered {len(account_ids)} account(s)") + + self._tools: list[BaseTool] = [] + + if not account_id and not account_ids: + logger.warning("No connected accounts found. No tools will be available.") + return + + self._toolset = StackOneToolSet( + api_key=api_key, + account_id=account_id, + base_url=base_url, + ) + + stackone_tools = self._toolset.fetch_tools( + account_ids=account_ids, + providers=providers, + actions=actions, + ) + + for tool in stackone_tools: + try: + self._tools.append(StackOneAdkTool(tool)) + except Exception as e: + logger.warning(f"Failed to convert tool '{tool.name}': {e}") + + logger.info(f"StackOnePlugin initialized with {len(self._tools)} tools") + + def get_tools(self) -> list[BaseTool]: + """Return pre-converted ADK tools.""" + return self._tools + + async def before_agent_callback( + self, + *, + agent: BaseAgent, + callback_context: CallbackContext, + ) -> types.Content | None: + """Called before the agent starts processing.""" + return None + + async def after_agent_callback( + self, + *, + agent: BaseAgent, + callback_context: CallbackContext, + ) -> types.Content | None: + """Called after the agent finishes processing.""" + return None + + async def before_tool_callback( + self, + *, + tool: BaseTool, + tool_args: dict[str, Any], + tool_context: ToolContext, + ) -> dict[str, Any] | None: + """Called before a tool is executed.""" + logger.debug(f"Before tool: {tool.name}") + return None + + async def after_tool_callback( + self, + *, + tool: BaseTool, + tool_args: dict[str, Any], + tool_context: ToolContext, + result: dict[str, Any], + ) -> dict[str, Any] | None: + """Called after a tool is executed.""" + logger.debug(f"After tool: {tool.name}") + if isinstance(result, dict) and "error" in result: + logger.warning(f"Tool {tool.name} returned error: {result['error']}") + return None + + async def on_tool_error_callback( + self, + *, + tool: BaseTool, + tool_args: dict[str, Any], + tool_context: ToolContext, + error: Exception, + ) -> dict[str, Any] | None: + """Called when a tool raises an uncaught exception.""" + logger.error(f"Tool {tool.name} raised uncaught exception: {error}") + return None + + async def close(self) -> None: + """Clean up plugin resources. + + StackOneToolSet is stateless HTTP — each execute() is an + independent request — so no cleanup is needed. + """ + logger.debug("StackOnePlugin closed") diff --git a/stackone_adk/py.typed b/stackone_adk/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/stackone_adk/tools.py b/stackone_adk/tools.py new file mode 100644 index 0000000..12c10ba --- /dev/null +++ b/stackone_adk/tools.py @@ -0,0 +1,146 @@ +"""StackOne tool adapter for Google ADK. + +Converts StackOne's dynamically-discovered tools into ADK-compatible BaseTool instances. +Handles JSON Schema to FunctionDeclaration conversion and sync-to-async bridging. +""" + +from __future__ import annotations + +import asyncio +import logging +from typing import Any + +from google.adk.tools import BaseTool, ToolContext +from google.genai import types +from stackone_ai.models import StackOneTool + +logger = logging.getLogger(__name__) + +# JSON Schema type string → google.genai types.Type enum +_TYPE_MAP: dict[str, types.Type] = { + "string": types.Type.STRING, + "integer": types.Type.INTEGER, + "number": types.Type.NUMBER, + "boolean": types.Type.BOOLEAN, + "array": types.Type.ARRAY, + "object": types.Type.OBJECT, +} + + +def _convert_property_to_schema(prop: dict[str, Any]) -> types.Schema: + """Convert a single JSON Schema property dict to a types.Schema. + + Handles type, description, enum, nullable, array items, and nested objects. + Unknown types default to STRING. Unknown fields are silently ignored. + """ + type_str = prop.get("type", "string") + schema_type = _TYPE_MAP.get(type_str, types.Type.STRING) + + kwargs: dict[str, Any] = {"type": schema_type} + + if "description" in prop: + kwargs["description"] = prop["description"] + + if "enum" in prop: + kwargs["enum"] = prop["enum"] + + if "nullable" in prop: + kwargs["nullable"] = prop["nullable"] + + # Handle array items + if schema_type == types.Type.ARRAY and "items" in prop: + items = prop["items"] + if isinstance(items, dict): + kwargs["items"] = _convert_property_to_schema(items) + + # Handle nested object properties + if schema_type == types.Type.OBJECT and "properties" in prop: + nested_props, nested_required = _convert_parameters_to_schema(prop["properties"]) + kwargs["properties"] = nested_props + if nested_required: + kwargs["required"] = nested_required + + return types.Schema(**kwargs) + + +def _convert_parameters_to_schema( + properties: dict[str, Any], +) -> tuple[dict[str, types.Schema], list[str]]: + """Convert all JSON Schema properties to ADK Schema format. + + Returns: + Tuple of (converted properties dict, list of required field names). + Required fields are those with nullable=False (StackOne SDK convention). + """ + converted: dict[str, types.Schema] = {} + required: list[str] = [] + + for name, prop in properties.items(): + if not isinstance(prop, dict): + continue + converted[name] = _convert_property_to_schema(prop) + if prop.get("nullable") is False: + required.append(name) + + return converted, required + + +class StackOneAdkTool(BaseTool): + """Adapter that wraps a StackOneTool as an ADK BaseTool. + + Converts StackOne's JSON Schema parameters to ADK FunctionDeclarations + and bridges the synchronous execute() method to async run_async(). + """ + + def __init__(self, stackone_tool: StackOneTool) -> None: + super().__init__( + name=stackone_tool.name, + description=stackone_tool.description, + ) + self._stackone_tool = stackone_tool + + def _get_declaration(self) -> types.FunctionDeclaration: + """Convert StackOne tool parameters to an ADK FunctionDeclaration.""" + properties = self._stackone_tool.parameters.properties + + if not properties: + return types.FunctionDeclaration( + name=self.name, + description=self.description, + ) + + converted_props, required = _convert_parameters_to_schema(properties) + + parameters = types.Schema( + type=types.Type.OBJECT, + properties=converted_props, + ) + if required: + parameters.required = required + + return types.FunctionDeclaration( + name=self.name, + description=self.description, + parameters=parameters, + ) + + async def run_async( + self, + *, + args: dict[str, Any], + tool_context: ToolContext, + ) -> dict[str, Any]: + """Execute the StackOne tool asynchronously. + + Runs the synchronous StackOneTool.execute() in a thread pool + to avoid blocking the event loop. + """ + try: + loop = asyncio.get_running_loop() + result = await loop.run_in_executor(None, self._stackone_tool.execute, args) + if isinstance(result, dict): + return result + return {"result": result} + except Exception as e: + logger.error(f"Tool {self.name} execution failed: {e}") + return {"error": str(e)} diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_plugin.py b/tests/test_plugin.py new file mode 100644 index 0000000..8acea9d --- /dev/null +++ b/tests/test_plugin.py @@ -0,0 +1,273 @@ +"""Tests for StackOne ADK plugin.""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from stackone_adk.plugin import StackOnePlugin, _discover_account_ids +from stackone_adk.tools import StackOneAdkTool + + +def _make_mock_stackone_tool(name: str = "test_tool", description: str = "A test tool") -> MagicMock: + """Create a mock StackOneTool.""" + tool = MagicMock() + tool.name = name + tool.description = description + tool.parameters = MagicMock() + tool.parameters.properties = {"field": {"type": "string", "nullable": True}} + return tool + + +def _make_mock_tools(count: int = 3) -> MagicMock: + """Create a mock Tools collection that is iterable.""" + tools_list = [_make_mock_stackone_tool(name=f"tool_{i}", description=f"Tool {i}") for i in range(count)] + mock_tools = MagicMock() + mock_tools.__iter__ = MagicMock(return_value=iter(tools_list)) + return mock_tools + + +# Patch both StackOneToolSet and _discover_account_ids for all init tests +PLUGIN_PATCH_TOOLSET = "stackone_adk.plugin.StackOneToolSet" +PLUGIN_PATCH_DISCOVER = "stackone_adk.plugin._discover_account_ids" + + +class TestDiscoverAccountIds: + @patch("stackone_adk.plugin.httpx") + def test_returns_all_account_ids(self, mock_httpx): + mock_resp = MagicMock() + mock_resp.json.return_value = [ + {"id": "acct-1", "provider": "calendly"}, + {"id": "acct-2", "provider": "hibob"}, + ] + mock_httpx.get.return_value = mock_resp + + result = _discover_account_ids("sk-test", "https://api.stackone.com") + assert result == ["acct-1", "acct-2"] + + @patch("stackone_adk.plugin.httpx") + def test_filters_by_provider(self, mock_httpx): + mock_resp = MagicMock() + mock_resp.json.return_value = [ + {"id": "acct-1", "provider": "calendly"}, + {"id": "acct-2", "provider": "hibob"}, + {"id": "acct-3", "provider": "calendly"}, + ] + mock_httpx.get.return_value = mock_resp + + result = _discover_account_ids("sk-test", "https://api.stackone.com", providers=["calendly"]) + assert result == ["acct-1", "acct-3"] + + @patch("stackone_adk.plugin.httpx") + def test_provider_filter_case_insensitive(self, mock_httpx): + mock_resp = MagicMock() + mock_resp.json.return_value = [{"id": "acct-1", "provider": "Calendly"}] + mock_httpx.get.return_value = mock_resp + + result = _discover_account_ids("sk-test", "https://api.stackone.com", providers=["CALENDLY"]) + assert result == ["acct-1"] + + @patch("stackone_adk.plugin.httpx") + def test_skips_accounts_without_id(self, mock_httpx): + mock_resp = MagicMock() + mock_resp.json.return_value = [ + {"id": "acct-1", "provider": "calendly"}, + {"provider": "hibob"}, + {"id": "", "provider": "bamboohr"}, + ] + mock_httpx.get.return_value = mock_resp + + result = _discover_account_ids("sk-test", "https://api.stackone.com") + assert result == ["acct-1"] + + @patch("stackone_adk.plugin.httpx") + def test_empty_accounts(self, mock_httpx): + mock_resp = MagicMock() + mock_resp.json.return_value = [] + mock_httpx.get.return_value = mock_resp + + result = _discover_account_ids("sk-test", "https://api.stackone.com") + assert result == [] + + +class TestStackOnePluginInit: + @patch(PLUGIN_PATCH_DISCOVER, return_value=["acct-auto"]) + @patch(PLUGIN_PATCH_TOOLSET) + def test_default_init_auto_discovers(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(2) + mock_toolset_cls.return_value = mock_toolset + + plugin = StackOnePlugin(api_key="sk-test") + + # Auto-discovery should have been called + mock_discover.assert_called_once() + # fetch_tools should receive the auto-discovered account_ids + mock_toolset.fetch_tools.assert_called_once_with( + account_ids=["acct-auto"], providers=None, actions=None + ) + assert len(plugin.get_tools()) == 2 + assert plugin.name == "stackone_plugin" + + @patch(PLUGIN_PATCH_DISCOVER, return_value=["acct-auto"]) + @patch(PLUGIN_PATCH_TOOLSET) + def test_custom_plugin_name(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(0) + mock_toolset_cls.return_value = mock_toolset + + plugin = StackOnePlugin(api_key="sk-test", plugin_name="my_plugin") + assert plugin.name == "my_plugin" + + @patch(PLUGIN_PATCH_DISCOVER) + @patch(PLUGIN_PATCH_TOOLSET) + def test_skips_discovery_when_account_id_provided(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(0) + mock_toolset_cls.return_value = mock_toolset + + StackOnePlugin(api_key="sk-test", account_id="acct-123", base_url="https://custom.api.com") + + # Auto-discovery should NOT be called when account_id is provided + mock_discover.assert_not_called() + mock_toolset_cls.assert_called_once_with( + api_key="sk-test", + account_id="acct-123", + base_url="https://custom.api.com", + ) + + @patch(PLUGIN_PATCH_DISCOVER) + @patch(PLUGIN_PATCH_TOOLSET) + def test_skips_discovery_when_account_ids_provided(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(0) + mock_toolset_cls.return_value = mock_toolset + + StackOnePlugin( + api_key="sk-test", + providers=["calendly"], + actions=["*_list_*"], + account_ids=["acct-1", "acct-2"], + ) + + mock_discover.assert_not_called() + mock_toolset.fetch_tools.assert_called_once_with( + account_ids=["acct-1", "acct-2"], + providers=["calendly"], + actions=["*_list_*"], + ) + + @patch(PLUGIN_PATCH_DISCOVER, return_value=["acct-auto"]) + @patch(PLUGIN_PATCH_TOOLSET) + def test_passes_providers_to_discovery(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(0) + mock_toolset_cls.return_value = mock_toolset + + StackOnePlugin(api_key="sk-test", providers=["calendly"]) + + mock_discover.assert_called_once_with("sk-test", "https://api.stackone.com", ["calendly"]) + + @patch(PLUGIN_PATCH_DISCOVER, return_value=["acct-auto"]) + @patch(PLUGIN_PATCH_TOOLSET) + def test_tools_converted_to_adk_tools(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(3) + mock_toolset_cls.return_value = mock_toolset + + plugin = StackOnePlugin(api_key="sk-test") + tools = plugin.get_tools() + + assert len(tools) == 3 + for tool in tools: + assert isinstance(tool, StackOneAdkTool) + + @patch("stackone_adk.plugin.StackOneAdkTool") + @patch(PLUGIN_PATCH_DISCOVER, return_value=["acct-auto"]) + @patch(PLUGIN_PATCH_TOOLSET) + def test_failed_conversion_skipped(self, mock_toolset_cls, mock_discover, mock_adk_tool_cls): + mock_toolset = MagicMock() + + good_tool = _make_mock_stackone_tool(name="good_tool") + bad_tool = _make_mock_stackone_tool(name="bad_tool") + + tools_list = [good_tool, bad_tool] + mock_tools = MagicMock() + mock_tools.__iter__ = MagicMock(return_value=iter(tools_list)) + mock_toolset.fetch_tools.return_value = mock_tools + mock_toolset_cls.return_value = mock_toolset + + # Make StackOneAdkTool succeed for good_tool, raise for bad_tool + good_adk_tool = MagicMock() + good_adk_tool.name = "good_tool" + mock_adk_tool_cls.side_effect = [good_adk_tool, ValueError("broken")] + + plugin = StackOnePlugin(api_key="sk-test") + assert len(plugin.get_tools()) == 1 + assert plugin.get_tools()[0].name == "good_tool" + + +class TestStackOnePluginCallbacks: + @patch(PLUGIN_PATCH_DISCOVER, return_value=[]) + @patch(PLUGIN_PATCH_TOOLSET) + def _make_plugin(self, mock_toolset_cls, mock_discover): + mock_toolset = MagicMock() + mock_toolset.fetch_tools.return_value = _make_mock_tools(0) + mock_toolset_cls.return_value = mock_toolset + return StackOnePlugin(api_key="sk-test") + + @pytest.mark.asyncio + async def test_before_agent_callback_returns_none(self): + plugin = self._make_plugin() + result = await plugin.before_agent_callback( + agent=MagicMock(), + callback_context=MagicMock(), + ) + assert result is None + + @pytest.mark.asyncio + async def test_after_agent_callback_returns_none(self): + plugin = self._make_plugin() + result = await plugin.after_agent_callback( + agent=MagicMock(), + callback_context=MagicMock(), + ) + assert result is None + + @pytest.mark.asyncio + async def test_before_tool_callback_returns_none(self): + plugin = self._make_plugin() + result = await plugin.before_tool_callback( + tool=MagicMock(), + tool_args={}, + tool_context=MagicMock(), + ) + assert result is None + + @pytest.mark.asyncio + async def test_after_tool_callback_returns_none(self): + plugin = self._make_plugin() + result = await plugin.after_tool_callback( + tool=MagicMock(), + tool_args={}, + tool_context=MagicMock(), + result={"data": []}, + ) + assert result is None + + @pytest.mark.asyncio + async def test_on_tool_error_callback_returns_none(self): + plugin = self._make_plugin() + result = await plugin.on_tool_error_callback( + tool=MagicMock(), + tool_args={}, + tool_context=MagicMock(), + error=RuntimeError("test error"), + ) + assert result is None + + @pytest.mark.asyncio + async def test_close_is_safe(self): + plugin = self._make_plugin() + await plugin.close() # Should not raise diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..fc01523 --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,260 @@ +"""Tests for StackOne ADK tool adapter and schema conversion.""" + +from __future__ import annotations + +import asyncio +from unittest.mock import MagicMock + +import pytest +from google.genai import types + +from stackone_adk.tools import ( + StackOneAdkTool, + _convert_parameters_to_schema, + _convert_property_to_schema, +) + +# --- Schema conversion tests --- + + +class TestConvertPropertyToSchema: + def test_string_type(self): + schema = _convert_property_to_schema({"type": "string", "description": "A name"}) + assert schema.type == types.Type.STRING + assert schema.description == "A name" + + def test_integer_type(self): + schema = _convert_property_to_schema({"type": "integer"}) + assert schema.type == types.Type.INTEGER + + def test_number_type(self): + schema = _convert_property_to_schema({"type": "number"}) + assert schema.type == types.Type.NUMBER + + def test_boolean_type(self): + schema = _convert_property_to_schema({"type": "boolean"}) + assert schema.type == types.Type.BOOLEAN + + def test_array_type_with_items(self): + schema = _convert_property_to_schema({ + "type": "array", + "items": {"type": "string"}, + "description": "A list of tags", + }) + assert schema.type == types.Type.ARRAY + assert schema.items.type == types.Type.STRING + assert schema.description == "A list of tags" + + def test_object_type_with_properties(self): + schema = _convert_property_to_schema({ + "type": "object", + "properties": { + "name": {"type": "string", "nullable": False}, + "age": {"type": "integer", "nullable": True}, + }, + }) + assert schema.type == types.Type.OBJECT + assert "name" in schema.properties + assert "age" in schema.properties + assert schema.required == ["name"] + + def test_enum_values(self): + schema = _convert_property_to_schema({ + "type": "string", + "enum": ["active", "inactive", "pending"], + }) + assert schema.type == types.Type.STRING + assert schema.enum == ["active", "inactive", "pending"] + + def test_nullable_field(self): + schema = _convert_property_to_schema({"type": "string", "nullable": True}) + assert schema.nullable is True + + def test_non_nullable_field(self): + schema = _convert_property_to_schema({"type": "string", "nullable": False}) + assert schema.nullable is False + + def test_unknown_type_defaults_to_string(self): + schema = _convert_property_to_schema({"type": "custom_type"}) + assert schema.type == types.Type.STRING + + def test_missing_type_defaults_to_string(self): + schema = _convert_property_to_schema({"description": "No type specified"}) + assert schema.type == types.Type.STRING + + def test_unknown_fields_ignored(self): + schema = _convert_property_to_schema({ + "type": "string", + "anyOf": [{"type": "string"}, {"type": "null"}], + "$ref": "#/components/schemas/Foo", + "x-custom": "ignored", + }) + assert schema.type == types.Type.STRING + + +class TestConvertParametersToSchema: + def test_basic_properties(self): + properties = { + "name": {"type": "string", "nullable": False}, + "email": {"type": "string", "nullable": True}, + } + converted, required = _convert_parameters_to_schema(properties) + assert "name" in converted + assert "email" in converted + assert required == ["name"] + + def test_all_required(self): + properties = { + "a": {"type": "string", "nullable": False}, + "b": {"type": "integer", "nullable": False}, + } + _, required = _convert_parameters_to_schema(properties) + assert set(required) == {"a", "b"} + + def test_none_required(self): + properties = { + "a": {"type": "string", "nullable": True}, + "b": {"type": "integer", "nullable": True}, + } + _, required = _convert_parameters_to_schema(properties) + assert required == [] + + def test_non_dict_property_skipped(self): + properties = { + "valid": {"type": "string", "nullable": False}, + "invalid": "not a dict", + } + converted, required = _convert_parameters_to_schema(properties) + assert "valid" in converted + assert "invalid" not in converted + assert required == ["valid"] + + def test_empty_properties(self): + converted, required = _convert_parameters_to_schema({}) + assert converted == {} + assert required == [] + + def test_nullable_not_set_means_not_required(self): + properties = { + "field": {"type": "string"}, + } + _, required = _convert_parameters_to_schema(properties) + assert required == [] + + +# --- Tool adapter tests --- + + +def _make_mock_tool( + name: str = "test_tool", + description: str = "A test tool", + properties: dict | None = None, +) -> MagicMock: + """Create a mock StackOneTool for testing.""" + tool = MagicMock() + tool.name = name + tool.description = description + tool.parameters = MagicMock() + tool.parameters.properties = properties or {} + return tool + + +class TestStackOneAdkTool: + def test_name_and_description(self): + mock_tool = _make_mock_tool(name="calendly_list_events", description="List Calendly events") + adk_tool = StackOneAdkTool(mock_tool) + assert adk_tool.name == "calendly_list_events" + assert adk_tool.description == "List Calendly events" + + def test_declaration_with_parameters(self): + mock_tool = _make_mock_tool( + name="calendly_list_events", + description="List events", + properties={ + "page_size": {"type": "integer", "description": "Number of results", "nullable": True}, + "status": {"type": "string", "description": "Filter by status", "nullable": False}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + assert decl.name == "calendly_list_events" + assert decl.description == "List events" + assert decl.parameters is not None + assert "page_size" in decl.parameters.properties + assert "status" in decl.parameters.properties + assert decl.parameters.required == ["status"] + + def test_declaration_empty_properties(self): + mock_tool = _make_mock_tool(properties={}) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + assert decl.name == "test_tool" + assert decl.parameters is None + + def test_declaration_no_required_fields(self): + mock_tool = _make_mock_tool( + properties={ + "page_size": {"type": "integer", "nullable": True}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + assert decl.parameters is not None + assert not decl.parameters.required + + @pytest.mark.asyncio + async def test_run_async_success(self): + mock_tool = _make_mock_tool() + mock_tool.execute.return_value = {"data": [{"id": "1", "name": "Event"}]} + + adk_tool = StackOneAdkTool(mock_tool) + tool_context = MagicMock() + result = await adk_tool.run_async(args={"page_size": 10}, tool_context=tool_context) + + assert result == {"data": [{"id": "1", "name": "Event"}]} + mock_tool.execute.assert_called_once_with({"page_size": 10}) + + @pytest.mark.asyncio + async def test_run_async_wraps_non_dict_result(self): + mock_tool = _make_mock_tool() + mock_tool.execute.return_value = "plain string result" + + adk_tool = StackOneAdkTool(mock_tool) + tool_context = MagicMock() + result = await adk_tool.run_async(args={}, tool_context=tool_context) + + assert result == {"result": "plain string result"} + + @pytest.mark.asyncio + async def test_run_async_handles_exception(self): + mock_tool = _make_mock_tool() + mock_tool.execute.side_effect = RuntimeError("API connection failed") + + adk_tool = StackOneAdkTool(mock_tool) + tool_context = MagicMock() + result = await adk_tool.run_async(args={}, tool_context=tool_context) + + assert "error" in result + assert "API connection failed" in result["error"] + + @pytest.mark.asyncio + async def test_run_async_concurrent_execution(self): + """Verify multiple tools can execute concurrently via run_in_executor.""" + mock_tool = _make_mock_tool() + mock_tool.execute.return_value = {"ok": True} + + adk_tool = StackOneAdkTool(mock_tool) + tool_context = MagicMock() + + results = await asyncio.gather( + adk_tool.run_async(args={"a": 1}, tool_context=tool_context), + adk_tool.run_async(args={"b": 2}, tool_context=tool_context), + adk_tool.run_async(args={"c": 3}, tool_context=tool_context), + ) + + assert len(results) == 3 + assert all(r == {"ok": True} for r in results) + assert mock_tool.execute.call_count == 3 From 2d5ebe45757686afa9ee6fb714f63c325857f45a Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 09:18:46 +0000 Subject: [PATCH 02/10] Add thr keyword search example for stackone tools --- README.md | 28 ++++++ examples/tool_search_agent.py | 167 ++++++++++++++++++++++++++++++++++ stackone_adk/plugin.py | 120 ++++++++++++++++++++++-- 3 files changed, 308 insertions(+), 7 deletions(-) create mode 100644 examples/tool_search_agent.py diff --git a/README.md b/README.md index 56315a9..434eabc 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,33 @@ async with InMemoryRunner(app_name="calendly_app", agent=agent) as runner: | `providers` | `list[str] \| None` | `None` | Filter by provider names. | | `actions` | `list[str] \| None` | `None` | Filter by action patterns (supports globs). | | `account_ids` | `list[str] \| None` | `None` | Scope tools to specific account IDs. | +| `use_utility_tools` | `bool` | `False` | Expose only `tool_search` + `tool_execute` instead of all tools. | + +## Dynamic Tool Discovery + +When you have many tools across providers, loading them all into the agent's context can be overwhelming. Use `use_utility_tools=True` to give the agent just two meta-tools: + +- **`tool_search`** — searches for relevant tools using keyword matching (hybrid BM25 + TF-IDF) +- **`tool_execute`** — executes a discovered tool by name with parameters + +The agent first searches for the right tool, then executes it: + +```python +plugin = StackOnePlugin( + use_utility_tools=True, # 2 tools instead of all provider tools +) + +agent = Agent( + model="gemini-3.0-flash", + name="assistant", + instruction=( + "Use tool_search to find relevant tools, then tool_execute to run them." + ), + tools=plugin.get_tools(), # [tool_search, tool_execute] +) +``` + +See [`examples/tool_search_agent.py`](examples/tool_search_agent.py) for a full working example. ## Tool Filtering @@ -202,6 +229,7 @@ See the [`examples/`](examples/) directory: |---------|-------------| | [`calendly_agent.py`](examples/calendly_agent.py) | Calendly scheduling agent — single provider | | [`hris_agent.py`](examples/hris_agent.py) | Multi-provider HRIS agent (HiBob, BambooHR) | +| [`tool_search_agent.py`](examples/tool_search_agent.py) | Keyword search for tools — discover and execute dynamically | ## Development diff --git a/examples/tool_search_agent.py b/examples/tool_search_agent.py new file mode 100644 index 0000000..ff63191 --- /dev/null +++ b/examples/tool_search_agent.py @@ -0,0 +1,167 @@ +"""Dynamic tool discovery using keyword search with StackOne and Google ADK. + +StackOne's utility tools let you search for relevant tools using natural +language queries (hybrid BM25 + TF-IDF), then execute the best match — +instead of loading all provider tools into the agent upfront. + +This example shows: + 1. Keyword search across all connected providers + 2. An ADK agent using the discovered tools + +Setup: + 1. Get your StackOne API key from https://app.stackone.com + 2. Connect your providers (e.g. Calendly, HiBob) in the StackOne dashboard + 3. Set environment variables: + export STACKONE_API_KEY="your-stackone-api-key" + export GOOGLE_API_KEY="your-google-api-key" + 4. Run: python examples/tool_search_agent.py +""" + +import asyncio +import json +import logging +import os +import warnings + +from google.adk.agents import Agent +from google.adk.apps import App +from google.adk.runners import InMemoryRunner +from stackone_ai import StackOneToolSet + +from stackone_adk import StackOnePlugin +from stackone_adk.plugin import DEFAULT_BASE_URL, _discover_account_ids + +# Suppress warnings from the Gemini SDK about non-text parts +warnings.filterwarnings("ignore", message=".*non-text parts.*") +_genai_logger = logging.getLogger("google.genai") +_genai_logger.addFilter(lambda r: "non-text parts" not in r.getMessage()) + + +def demo_keyword_search() -> None: + """Demonstrate keyword search for tool discovery.""" + print("=" * 60) + print("Keyword Search — discover tools by query") + print("=" * 60) + + api_key = os.getenv("STACKONE_API_KEY", "") + account_ids = _discover_account_ids(api_key, DEFAULT_BASE_URL) + + toolset = StackOneToolSet(api_key=api_key) + all_tools = toolset.fetch_tools(account_ids=account_ids) + print(f"\n{len(all_tools)} tools across {len(account_ids)} connected account(s)\n") + + utility = all_tools.utility_tools() + search_tool = utility.get_tool("tool_search") + if not search_tool: + print("tool_search not available") + return + + queries = [ + "list events", + "get current user", + "list employees", + ] + + for query in queries: + result = search_tool.execute({"query": query, "limit": 3}) + tools_found = result.get("tools", []) + print(f' "{query}"') + for t in tools_found: + print(f" -> {t['name']} (score: {t['score']:.2f})") + print() + + +def print_events(events: list) -> None: + """Print agent events in a readable format showing the tool call flow.""" + step = 0 + for event in events: + if not event.content or not event.content.parts: + continue + for part in event.content.parts: + if part.function_call: + step += 1 + name = part.function_call.name + args = part.function_call.args or {} + + if name == "tool_search": + query = args.get("query", "") + print(f" [{step}] tool_search(\"{query}\")") + elif name == "tool_execute": + tool_name = args.get("toolName", "?") + params = args.get("params") + if params: + print(f" [{step}] tool_execute({tool_name}, {json.dumps(params)})") + else: + print(f" [{step}] tool_execute({tool_name})") + + elif part.function_response: + resp = part.function_response.response or {} + name = part.function_response.name + + if name == "tool_search": + tools_found = resp.get("tools", []) + for t in tools_found[:3]: + print(f" found: {t['name']} ({t['score']:.2f})") + elif name == "tool_execute": + if "error" in resp: + print(f" error: {resp['error'][:100]}") + else: + resp_str = json.dumps(resp) + if len(resp_str) > 200: + resp_str = resp_str[:200] + "..." + print(f" result: {resp_str}") + + elif part.text: + print(f"\n{'─' * 60}") + print(f"Assistant: {part.text}") + + +async def demo_agent_with_utility_tools() -> None: + """Demonstrate an ADK agent using utility tools.""" + print("=" * 60) + print("ADK Agent — using tool_search + tool_execute") + print("=" * 60) + + plugin = StackOnePlugin(use_utility_tools=True) + tools = plugin.get_tools() + print(f"\nAgent has {len(tools)} tools: {[t.name for t in tools]}\n") + + if not tools: + print("No tools available. Connect a provider in your StackOne dashboard.") + return + + agent = Agent( + model="gemini-2.5-flash", + name="assistant", + description="Assistant that discovers and executes tools via StackOne.", + instruction=( + "You are an assistant with access to tools from multiple SaaS providers " + "via StackOne.\n\n" + "Workflow:\n" + "1. Use tool_search with action words like 'list scheduled events', " + "'get current user' — not provider names like 'Calendly'.\n" + "2. Use tool_execute with the exact parameter schema from the search results.\n" + "3. If a tool needs a parameter you don't have (like a user URI), " + "first search for and execute a tool that provides it.\n\n" + "Never ask the user for IDs, URIs, or technical parameters." + ), + tools=tools, + ) + + app = App(name="tool_search_app", root_agent=agent, plugins=[plugin]) + + async with InMemoryRunner(app=app) as runner: + prompt = "List my upcoming Calendly events" + print(f"User: {prompt}\n") + events = await runner.run_debug(prompt, quiet=True) + print_events(events) + + +async def main() -> None: + demo_keyword_search() + print() + await demo_agent_with_utility_tools() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/stackone_adk/plugin.py b/stackone_adk/plugin.py index cbfce34..fd887bf 100644 --- a/stackone_adk/plugin.py +++ b/stackone_adk/plugin.py @@ -7,6 +7,7 @@ from __future__ import annotations import base64 +import json import logging import os from typing import Any @@ -18,6 +19,8 @@ from google.adk.tools import BaseTool, ToolContext from google.genai import types from stackone_ai import StackOneToolSet +from stackone_ai.models import ExecuteConfig, StackOneTool, ToolParameters +from stackone_ai.utility_tools import ToolIndex from stackone_adk.tools import StackOneAdkTool @@ -55,6 +58,98 @@ def _discover_account_ids( return [a["id"] for a in accounts if a.get("id")] +def _build_utility_tools(tools: Any) -> list[StackOneTool]: + """Build enhanced utility tools that include parameter schemas in search results. + + The SDK's default tool_search returns {name, description, score} but not the + parameter schema. Without the schema, the agent guesses parameter names from + the description, which leads to 400 errors on execution. + + This version includes parameters in the search results so the agent can + construct correct tool_execute calls. + """ + tool_list = list(tools) + tool_map = {t.name: t for t in tool_list} + index = ToolIndex(tool_list) + + # --- tool_search (enhanced with parameter schemas) --- + + def execute_search(arguments: str | dict[str, Any] | None = None) -> dict[str, Any]: + if isinstance(arguments, str): + kwargs = json.loads(arguments) + else: + kwargs = arguments or {} + query = kwargs.get("query", "") + limit = int(kwargs["limit"]) if kwargs.get("limit") is not None else 5 + min_score = float(kwargs["minScore"]) if kwargs.get("minScore") is not None else 0.0 + + results = index.search(query, limit, min_score) + tools_data = [] + for r in results: + tool = tool_map.get(r.name) + entry: dict[str, Any] = { + "name": r.name, + "description": r.description, + "score": r.score, + } + if tool and tool.parameters.properties: + entry["parameters"] = tool.parameters.properties + tools_data.append(entry) + return {"tools": tools_data} + + class EnhancedToolSearch(StackOneTool): + def __init__(self) -> None: + super().__init__( + description=( + "Searches for relevant tools based on a natural language query. " + "Returns tool names, descriptions, relevance scores, and parameter " + "schemas. Call this first to discover available tools before executing them." + ), + parameters=ToolParameters( + type="object", + properties={ + "query": { + "type": "string", + "description": ( + "Natural language query describing what tools you need " + '(e.g., "list events", "get current user")' + ), + }, + "limit": { + "type": "number", + "description": "Maximum number of tools to return (default: 5)", + "nullable": True, + }, + "minScore": { + "type": "number", + "description": "Minimum relevance score 0-1 (default: 0.0)", + "nullable": True, + }, + }, + ), + _execute_config=ExecuteConfig(name="tool_search", method="POST", url="", headers={}), + _api_key="", + _account_id=None, + ) + + def execute( + self, + arguments: str | dict[str, Any] | None = None, + *, + options: dict[str, Any] | None = None, + ) -> dict[str, Any]: + return execute_search(arguments) + + # --- tool_execute (reuse SDK's version) --- + from stackone_ai.models import Tools as ToolsCollection + from stackone_ai.utility_tools import create_tool_execute + + tools_collection = ToolsCollection(tool_list) + execute_tool = create_tool_execute(tools_collection) + + return [EnhancedToolSearch(), execute_tool] + + class StackOnePlugin(BasePlugin): """Plugin for connecting ADK agents to 200+ SaaS providers via StackOne. @@ -73,6 +168,9 @@ class StackOnePlugin(BasePlugin): providers: Filter by provider names (e.g., ["calendly", "hibob"]). actions: Filter by action patterns with globs (e.g., ["*_list_*"]). account_ids: Scope tools to specific account IDs. + use_utility_tools: When True, expose only tool_search and tool_execute + instead of all provider tools. The agent uses tool_search to discover + relevant tools via keyword search, then tool_execute to run them. """ def __init__( @@ -84,6 +182,7 @@ def __init__( providers: list[str] | None = None, actions: list[str] | None = None, account_ids: list[str] | None = None, + use_utility_tools: bool = False, ) -> None: super().__init__(name=plugin_name) @@ -113,13 +212,20 @@ def __init__( actions=actions, ) - for tool in stackone_tools: - try: - self._tools.append(StackOneAdkTool(tool)) - except Exception as e: - logger.warning(f"Failed to convert tool '{tool.name}': {e}") - - logger.info(f"StackOnePlugin initialized with {len(self._tools)} tools") + if use_utility_tools: + for tool in _build_utility_tools(stackone_tools): + try: + self._tools.append(StackOneAdkTool(tool)) + except Exception as e: + logger.warning(f"Failed to convert utility tool '{tool.name}': {e}") + logger.info(f"StackOnePlugin initialized with {len(self._tools)} utility tools") + else: + for tool in stackone_tools: + try: + self._tools.append(StackOneAdkTool(tool)) + except Exception as e: + logger.warning(f"Failed to convert tool '{tool.name}': {e}") + logger.info(f"StackOnePlugin initialized with {len(self._tools)} tools") def get_tools(self) -> list[BaseTool]: """Return pre-converted ADK tools.""" From 23f38009ec05fa6634f333e82f25c3a78fb9d08e Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 10:29:11 +0000 Subject: [PATCH 03/10] Revert "Add thr keyword search example for stackone tools" This reverts commit 2d5ebe45757686afa9ee6fb714f63c325857f45a. --- README.md | 28 ------ examples/tool_search_agent.py | 167 ---------------------------------- stackone_adk/plugin.py | 120 ++---------------------- 3 files changed, 7 insertions(+), 308 deletions(-) delete mode 100644 examples/tool_search_agent.py diff --git a/README.md b/README.md index 434eabc..56315a9 100644 --- a/README.md +++ b/README.md @@ -137,33 +137,6 @@ async with InMemoryRunner(app_name="calendly_app", agent=agent) as runner: | `providers` | `list[str] \| None` | `None` | Filter by provider names. | | `actions` | `list[str] \| None` | `None` | Filter by action patterns (supports globs). | | `account_ids` | `list[str] \| None` | `None` | Scope tools to specific account IDs. | -| `use_utility_tools` | `bool` | `False` | Expose only `tool_search` + `tool_execute` instead of all tools. | - -## Dynamic Tool Discovery - -When you have many tools across providers, loading them all into the agent's context can be overwhelming. Use `use_utility_tools=True` to give the agent just two meta-tools: - -- **`tool_search`** — searches for relevant tools using keyword matching (hybrid BM25 + TF-IDF) -- **`tool_execute`** — executes a discovered tool by name with parameters - -The agent first searches for the right tool, then executes it: - -```python -plugin = StackOnePlugin( - use_utility_tools=True, # 2 tools instead of all provider tools -) - -agent = Agent( - model="gemini-3.0-flash", - name="assistant", - instruction=( - "Use tool_search to find relevant tools, then tool_execute to run them." - ), - tools=plugin.get_tools(), # [tool_search, tool_execute] -) -``` - -See [`examples/tool_search_agent.py`](examples/tool_search_agent.py) for a full working example. ## Tool Filtering @@ -229,7 +202,6 @@ See the [`examples/`](examples/) directory: |---------|-------------| | [`calendly_agent.py`](examples/calendly_agent.py) | Calendly scheduling agent — single provider | | [`hris_agent.py`](examples/hris_agent.py) | Multi-provider HRIS agent (HiBob, BambooHR) | -| [`tool_search_agent.py`](examples/tool_search_agent.py) | Keyword search for tools — discover and execute dynamically | ## Development diff --git a/examples/tool_search_agent.py b/examples/tool_search_agent.py deleted file mode 100644 index ff63191..0000000 --- a/examples/tool_search_agent.py +++ /dev/null @@ -1,167 +0,0 @@ -"""Dynamic tool discovery using keyword search with StackOne and Google ADK. - -StackOne's utility tools let you search for relevant tools using natural -language queries (hybrid BM25 + TF-IDF), then execute the best match — -instead of loading all provider tools into the agent upfront. - -This example shows: - 1. Keyword search across all connected providers - 2. An ADK agent using the discovered tools - -Setup: - 1. Get your StackOne API key from https://app.stackone.com - 2. Connect your providers (e.g. Calendly, HiBob) in the StackOne dashboard - 3. Set environment variables: - export STACKONE_API_KEY="your-stackone-api-key" - export GOOGLE_API_KEY="your-google-api-key" - 4. Run: python examples/tool_search_agent.py -""" - -import asyncio -import json -import logging -import os -import warnings - -from google.adk.agents import Agent -from google.adk.apps import App -from google.adk.runners import InMemoryRunner -from stackone_ai import StackOneToolSet - -from stackone_adk import StackOnePlugin -from stackone_adk.plugin import DEFAULT_BASE_URL, _discover_account_ids - -# Suppress warnings from the Gemini SDK about non-text parts -warnings.filterwarnings("ignore", message=".*non-text parts.*") -_genai_logger = logging.getLogger("google.genai") -_genai_logger.addFilter(lambda r: "non-text parts" not in r.getMessage()) - - -def demo_keyword_search() -> None: - """Demonstrate keyword search for tool discovery.""" - print("=" * 60) - print("Keyword Search — discover tools by query") - print("=" * 60) - - api_key = os.getenv("STACKONE_API_KEY", "") - account_ids = _discover_account_ids(api_key, DEFAULT_BASE_URL) - - toolset = StackOneToolSet(api_key=api_key) - all_tools = toolset.fetch_tools(account_ids=account_ids) - print(f"\n{len(all_tools)} tools across {len(account_ids)} connected account(s)\n") - - utility = all_tools.utility_tools() - search_tool = utility.get_tool("tool_search") - if not search_tool: - print("tool_search not available") - return - - queries = [ - "list events", - "get current user", - "list employees", - ] - - for query in queries: - result = search_tool.execute({"query": query, "limit": 3}) - tools_found = result.get("tools", []) - print(f' "{query}"') - for t in tools_found: - print(f" -> {t['name']} (score: {t['score']:.2f})") - print() - - -def print_events(events: list) -> None: - """Print agent events in a readable format showing the tool call flow.""" - step = 0 - for event in events: - if not event.content or not event.content.parts: - continue - for part in event.content.parts: - if part.function_call: - step += 1 - name = part.function_call.name - args = part.function_call.args or {} - - if name == "tool_search": - query = args.get("query", "") - print(f" [{step}] tool_search(\"{query}\")") - elif name == "tool_execute": - tool_name = args.get("toolName", "?") - params = args.get("params") - if params: - print(f" [{step}] tool_execute({tool_name}, {json.dumps(params)})") - else: - print(f" [{step}] tool_execute({tool_name})") - - elif part.function_response: - resp = part.function_response.response or {} - name = part.function_response.name - - if name == "tool_search": - tools_found = resp.get("tools", []) - for t in tools_found[:3]: - print(f" found: {t['name']} ({t['score']:.2f})") - elif name == "tool_execute": - if "error" in resp: - print(f" error: {resp['error'][:100]}") - else: - resp_str = json.dumps(resp) - if len(resp_str) > 200: - resp_str = resp_str[:200] + "..." - print(f" result: {resp_str}") - - elif part.text: - print(f"\n{'─' * 60}") - print(f"Assistant: {part.text}") - - -async def demo_agent_with_utility_tools() -> None: - """Demonstrate an ADK agent using utility tools.""" - print("=" * 60) - print("ADK Agent — using tool_search + tool_execute") - print("=" * 60) - - plugin = StackOnePlugin(use_utility_tools=True) - tools = plugin.get_tools() - print(f"\nAgent has {len(tools)} tools: {[t.name for t in tools]}\n") - - if not tools: - print("No tools available. Connect a provider in your StackOne dashboard.") - return - - agent = Agent( - model="gemini-2.5-flash", - name="assistant", - description="Assistant that discovers and executes tools via StackOne.", - instruction=( - "You are an assistant with access to tools from multiple SaaS providers " - "via StackOne.\n\n" - "Workflow:\n" - "1. Use tool_search with action words like 'list scheduled events', " - "'get current user' — not provider names like 'Calendly'.\n" - "2. Use tool_execute with the exact parameter schema from the search results.\n" - "3. If a tool needs a parameter you don't have (like a user URI), " - "first search for and execute a tool that provides it.\n\n" - "Never ask the user for IDs, URIs, or technical parameters." - ), - tools=tools, - ) - - app = App(name="tool_search_app", root_agent=agent, plugins=[plugin]) - - async with InMemoryRunner(app=app) as runner: - prompt = "List my upcoming Calendly events" - print(f"User: {prompt}\n") - events = await runner.run_debug(prompt, quiet=True) - print_events(events) - - -async def main() -> None: - demo_keyword_search() - print() - await demo_agent_with_utility_tools() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/stackone_adk/plugin.py b/stackone_adk/plugin.py index fd887bf..cbfce34 100644 --- a/stackone_adk/plugin.py +++ b/stackone_adk/plugin.py @@ -7,7 +7,6 @@ from __future__ import annotations import base64 -import json import logging import os from typing import Any @@ -19,8 +18,6 @@ from google.adk.tools import BaseTool, ToolContext from google.genai import types from stackone_ai import StackOneToolSet -from stackone_ai.models import ExecuteConfig, StackOneTool, ToolParameters -from stackone_ai.utility_tools import ToolIndex from stackone_adk.tools import StackOneAdkTool @@ -58,98 +55,6 @@ def _discover_account_ids( return [a["id"] for a in accounts if a.get("id")] -def _build_utility_tools(tools: Any) -> list[StackOneTool]: - """Build enhanced utility tools that include parameter schemas in search results. - - The SDK's default tool_search returns {name, description, score} but not the - parameter schema. Without the schema, the agent guesses parameter names from - the description, which leads to 400 errors on execution. - - This version includes parameters in the search results so the agent can - construct correct tool_execute calls. - """ - tool_list = list(tools) - tool_map = {t.name: t for t in tool_list} - index = ToolIndex(tool_list) - - # --- tool_search (enhanced with parameter schemas) --- - - def execute_search(arguments: str | dict[str, Any] | None = None) -> dict[str, Any]: - if isinstance(arguments, str): - kwargs = json.loads(arguments) - else: - kwargs = arguments or {} - query = kwargs.get("query", "") - limit = int(kwargs["limit"]) if kwargs.get("limit") is not None else 5 - min_score = float(kwargs["minScore"]) if kwargs.get("minScore") is not None else 0.0 - - results = index.search(query, limit, min_score) - tools_data = [] - for r in results: - tool = tool_map.get(r.name) - entry: dict[str, Any] = { - "name": r.name, - "description": r.description, - "score": r.score, - } - if tool and tool.parameters.properties: - entry["parameters"] = tool.parameters.properties - tools_data.append(entry) - return {"tools": tools_data} - - class EnhancedToolSearch(StackOneTool): - def __init__(self) -> None: - super().__init__( - description=( - "Searches for relevant tools based on a natural language query. " - "Returns tool names, descriptions, relevance scores, and parameter " - "schemas. Call this first to discover available tools before executing them." - ), - parameters=ToolParameters( - type="object", - properties={ - "query": { - "type": "string", - "description": ( - "Natural language query describing what tools you need " - '(e.g., "list events", "get current user")' - ), - }, - "limit": { - "type": "number", - "description": "Maximum number of tools to return (default: 5)", - "nullable": True, - }, - "minScore": { - "type": "number", - "description": "Minimum relevance score 0-1 (default: 0.0)", - "nullable": True, - }, - }, - ), - _execute_config=ExecuteConfig(name="tool_search", method="POST", url="", headers={}), - _api_key="", - _account_id=None, - ) - - def execute( - self, - arguments: str | dict[str, Any] | None = None, - *, - options: dict[str, Any] | None = None, - ) -> dict[str, Any]: - return execute_search(arguments) - - # --- tool_execute (reuse SDK's version) --- - from stackone_ai.models import Tools as ToolsCollection - from stackone_ai.utility_tools import create_tool_execute - - tools_collection = ToolsCollection(tool_list) - execute_tool = create_tool_execute(tools_collection) - - return [EnhancedToolSearch(), execute_tool] - - class StackOnePlugin(BasePlugin): """Plugin for connecting ADK agents to 200+ SaaS providers via StackOne. @@ -168,9 +73,6 @@ class StackOnePlugin(BasePlugin): providers: Filter by provider names (e.g., ["calendly", "hibob"]). actions: Filter by action patterns with globs (e.g., ["*_list_*"]). account_ids: Scope tools to specific account IDs. - use_utility_tools: When True, expose only tool_search and tool_execute - instead of all provider tools. The agent uses tool_search to discover - relevant tools via keyword search, then tool_execute to run them. """ def __init__( @@ -182,7 +84,6 @@ def __init__( providers: list[str] | None = None, actions: list[str] | None = None, account_ids: list[str] | None = None, - use_utility_tools: bool = False, ) -> None: super().__init__(name=plugin_name) @@ -212,20 +113,13 @@ def __init__( actions=actions, ) - if use_utility_tools: - for tool in _build_utility_tools(stackone_tools): - try: - self._tools.append(StackOneAdkTool(tool)) - except Exception as e: - logger.warning(f"Failed to convert utility tool '{tool.name}': {e}") - logger.info(f"StackOnePlugin initialized with {len(self._tools)} utility tools") - else: - for tool in stackone_tools: - try: - self._tools.append(StackOneAdkTool(tool)) - except Exception as e: - logger.warning(f"Failed to convert tool '{tool.name}': {e}") - logger.info(f"StackOnePlugin initialized with {len(self._tools)} tools") + for tool in stackone_tools: + try: + self._tools.append(StackOneAdkTool(tool)) + except Exception as e: + logger.warning(f"Failed to convert tool '{tool.name}': {e}") + + logger.info(f"StackOnePlugin initialized with {len(self._tools)} tools") def get_tools(self) -> list[BaseTool]: """Return pre-converted ADK tools.""" From 3a86475647fc62e82d2ffbf4a889c42ea05b768f Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 12:06:33 +0000 Subject: [PATCH 04/10] Use ADK methods for tool conversation, tempararily use nullable until tool parameter enhament in SDK --- stackone_adk/py.typed | 0 stackone_adk/tools.py | 91 +++----------------- tests/test_tools.py | 194 ++++++++++++------------------------------ 3 files changed, 68 insertions(+), 217 deletions(-) delete mode 100644 stackone_adk/py.typed diff --git a/stackone_adk/py.typed b/stackone_adk/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/stackone_adk/tools.py b/stackone_adk/tools.py index 12c10ba..fdaba40 100644 --- a/stackone_adk/tools.py +++ b/stackone_adk/tools.py @@ -16,74 +16,6 @@ logger = logging.getLogger(__name__) -# JSON Schema type string → google.genai types.Type enum -_TYPE_MAP: dict[str, types.Type] = { - "string": types.Type.STRING, - "integer": types.Type.INTEGER, - "number": types.Type.NUMBER, - "boolean": types.Type.BOOLEAN, - "array": types.Type.ARRAY, - "object": types.Type.OBJECT, -} - - -def _convert_property_to_schema(prop: dict[str, Any]) -> types.Schema: - """Convert a single JSON Schema property dict to a types.Schema. - - Handles type, description, enum, nullable, array items, and nested objects. - Unknown types default to STRING. Unknown fields are silently ignored. - """ - type_str = prop.get("type", "string") - schema_type = _TYPE_MAP.get(type_str, types.Type.STRING) - - kwargs: dict[str, Any] = {"type": schema_type} - - if "description" in prop: - kwargs["description"] = prop["description"] - - if "enum" in prop: - kwargs["enum"] = prop["enum"] - - if "nullable" in prop: - kwargs["nullable"] = prop["nullable"] - - # Handle array items - if schema_type == types.Type.ARRAY and "items" in prop: - items = prop["items"] - if isinstance(items, dict): - kwargs["items"] = _convert_property_to_schema(items) - - # Handle nested object properties - if schema_type == types.Type.OBJECT and "properties" in prop: - nested_props, nested_required = _convert_parameters_to_schema(prop["properties"]) - kwargs["properties"] = nested_props - if nested_required: - kwargs["required"] = nested_required - - return types.Schema(**kwargs) - - -def _convert_parameters_to_schema( - properties: dict[str, Any], -) -> tuple[dict[str, types.Schema], list[str]]: - """Convert all JSON Schema properties to ADK Schema format. - - Returns: - Tuple of (converted properties dict, list of required field names). - Required fields are those with nullable=False (StackOne SDK convention). - """ - converted: dict[str, types.Schema] = {} - required: list[str] = [] - - for name, prop in properties.items(): - if not isinstance(prop, dict): - continue - converted[name] = _convert_property_to_schema(prop) - if prop.get("nullable") is False: - required.append(name) - - return converted, required - class StackOneAdkTool(BaseTool): """Adapter that wraps a StackOneTool as an ADK BaseTool. @@ -100,7 +32,11 @@ def __init__(self, stackone_tool: StackOneTool) -> None: self._stackone_tool = stackone_tool def _get_declaration(self) -> types.FunctionDeclaration: - """Convert StackOne tool parameters to an ADK FunctionDeclaration.""" + """Convert StackOne tool parameters to an ADK FunctionDeclaration. + + Uses ADK's native ``parameters_json_schema`` which accepts raw + JSON Schema dicts directly, matching how ADK's own McpTool works. + """ properties = self._stackone_tool.parameters.properties if not properties: @@ -109,19 +45,20 @@ def _get_declaration(self) -> types.FunctionDeclaration: description=self.description, ) - converted_props, required = _convert_parameters_to_schema(properties) - - parameters = types.Schema( - type=types.Type.OBJECT, - properties=converted_props, - ) + # Build JSON Schema dict — StackOne uses "nullable: false" to mark required fields + schema = self._stackone_tool.parameters.model_dump() + required = [ + name + for name, prop in properties.items() + if isinstance(prop, dict) and prop.get("nullable") is False + ] if required: - parameters.required = required + schema["required"] = required return types.FunctionDeclaration( name=self.name, description=self.description, - parameters=parameters, + parameters_json_schema=schema, ) async def run_async( diff --git a/tests/test_tools.py b/tests/test_tools.py index fc01523..31b96ca 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,4 +1,4 @@ -"""Tests for StackOne ADK tool adapter and schema conversion.""" +"""Tests for StackOne ADK tool adapter.""" from __future__ import annotations @@ -8,141 +8,10 @@ import pytest from google.genai import types -from stackone_adk.tools import ( - StackOneAdkTool, - _convert_parameters_to_schema, - _convert_property_to_schema, -) - -# --- Schema conversion tests --- - - -class TestConvertPropertyToSchema: - def test_string_type(self): - schema = _convert_property_to_schema({"type": "string", "description": "A name"}) - assert schema.type == types.Type.STRING - assert schema.description == "A name" - - def test_integer_type(self): - schema = _convert_property_to_schema({"type": "integer"}) - assert schema.type == types.Type.INTEGER - - def test_number_type(self): - schema = _convert_property_to_schema({"type": "number"}) - assert schema.type == types.Type.NUMBER - - def test_boolean_type(self): - schema = _convert_property_to_schema({"type": "boolean"}) - assert schema.type == types.Type.BOOLEAN - - def test_array_type_with_items(self): - schema = _convert_property_to_schema({ - "type": "array", - "items": {"type": "string"}, - "description": "A list of tags", - }) - assert schema.type == types.Type.ARRAY - assert schema.items.type == types.Type.STRING - assert schema.description == "A list of tags" - - def test_object_type_with_properties(self): - schema = _convert_property_to_schema({ - "type": "object", - "properties": { - "name": {"type": "string", "nullable": False}, - "age": {"type": "integer", "nullable": True}, - }, - }) - assert schema.type == types.Type.OBJECT - assert "name" in schema.properties - assert "age" in schema.properties - assert schema.required == ["name"] - - def test_enum_values(self): - schema = _convert_property_to_schema({ - "type": "string", - "enum": ["active", "inactive", "pending"], - }) - assert schema.type == types.Type.STRING - assert schema.enum == ["active", "inactive", "pending"] - - def test_nullable_field(self): - schema = _convert_property_to_schema({"type": "string", "nullable": True}) - assert schema.nullable is True - - def test_non_nullable_field(self): - schema = _convert_property_to_schema({"type": "string", "nullable": False}) - assert schema.nullable is False - - def test_unknown_type_defaults_to_string(self): - schema = _convert_property_to_schema({"type": "custom_type"}) - assert schema.type == types.Type.STRING - - def test_missing_type_defaults_to_string(self): - schema = _convert_property_to_schema({"description": "No type specified"}) - assert schema.type == types.Type.STRING - - def test_unknown_fields_ignored(self): - schema = _convert_property_to_schema({ - "type": "string", - "anyOf": [{"type": "string"}, {"type": "null"}], - "$ref": "#/components/schemas/Foo", - "x-custom": "ignored", - }) - assert schema.type == types.Type.STRING - - -class TestConvertParametersToSchema: - def test_basic_properties(self): - properties = { - "name": {"type": "string", "nullable": False}, - "email": {"type": "string", "nullable": True}, - } - converted, required = _convert_parameters_to_schema(properties) - assert "name" in converted - assert "email" in converted - assert required == ["name"] - - def test_all_required(self): - properties = { - "a": {"type": "string", "nullable": False}, - "b": {"type": "integer", "nullable": False}, - } - _, required = _convert_parameters_to_schema(properties) - assert set(required) == {"a", "b"} - - def test_none_required(self): - properties = { - "a": {"type": "string", "nullable": True}, - "b": {"type": "integer", "nullable": True}, - } - _, required = _convert_parameters_to_schema(properties) - assert required == [] - - def test_non_dict_property_skipped(self): - properties = { - "valid": {"type": "string", "nullable": False}, - "invalid": "not a dict", - } - converted, required = _convert_parameters_to_schema(properties) - assert "valid" in converted - assert "invalid" not in converted - assert required == ["valid"] - - def test_empty_properties(self): - converted, required = _convert_parameters_to_schema({}) - assert converted == {} - assert required == [] - - def test_nullable_not_set_means_not_required(self): - properties = { - "field": {"type": "string"}, - } - _, required = _convert_parameters_to_schema(properties) - assert required == [] +from stackone_adk.tools import StackOneAdkTool -# --- Tool adapter tests --- +# --- Helper --- def _make_mock_tool( @@ -156,9 +25,16 @@ def _make_mock_tool( tool.description = description tool.parameters = MagicMock() tool.parameters.properties = properties or {} + tool.parameters.model_dump.return_value = { + "type": "object", + "properties": properties or {}, + } return tool +# --- Tool adapter tests --- + + class TestStackOneAdkTool: def test_name_and_description(self): mock_tool = _make_mock_tool(name="calendly_list_events", description="List Calendly events") @@ -180,10 +56,10 @@ def test_declaration_with_parameters(self): assert decl.name == "calendly_list_events" assert decl.description == "List events" - assert decl.parameters is not None - assert "page_size" in decl.parameters.properties - assert "status" in decl.parameters.properties - assert decl.parameters.required == ["status"] + assert decl.parameters_json_schema is not None + assert "page_size" in decl.parameters_json_schema["properties"] + assert "status" in decl.parameters_json_schema["properties"] + assert decl.parameters_json_schema["required"] == ["status"] def test_declaration_empty_properties(self): mock_tool = _make_mock_tool(properties={}) @@ -192,6 +68,7 @@ def test_declaration_empty_properties(self): assert decl.name == "test_tool" assert decl.parameters is None + assert decl.parameters_json_schema is None def test_declaration_no_required_fields(self): mock_tool = _make_mock_tool( @@ -202,8 +79,45 @@ def test_declaration_no_required_fields(self): adk_tool = StackOneAdkTool(mock_tool) decl = adk_tool._get_declaration() - assert decl.parameters is not None - assert not decl.parameters.required + assert decl.parameters_json_schema is not None + assert "required" not in decl.parameters_json_schema + + def test_declaration_all_required_fields(self): + mock_tool = _make_mock_tool( + properties={ + "a": {"type": "string", "nullable": False}, + "b": {"type": "integer", "nullable": False}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + assert set(decl.parameters_json_schema["required"]) == {"a", "b"} + + def test_declaration_nullable_not_set_means_not_required(self): + mock_tool = _make_mock_tool( + properties={ + "field": {"type": "string"}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + assert "required" not in decl.parameters_json_schema + + def test_declaration_passes_raw_json_schema(self): + """Verify the declaration uses parameters_json_schema (not parameters).""" + mock_tool = _make_mock_tool( + properties={ + "name": {"type": "string", "nullable": False}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + # parameters_json_schema should be set, parameters should not + assert decl.parameters_json_schema is not None + assert decl.parameters is None @pytest.mark.asyncio async def test_run_async_success(self): From f457ac996e6c69b1be26432575c73738f1f88002 Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 12:48:14 +0000 Subject: [PATCH 05/10] remove all logging callback and simplify plugin --- stackone_adk/plugin.py | 70 +----------------------------------------- tests/test_plugin.py | 67 ---------------------------------------- 2 files changed, 1 insertion(+), 136 deletions(-) diff --git a/stackone_adk/plugin.py b/stackone_adk/plugin.py index cbfce34..e985faa 100644 --- a/stackone_adk/plugin.py +++ b/stackone_adk/plugin.py @@ -9,14 +9,9 @@ import base64 import logging import os -from typing import Any - import httpx -from google.adk.agents.base_agent import BaseAgent -from google.adk.agents.callback_context import CallbackContext from google.adk.plugins import BasePlugin -from google.adk.tools import BaseTool, ToolContext -from google.genai import types +from google.adk.tools import BaseTool from stackone_ai import StackOneToolSet from stackone_adk.tools import StackOneAdkTool @@ -124,66 +119,3 @@ def __init__( def get_tools(self) -> list[BaseTool]: """Return pre-converted ADK tools.""" return self._tools - - async def before_agent_callback( - self, - *, - agent: BaseAgent, - callback_context: CallbackContext, - ) -> types.Content | None: - """Called before the agent starts processing.""" - return None - - async def after_agent_callback( - self, - *, - agent: BaseAgent, - callback_context: CallbackContext, - ) -> types.Content | None: - """Called after the agent finishes processing.""" - return None - - async def before_tool_callback( - self, - *, - tool: BaseTool, - tool_args: dict[str, Any], - tool_context: ToolContext, - ) -> dict[str, Any] | None: - """Called before a tool is executed.""" - logger.debug(f"Before tool: {tool.name}") - return None - - async def after_tool_callback( - self, - *, - tool: BaseTool, - tool_args: dict[str, Any], - tool_context: ToolContext, - result: dict[str, Any], - ) -> dict[str, Any] | None: - """Called after a tool is executed.""" - logger.debug(f"After tool: {tool.name}") - if isinstance(result, dict) and "error" in result: - logger.warning(f"Tool {tool.name} returned error: {result['error']}") - return None - - async def on_tool_error_callback( - self, - *, - tool: BaseTool, - tool_args: dict[str, Any], - tool_context: ToolContext, - error: Exception, - ) -> dict[str, Any] | None: - """Called when a tool raises an uncaught exception.""" - logger.error(f"Tool {tool.name} raised uncaught exception: {error}") - return None - - async def close(self) -> None: - """Clean up plugin resources. - - StackOneToolSet is stateless HTTP — each execute() is an - independent request — so no cleanup is needed. - """ - logger.debug("StackOnePlugin closed") diff --git a/tests/test_plugin.py b/tests/test_plugin.py index 8acea9d..a318dd3 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -4,8 +4,6 @@ from unittest.mock import MagicMock, patch -import pytest - from stackone_adk.plugin import StackOnePlugin, _discover_account_ids from stackone_adk.tools import StackOneAdkTool @@ -206,68 +204,3 @@ def test_failed_conversion_skipped(self, mock_toolset_cls, mock_discover, mock_a plugin = StackOnePlugin(api_key="sk-test") assert len(plugin.get_tools()) == 1 assert plugin.get_tools()[0].name == "good_tool" - - -class TestStackOnePluginCallbacks: - @patch(PLUGIN_PATCH_DISCOVER, return_value=[]) - @patch(PLUGIN_PATCH_TOOLSET) - def _make_plugin(self, mock_toolset_cls, mock_discover): - mock_toolset = MagicMock() - mock_toolset.fetch_tools.return_value = _make_mock_tools(0) - mock_toolset_cls.return_value = mock_toolset - return StackOnePlugin(api_key="sk-test") - - @pytest.mark.asyncio - async def test_before_agent_callback_returns_none(self): - plugin = self._make_plugin() - result = await plugin.before_agent_callback( - agent=MagicMock(), - callback_context=MagicMock(), - ) - assert result is None - - @pytest.mark.asyncio - async def test_after_agent_callback_returns_none(self): - plugin = self._make_plugin() - result = await plugin.after_agent_callback( - agent=MagicMock(), - callback_context=MagicMock(), - ) - assert result is None - - @pytest.mark.asyncio - async def test_before_tool_callback_returns_none(self): - plugin = self._make_plugin() - result = await plugin.before_tool_callback( - tool=MagicMock(), - tool_args={}, - tool_context=MagicMock(), - ) - assert result is None - - @pytest.mark.asyncio - async def test_after_tool_callback_returns_none(self): - plugin = self._make_plugin() - result = await plugin.after_tool_callback( - tool=MagicMock(), - tool_args={}, - tool_context=MagicMock(), - result={"data": []}, - ) - assert result is None - - @pytest.mark.asyncio - async def test_on_tool_error_callback_returns_none(self): - plugin = self._make_plugin() - result = await plugin.on_tool_error_callback( - tool=MagicMock(), - tool_args={}, - tool_context=MagicMock(), - error=RuntimeError("test error"), - ) - assert result is None - - @pytest.mark.asyncio - async def test_close_is_safe(self): - plugin = self._make_plugin() - await plugin.close() # Should not raise From d1ff8b0121039e34a5fd3f9e2e856caa81c32e8e Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 13:49:03 +0000 Subject: [PATCH 06/10] align the ADK plugin's logic with the SDK's for presence of nullable --- stackone_adk/tools.py | 4 ++-- tests/test_tools.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/stackone_adk/tools.py b/stackone_adk/tools.py index fdaba40..b6216b2 100644 --- a/stackone_adk/tools.py +++ b/stackone_adk/tools.py @@ -45,12 +45,12 @@ def _get_declaration(self) -> types.FunctionDeclaration: description=self.description, ) - # Build JSON Schema dict — StackOne uses "nullable: false" to mark required fields + # Build JSON Schema dict — match SDK logic: fields are required unless explicitly nullable schema = self._stackone_tool.parameters.model_dump() required = [ name for name, prop in properties.items() - if isinstance(prop, dict) and prop.get("nullable") is False + if isinstance(prop, dict) and not prop.get("nullable", False) ] if required: schema["required"] = required diff --git a/tests/test_tools.py b/tests/test_tools.py index 31b96ca..904e8a5 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -94,7 +94,7 @@ def test_declaration_all_required_fields(self): assert set(decl.parameters_json_schema["required"]) == {"a", "b"} - def test_declaration_nullable_not_set_means_not_required(self): + def test_declaration_nullable_not_set_means_required(self): mock_tool = _make_mock_tool( properties={ "field": {"type": "string"}, @@ -103,7 +103,7 @@ def test_declaration_nullable_not_set_means_not_required(self): adk_tool = StackOneAdkTool(mock_tool) decl = adk_tool._get_declaration() - assert "required" not in decl.parameters_json_schema + assert decl.parameters_json_schema["required"] == ["field"] def test_declaration_passes_raw_json_schema(self): """Verify the declaration uses parameters_json_schema (not parameters).""" From bdbf24a0eb54f39ec8096b67323048bd0a69ad8b Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 14:02:18 +0000 Subject: [PATCH 07/10] Make Plugin more resilient --- stackone_adk/plugin.py | 13 +++++++++++-- tests/test_plugin.py | 13 +++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/stackone_adk/plugin.py b/stackone_adk/plugin.py index e985faa..3f5bd09 100644 --- a/stackone_adk/plugin.py +++ b/stackone_adk/plugin.py @@ -83,14 +83,23 @@ def __init__( super().__init__(name=plugin_name) resolved_api_key = api_key if api_key is not None else os.getenv("STACKONE_API_KEY", "") + if not resolved_api_key: + raise ValueError( + "StackOne API key is required. Set the STACKONE_API_KEY environment variable or pass api_key=..." + ) resolved_base_url = base_url or DEFAULT_BASE_URL # Auto-discover account IDs if none provided if not account_id and not account_ids: - account_ids = _discover_account_ids(resolved_api_key, resolved_base_url, providers) - logger.info(f"Auto-discovered {len(account_ids)} account(s)") + try: + account_ids = _discover_account_ids(resolved_api_key, resolved_base_url, providers) + logger.info(f"Auto-discovered {len(account_ids)} account(s)") + except Exception as e: + logger.warning(f"Auto-discovery failed: {e}") + account_ids = [] self._tools: list[BaseTool] = [] + self._toolset: StackOneToolSet | None = None if not account_id and not account_ids: logger.warning("No connected accounts found. No tools will be available.") diff --git a/tests/test_plugin.py b/tests/test_plugin.py index a318dd3..24b79b2 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -4,6 +4,8 @@ from unittest.mock import MagicMock, patch +import pytest + from stackone_adk.plugin import StackOnePlugin, _discover_account_ids from stackone_adk.tools import StackOneAdkTool @@ -204,3 +206,14 @@ def test_failed_conversion_skipped(self, mock_toolset_cls, mock_discover, mock_a plugin = StackOnePlugin(api_key="sk-test") assert len(plugin.get_tools()) == 1 assert plugin.get_tools()[0].name == "good_tool" + + def test_raises_on_missing_api_key(self): + with patch.dict("os.environ", {}, clear=True): + with pytest.raises(ValueError, match="StackOne API key is required"): + StackOnePlugin() + + @patch(PLUGIN_PATCH_DISCOVER, side_effect=RuntimeError("connection refused")) + @patch(PLUGIN_PATCH_TOOLSET) + def test_graceful_discovery_failure(self, mock_toolset_cls, mock_discover): + plugin = StackOnePlugin(api_key="sk-test") + assert plugin.get_tools() == [] From 602754e9ee51cd70f1dc2692cc4d5a2b2890ae20 Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Mon, 16 Feb 2026 14:30:34 +0000 Subject: [PATCH 08/10] Use gemini-2.5-flash everywhere for reproducibility --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 56315a9..457cd3f 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ def get_current_time(city: str) -> dict: return {"status": "success", "city": city, "time": "10:30 AM"} root_agent = Agent( - model="gemini-3.0-flash", + model="gemini-2.5-flash", name="root_agent", tools=[get_current_time], ) @@ -72,7 +72,7 @@ async def main(): plugin = StackOnePlugin() # reads STACKONE_API_KEY from env agent = Agent( - model="gemini-3.0-flash", + model="gemini-2.5-flash", name="calendly_agent", # replace with your agent name instruction="You are a scheduling assistant with access to Calendly.", tools=plugin.get_tools(), # instead of: tools=[get_current_time] @@ -98,7 +98,7 @@ from google.adk.runners import InMemoryRunner plugin = StackOnePlugin(providers=["calendly"]) agent = Agent( - model="gemini-3.0-flash", + model="gemini-2.5-flash", name="calendly_agent", # replace with your agent name tools=plugin.get_tools(), ) @@ -117,7 +117,7 @@ from google.adk.runners import InMemoryRunner plugin = StackOnePlugin(providers=["calendly"]) agent = Agent( - model="gemini-3.0-flash", + model="gemini-2.5-flash", name="calendly_agent", # replace with your agent name tools=plugin.get_tools(), ) From 0b54fac1a453c9daf1009721f161744aa0bf2791 Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Tue, 17 Feb 2026 09:38:15 +0000 Subject: [PATCH 09/10] Remove the HRIS example and make intructions less verbose for the Agent --- examples/calendly_agent.py | 4 -- examples/hris_agent.py | 86 -------------------------------------- 2 files changed, 90 deletions(-) delete mode 100644 examples/hris_agent.py diff --git a/examples/calendly_agent.py b/examples/calendly_agent.py index a1a64f0..cddbcaa 100644 --- a/examples/calendly_agent.py +++ b/examples/calendly_agent.py @@ -53,10 +53,6 @@ async def main() -> None: "You are a scheduling assistant powered by StackOne and Calendly. " "You help users manage their scheduling by listing event types " "and checking scheduled events.\n\n" - "When asked about scheduled events, always use the tools directly " - "to fetch the data — do not ask the user for URIs or parameters. " - "First call calendly_get_current_user to get the user URI, then " - "use that URI in subsequent calls.\n\n" "Always be helpful and provide clear, organized responses." ), tools=tools, diff --git a/examples/hris_agent.py b/examples/hris_agent.py deleted file mode 100644 index 7780091..0000000 --- a/examples/hris_agent.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Multi-provider HRIS agent using StackOne plugin for Google ADK. - -StackOne lets you combine tools from multiple SaaS providers and filter -by action type — all discovered dynamically from your connected accounts: - - plugin = StackOnePlugin( - providers=["hibob", "bamboohr"], - actions=["*_list_*", "*_get_*"], # read-only operations only - ) - agent = Agent( - model="gemini-2.5-flash", - name="hris_agent", - tools=plugin.get_tools(), # tools from both providers - ) - -Setup: - 1. Get your StackOne API key from https://app.stackone.com - 2. Connect your HRIS providers in the StackOne dashboard - 3. Set environment variables: - export STACKONE_API_KEY="your-stackone-api-key" - export GOOGLE_API_KEY="your-google-api-key" - 4. Run: python examples/hris_agent.py -""" - -import asyncio -import logging - -from google.adk.agents import Agent -from google.adk.apps import App -from google.adk.runners import InMemoryRunner - -from stackone_adk import StackOnePlugin - -# Suppress "non-text parts" warning from the Gemini SDK -_genai_logger = logging.getLogger("google.genai") -_genai_logger.addFilter(lambda r: "non-text parts" not in r.getMessage()) - - -async def main() -> None: - # Combine multiple providers with optional action filtering - plugin = StackOnePlugin( - providers=["hibob", "bamboohr"], - actions=["*_list_*", "*_get_*"], # read-only operations only - ) - - tools = plugin.get_tools() - print(f"Discovered {len(tools)} HRIS tools\n") - - if not tools: - print("No HRIS tools found. Connect HiBob or BambooHR in your StackOne dashboard.") - return - - # Create agent with tools from multiple providers - agent = Agent( - model="gemini-2.5-flash", - name="hris_agent", # replace with your agent name - description="Agent to answer questions using HiBob and BambooHR data.", - instruction=( - "You are a read-only HRIS assistant with access to multiple providers " - "via StackOne. You can list and retrieve data from HiBob and BambooHR, " - "but you cannot create, update, or delete anything.\n\n" - "When asked to list employees or retrieve data, use the tools directly " - "— do not ask the user for additional parameters.\n\n" - "Always clarify which provider the data comes from in your responses." - ), - tools=tools, - ) - - app = App(name="hris_app", root_agent=agent, plugins=[plugin]) - - async with InMemoryRunner(app=app) as runner: - prompt = "List employees from HiBob" - print(f"User: {prompt}") - print("=" * 60) - events = await runner.run_debug(prompt, quiet=True) - # Extract the agent's final text response - for event in reversed(events): - if event.content and event.content.parts: - text_parts = [p.text for p in event.content.parts if p.text] - if text_parts: - print(f"Agent: {''.join(text_parts)}\n") - break - - -if __name__ == "__main__": - asyncio.run(main()) From 31efe1027576406ca7fff489b764f5c71d6be457 Mon Sep 17 00:00:00 2001 From: Shashikant86 Date: Tue, 17 Feb 2026 09:47:59 +0000 Subject: [PATCH 10/10] Remove the HRIS example from README --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 457cd3f..593a014 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,6 @@ See the [`examples/`](examples/) directory: | Example | Description | |---------|-------------| | [`calendly_agent.py`](examples/calendly_agent.py) | Calendly scheduling agent — single provider | -| [`hris_agent.py`](examples/hris_agent.py) | Multi-provider HRIS agent (HiBob, BambooHR) | ## Development