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..593a014 --- /dev/null +++ b/README.md @@ -0,0 +1,242 @@ +# 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-2.5-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-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] + ) + + 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-2.5-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-2.5-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 | + +## 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..cddbcaa --- /dev/null +++ b/examples/calendly_agent.py @@ -0,0 +1,79 @@ +"""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" + "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/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..3f5bd09 --- /dev/null +++ b/stackone_adk/plugin.py @@ -0,0 +1,130 @@ +"""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 +import httpx +from google.adk.plugins import BasePlugin +from google.adk.tools import BaseTool +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", "") + 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: + 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.") + 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 diff --git a/stackone_adk/tools.py b/stackone_adk/tools.py new file mode 100644 index 0000000..b6216b2 --- /dev/null +++ b/stackone_adk/tools.py @@ -0,0 +1,83 @@ +"""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__) + + +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. + + 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: + return types.FunctionDeclaration( + name=self.name, + description=self.description, + ) + + # 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 not prop.get("nullable", False) + ] + if required: + schema["required"] = required + + return types.FunctionDeclaration( + name=self.name, + description=self.description, + parameters_json_schema=schema, + ) + + 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..24b79b2 --- /dev/null +++ b/tests/test_plugin.py @@ -0,0 +1,219 @@ +"""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" + + 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() == [] diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..904e8a5 --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,174 @@ +"""Tests for StackOne ADK tool adapter.""" + +from __future__ import annotations + +import asyncio +from unittest.mock import MagicMock + +import pytest +from google.genai import types + +from stackone_adk.tools import StackOneAdkTool + + +# --- Helper --- + + +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 {} + 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") + 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_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={}) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + 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( + properties={ + "page_size": {"type": "integer", "nullable": True}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + 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_required(self): + mock_tool = _make_mock_tool( + properties={ + "field": {"type": "string"}, + }, + ) + adk_tool = StackOneAdkTool(mock_tool) + decl = adk_tool._get_declaration() + + assert decl.parameters_json_schema["required"] == ["field"] + + 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): + 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