Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Fix Throw error when explicit toolkit version is not provided for manual execute (#2070)
Musthaq Ahamad157bf7ba4ece
diff --git a/.changeset/vast-rings-tan.md b/.changeset/vast-rings-tan.mdnew file mode 100644index 000000000..b4fe54bd8--- /dev/null+++ b/.changeset/vast-rings-tan.md@@ -0,0 +1,68 @@+---+'@composio/core': minor+'@composio/anthropic': minor+'@composio/cloudflare': minor+'@composio/google': minor+'@composio/langchain': minor+'@composio/llamaindex': minor+'@composio/mastra': minor+'@composio/openai': minor+'@composio/openai-agents': minor+'@composio/vercel': patch+'@composio/json-schema-to-zod': patch+---++### Added+- **Version validation for manual tool execution**: Tools now require explicit toolkit version specification when executing manually to prevent unexpected behavior from `latest` version changes+- **New `dangerously_skip_version_check` parameter** (Python) / `dangerouslySkipVersionCheck` (TypeScript): Optional flag to bypass version validation (use with caution)+- **`ToolVersionRequiredError` exception** (Python): Raised when attempting to execute tools with `latest` version without skip flag, includes helpful error messages with 4 possible fixes+- **`ComposioToolVersionRequiredError` error** (TypeScript): Parallel implementation for TypeScript SDK with detailed error context and resolution suggestions+- **Comprehensive test coverage**: Added 19 new test methods in Python covering all tool execution scenarios including version resolution, error handling, modifiers, and environment variables++### Changed+- **Tool execution behavior**: Manual execution via `tools.execute()` now validates toolkit versions before API calls+- **Agentic provider flows**: Automatically set `dangerously_skip_version_check=True` internally to maintain backward compatibility for framework integrations+- **Instance-level version resolution**: Both `execute()` and `_execute_tool()` methods now consistently resolve versions from instance-level `toolkit_versions` configuration+- **Modifier support**: Added `dangerously_skip_version_check` to modifier parameter types for complete flow coverage+- **Test version format**: Updated all test files to use production date-based version format (`20251201_XX`) instead of semantic versioning++### Fixed+- **Consistent version handling**: Removed `toolkit_versions` parameter from `_execute_tool()` in favor of instance-level configuration, ensuring consistent version resolution across the SDK+- **Code formatting**: Applied ruff formatting to all modified Python files+- **Array parsing to ZodSchema**: Fixes in json-schema-to-zod to parse array without properties and with properties++### Migration Guide+When manually executing tools, you must now specify toolkit versions:++**Option 1: Pass explicit version parameter**+```python+tools.execute("GITHUB_CREATE_ISSUE",+ arguments={...},+ version="20251201_01"+)+```++**Option 2: Configure at SDK initialization**+```python+tools = Tools(client, provider,+ toolkit_versions={"github": "20251201_01"}+)+```++**Option 3: Use environment variables**+```bash+export COMPOSIO_TOOLKIT_VERSION_GITHUB=20251201_01+```++**Option 4: Skip validation (not recommended)**+```python+tools.execute("GITHUB_CREATE_ISSUE",+ arguments={...},+ dangerously_skip_version_check=True+)+```++### Developer Notes+- Agentic framework integrations (LangChain, CrewAI, etc.) are not affected as they automatically use the skip flag+- The `latest` version can still be used with the skip flag, but specific versions are strongly recommended+- Error messages include all available resolution options for better developer experience\ No newline at end of filediff --git a/python/composio/core/models/_modifiers.py b/python/composio/core/models/_modifiers.pyindex c8538f725..72bb300d3 100644--- a/python/composio/core/models/_modifiers.py+++ b/python/composio/core/models/_modifiers.py@@ -18,6 +18,7 @@ class ToolExecuteParams(te.TypedDict):user_id: t.Optional[str]text: t.Optional[str]version: t.Optional[str]+ dangerously_skip_version_check: te.NotRequired[t.Optional[bool]]ModifierInOut = t.Union["ToolExecuteParams", "ToolExecutionResponse", "Tool"]diff --git a/python/composio/core/models/tools.py b/python/composio/core/models/tools.pyindex 3c5b7440a..ae56f1efc 100644--- a/python/composio/core/models/tools.py+++ b/python/composio/core/models/tools.py@@ -25,7 +25,7 @@ from composio.core.provider.none_agentic import (NoneAgenticProviderExecuteFn,)from composio.core.types import ToolkitVersionParam-from composio.exceptions import InvalidParams, NotFoundError+from composio.exceptions import InvalidParams, NotFoundError, ToolVersionRequiredErrorfrom composio.utils.pydantic import none_to_omitfrom composio.utils.toolkit_version import get_toolkit_version@@ -296,6 +296,9 @@ class Tools(Resource, t.Generic[TProvider]):self.execute,modifiers=modifiers,user_id=user_id,+ # Dangerously skip version check for agentic and non-agentic tool execution via providers+ # This can be safe because most agentic flows users fetch latest version and then execute the tool+ dangerously_skip_version_check=True,),)@@ -336,17 +339,23 @@ class Tools(Resource, t.Generic[TProvider]):user_id: t.Optional[str] = None,text: t.Optional[str] = None,version: t.Optional[str] = None,- toolkit_versions: t.Optional[ToolkitVersionParam] = None,+ dangerously_skip_version_check: t.Optional[bool] = None,) -> ToolExecutionResponse:"""Execute a tool"""# Get the tool to determine its toolkittool = self.get_raw_composio_tool_by_slug(slug)- # If version is not explicitly provided, resolve it from toolkit versions- # This matches the TypeScript behavior- if version is None and toolkit_versions is not None:+ # If version is not explicitly provided, resolve it from instance-level toolkit versions+ # This matches the TypeScript behavior - always resolve version when None+ if version is None:toolkit_slug = tool.toolkit.slug if tool.toolkit else "unknown"- version = get_toolkit_version(toolkit_slug, toolkit_versions)+ # Use instance-level toolkit versions configuration+ version = get_toolkit_version(toolkit_slug, self._toolkit_versions)++ # Check if the version is 'latest' and dangerously_skip_version_check is not True+ # If so, raise an error to prevent unexpected behavior+ if version == "latest" and not dangerously_skip_version_check:+ raise ToolVersionRequiredError()return t.cast(ToolExecutionResponse,@@ -359,7 +368,6 @@ class Tools(Resource, t.Generic[TProvider]):user_id=none_to_omit(user_id),text=none_to_omit(text),version=none_to_omit(version),- # Note: We don't pass toolkit_versions to the API, we resolve the specific version above).model_dump(exclude={"log_id",@@ -381,7 +389,7 @@ class Tools(Resource, t.Generic[TProvider]):user_id: t.Optional[str] = None,text: t.Optional[str] = None,version: t.Optional[str] = None,- toolkit_versions: t.Optional[ToolkitVersionParam] = None,+ dangerously_skip_version_check: t.Optional[bool] = None,modifiers: t.Optional[Modifiers] = None,) -> ToolExecutionResponse:"""@@ -398,13 +406,11 @@ class Tools(Resource, t.Generic[TProvider])::param custom_connection_data: The custom connection data to use for the tool, takes priority over custom_auth_params.:param user_id: The ID of the user to execute the tool for.:param text: The text to pass to the tool.- :param version: The version of the tool to execute.- :param toolkit_versions: Toolkit versions to use for execution, overrides the SDK-level configuration.+ :param version: The version of the tool to execute (overrides the SDK-level toolkit versions for this execution).+ :param dangerously_skip_version_check: Skip the version check for 'latest' version. This might cause unexpected behavior when new versions are released.:param modifiers: The modifiers to apply to the tool.:return: The response from the tool."""- # Use provided toolkit_versions or fall back to instance-level versions- effective_toolkit_versions = toolkit_versions or self._toolkit_versionstool = self._tool_schemas.get(slug)if tool is None and self._custom_tools.get(slug=slug) is not None:@@ -416,7 +422,7 @@ class Tools(Resource, t.Generic[TProvider]):Tool,self._client.tools.retrieve(tool_slug=slug,- toolkit_versions=none_to_omit(effective_toolkit_versions),+ toolkit_versions=none_to_omit(self._toolkit_versions),),)self._tool_schemas[slug] = tool@@ -435,6 +441,7 @@ class Tools(Resource, t.Generic[TProvider]):"text": text,"user_id": user_id,"arguments": arguments,+ "dangerously_skip_version_check": dangerously_skip_version_check,},)connected_account_id = processed_params["connected_account_id"]@@ -444,6 +451,9 @@ class Tools(Resource, t.Generic[TProvider]):version = processed_params["version"]user_id = processed_params["user_id"]arguments = processed_params["arguments"]+ dangerously_skip_version_check = processed_params.get(+ "dangerously_skip_version_check"+ )arguments = self._file_helper.substitute_file_uploads(tool=tool,@@ -465,7 +475,7 @@ class Tools(Resource, t.Generic[TProvider]):user_id=user_id,text=text,version=version,- toolkit_versions=none_to_omit(effective_toolkit_versions),+ dangerously_skip_version_check=dangerously_skip_version_check,))response = self._file_helper.substitute_file_downloads(diff --git a/python/composio/exceptions.py b/python/composio/exceptions.pyindex cad8522eb..4c5d5525b 100644--- a/python/composio/exceptions.py+++ b/python/composio/exceptions.py@@ -281,5 +281,26 @@ class ExecuteToolFnNotSetError(ComposioError):pass+class ToolVersionRequiredError(ComposioError):+ """Raised when toolkit version is not specified for manual tool execution."""++ def __init__(self) -> None:+ super().__init__(+ message=(+ "Toolkit version not specified. For manual execution of the tool "+ "please pass a specific toolkit version.\n\n"+ "Possible fixes:\n"+ "1. Pass the toolkit version as a parameter to the execute function "+ '("latest" is not supported in manual execution)\n'+ "2. Set the toolkit versions in the Composio config "+ "(toolkit_versions={'<toolkit-slug>': '<toolkit-version>'})\n"+ "3. Set the toolkit version in the environment variable "+ "(COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_SLUG>)\n"+ "4. Set dangerously_skip_version_check to True "+ "(this might cause unexpected behavior when new versions of the tools are released)"+ ),+ )++class UsageError(ComposioError):passdiff --git a/python/providers/anthropic/pyproject.toml b/python/providers/anthropic/pyproject.tomlindex 35e3daa6b..d5a3552b2 100644--- a/python/providers/anthropic/pyproject.toml+++ b/python/providers/anthropic/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-anthropic"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your Anthropic LLMs."readme = "README.md"requires-python = ">=3.10,<4"diff --git a/python/providers/anthropic/setup.py b/python/providers/anthropic/setup.pyindex b4614c75b..cdc23db0f 100644--- a/python/providers/anthropic/setup.py+++ b/python/providers/anthropic/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_anthropic",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Anthropic LLMs.",diff --git a/python/providers/autogen/pyproject.toml b/python/providers/autogen/pyproject.tomlindex 2e11720d1..75d22913e 100644--- a/python/providers/autogen/pyproject.toml+++ b/python/providers/autogen/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-autogen"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your autogen agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/autogen/setup.py b/python/providers/autogen/setup.pyindex b2357ca73..9b3f4fcc0 100644--- a/python/providers/autogen/setup.py+++ b/python/providers/autogen/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_autogen",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Autogen agent.",diff --git a/python/providers/crewai/pyproject.toml b/python/providers/crewai/pyproject.tomlindex cd1b56699..804cd3206 100644--- a/python/providers/crewai/pyproject.toml+++ b/python/providers/crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-crewai"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your CrewAI agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/crewai/setup.py b/python/providers/crewai/setup.pyindex a9ae67817..59606ecec 100644--- a/python/providers/crewai/setup.py+++ b/python/providers/crewai/setup.py@@ -6,7 +6,7 @@ from setuptools import setupsetup(name="composio_crewai",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your CrewAI agent.",diff --git a/python/providers/gemini/pyproject.toml b/python/providers/gemini/pyproject.tomlindex c2acce4f8..52074ff5e 100644--- a/python/providers/gemini/pyproject.toml+++ b/python/providers/gemini/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-gemini"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your Gemini agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/gemini/setup.py b/python/providers/gemini/setup.pyindex 6fd8eeb6d..58121077a 100644--- a/python/providers/gemini/setup.py+++ b/python/providers/gemini/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_gemini",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Gemini agent.",diff --git a/python/providers/google/pyproject.toml b/python/providers/google/pyproject.tomlindex 59931a85b..665cdfd21 100644--- a/python/providers/google/pyproject.toml+++ b/python/providers/google/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-google"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your Google AI Python Gemini model."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/google/setup.py b/python/providers/google/setup.pyindex 8df24550e..c6b17b27a 100644--- a/python/providers/google/setup.py+++ b/python/providers/google/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_google",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Google AI Python Gemini model.",diff --git a/python/providers/google_adk/pyproject.toml b/python/providers/google_adk/pyproject.tomlindex 721511ab4..fc6c77a26 100644--- a/python/providers/google_adk/pyproject.toml+++ b/python/providers/google_adk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-google-adk"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your Google AI Python Gemini model."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/google_adk/setup.py b/python/providers/google_adk/setup.pyindex 8bb8a2c89..b4023b5ad 100644--- a/python/providers/google_adk/setup.py+++ b/python/providers/google_adk/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_google_adk",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Google AI Python Gemini model.",diff --git a/python/providers/langchain/pyproject.toml b/python/providers/langchain/pyproject.tomlindex 7c23bb86d..9f420b278 100644--- a/python/providers/langchain/pyproject.toml+++ b/python/providers/langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-langchain"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your Langchain agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/langchain/setup.py b/python/providers/langchain/setup.pyindex b1e692095..c6c284e62 100644--- a/python/providers/langchain/setup.py+++ b/python/providers/langchain/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_langchain",- version="0.8.20",+ version="0.9.0",author="composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Langchain agent.",diff --git a/python/providers/langgraph/pyproject.toml b/python/providers/langgraph/pyproject.tomlindex fbb850d6b..b6ee761cf 100644--- a/python/providers/langgraph/pyproject.toml+++ b/python/providers/langgraph/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-langgraph"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get array of tools with LangGraph Agent Workflows."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/langgraph/setup.py b/python/providers/langgraph/setup.pyindex e74dcfd4f..3aeb4d160 100644--- a/python/providers/langgraph/setup.py+++ b/python/providers/langgraph/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_langgraph",- version="0.8.20",+ version="0.9.0",author="composio",author_email="[email protected]",description="Use Composio to get array of tools with LangGraph Agent Workflows",diff --git a/python/providers/llamaindex/pyproject.toml b/python/providers/llamaindex/pyproject.tomlindex 645addce1..b7b9ad9a9 100644--- a/python/providers/llamaindex/pyproject.toml+++ b/python/providers/llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-llamaindex"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/llamaindex/setup.py b/python/providers/llamaindex/setup.pyindex a78947c6a..796b3f193 100644--- a/python/providers/llamaindex/setup.py+++ b/python/providers/llamaindex/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_llamaindex",- version="0.8.20",+ version="0.9.0",author="composio",author_email="[email protected]",description="Use Composio to get array of tools with LlamaIndex Agent Workflows",diff --git a/python/providers/openai/pyproject.toml b/python/providers/openai/pyproject.tomlindex 70be43b16..7e5bfc5b8 100644--- a/python/providers/openai/pyproject.toml+++ b/python/providers/openai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-openai"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get an array of tools with your OpenAI Function Call."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/openai/setup.py b/python/providers/openai/setup.pyindex acd3b2ca2..5ad56d2fc 100644--- a/python/providers/openai/setup.py+++ b/python/providers/openai/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_openai",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your OpenAI Function Call.",diff --git a/python/providers/openai_agents/pyproject.toml b/python/providers/openai_agents/pyproject.tomlindex 1b2d4cc2a..e956076fa 100644--- a/python/providers/openai_agents/pyproject.toml+++ b/python/providers/openai_agents/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-openai-agents"-version = "0.8.20"+version = "0.9.0"description = "Use Composio to get array of strongly typed tools for OpenAI Agents"readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/openai_agents/setup.py b/python/providers/openai_agents/setup.pyindex a2355a1a8..7a6c62643 100644--- a/python/providers/openai_agents/setup.py+++ b/python/providers/openai_agents/setup.py@@ -8,7 +8,7 @@ from setuptools import find_packages, setupsetup(name="composio_openai_agents",- version="0.8.20",+ version="0.9.0",author="Composio",author_email="[email protected]",description="Use Composio to get array of strongly typed tools for OpenAI Agents",diff --git a/python/pyproject.toml b/python/pyproject.tomlindex 89217b6a8..77162482b 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio"-version = "0.8.20"+version = "0.9.0"description = "SDK for integrating Composio with your applications."readme = "README.md"requires-python = ">=3.10,<4"diff --git a/python/tests/test_tool_execution.py b/python/tests/test_tool_execution.pyindex a3a830bba..ae5c87fcc 100644--- a/python/tests/test_tool_execution.py+++ b/python/tests/test_tool_execution.py@@ -1,9 +1,20 @@"""Test tool execution with toolkit versions."""+import pytestfrom unittest.mock import Mock, patchfrom composio.client.types import Tool, tool_list_responsefrom composio.core.models.tools import Tools+from composio.core.models.base import allow_tracking+from composio.exceptions import ToolVersionRequiredError++[email protected](autouse=True)+def disable_telemetry():+ """Disable telemetry for all tests to prevent thread issues."""+ token = allow_tracking.set(False)+ yield+ allow_tracking.reset(token)class TestToolExecution:@@ -42,7 +53,7 @@ class TestToolExecution:mock_provider.name = "test_provider"# Create toolkit versions configuration- toolkit_versions = {"github": "v2.0.0", "slack": "v1.5.0"}+ toolkit_versions = {"github": "20251201_01", "slack": "20251201_02"}# Create Tools instancetools = Tools(@@ -71,15 +82,14 @@ class TestToolExecution:tools._execute_tool(slug="GITHUB_GET_REPOS",arguments={"owner": "test", "repo": "test"},- toolkit_versions=toolkit_versions,)# Verify that the client was called with the resolved versionmock_client.tools.execute.assert_called_once()call_args = mock_client.tools.execute.call_args- # Should have called with version="v2.0.0" (resolved from github toolkit)- assert call_args.kwargs["version"] == "v2.0.0"+ # Should have called with version="20251201_01" (resolved from github toolkit)+ assert call_args.kwargs["version"] == "20251201_01"def test_tool_execution_with_explicit_version(self):"""Test that explicit version overrides toolkit version."""@@ -90,7 +100,7 @@ class TestToolExecution:# Create toolkit versions configurationtoolkit_versions = {- "github": "v2.0.0",+ "github": "20251201_01",}# Create Tools instance@@ -120,8 +130,7 @@ class TestToolExecution:tools._execute_tool(slug="GITHUB_GET_REPOS",arguments={"owner": "test", "repo": "test"},- version="v3.0.0", # Explicit version should take precedence- toolkit_versions=toolkit_versions,+ version="20251201_03", # Explicit version should take precedence)# Verify that the client was called with the explicit version@@ -129,7 +138,7 @@ class TestToolExecution:call_args = mock_client.tools.execute.call_args# Should have called with explicit version, not resolved from toolkit- assert call_args.kwargs["version"] == "v3.0.0"+ assert call_args.kwargs["version"] == "20251201_03"def test_tool_execution_unknown_toolkit_fallback(self):"""Test that unknown toolkit falls back to 'latest'."""@@ -140,7 +149,7 @@ class TestToolExecution:# Create toolkit versions configuration that doesn't include the tool's toolkittoolkit_versions = {- "slack": "v1.5.0" # No github version specified+ "slack": "20251201_02" # No github version specified}# Create Tools instance@@ -166,11 +175,11 @@ class TestToolExecution:}mock_client.tools.execute.return_value = mock_execute_response- # Execute the tool+ # Execute the tool with dangerously_skip_version_check since version will be 'latest'tools._execute_tool(slug="GITHUB_GET_REPOS",arguments={"owner": "test", "repo": "test"},- toolkit_versions=toolkit_versions,+ dangerously_skip_version_check=True,)# Verify that the client was called with "latest" (fallback)@@ -188,7 +197,7 @@ class TestToolExecution:mock_provider.name = "test_provider"# Create global toolkit version (string)- toolkit_versions = "v3.0.0"+ toolkit_versions = "20251201_03"# Create Tools instancetools = Tools(@@ -217,7 +226,6 @@ class TestToolExecution:tools._execute_tool(slug="GITHUB_GET_REPOS",arguments={"owner": "test", "repo": "test"},- toolkit_versions=toolkit_versions,)# Verify that the client was called with the global version@@ -225,7 +233,7 @@ class TestToolExecution:call_args = mock_client.tools.execute.call_args# Should have called with the global version string- assert call_args.kwargs["version"] == "v3.0.0"+ assert call_args.kwargs["version"] == "20251201_03"def test_tool_execution_matches_typescript_behavior(self):"""Test that Python execution matches TypeScript behavior exactly."""@@ -239,9 +247,9 @@ class TestToolExecution:# Create toolkit versions like TypeScript would havetoolkit_versions = {- "github": "20250906_01",+ "github": "20251201_01","slack": "latest",- "notion": "20250901_05",+ "notion": "20251201_05",}# Create Tools instance@@ -253,13 +261,23 @@ class TestToolExecution:# Test cases matching TypeScript behaviortest_cases = [- ("GITHUB_GET_REPOS", "github", "20250906_01"),- ("SLACK_SEND_MESSAGE", "slack", "latest"),- ("NOTION_CREATE_PAGE", "notion", "20250901_05"),- ("CUSTOM_TOOL", "unknown_toolkit", "latest"), # Unknown toolkit fallback+ ("GITHUB_GET_REPOS", "github", "20251201_01", False),+ (+ "SLACK_SEND_MESSAGE",+ "slack",+ "latest",+ True,+ ), # Need skip flag for latest+ ("NOTION_CREATE_PAGE", "notion", "20251201_05", False),+ (+ "CUSTOM_TOOL",+ "unknown_toolkit",+ "latest",+ True,+ ), # Unknown toolkit fallback to latest]- for tool_slug, toolkit_slug, expected_version in test_cases:+ for tool_slug, toolkit_slug, expected_version, needs_skip in test_cases:# Create mock toolmock_tool = self.create_mock_tool(tool_slug, toolkit_slug)@@ -277,11 +295,17 @@ class TestToolExecution:mock_client.tools.execute.return_value = mock_execute_response# Execute the tool- tools._execute_tool(- slug=tool_slug,- arguments={"test": "data"},- toolkit_versions=toolkit_versions,- )+ if needs_skip:+ tools._execute_tool(+ slug=tool_slug,+ arguments={"test": "data"},+ dangerously_skip_version_check=True,+ )+ else:+ tools._execute_tool(+ slug=tool_slug,+ arguments={"test": "data"},+ )# Verify the version matches expectedcall_args = mock_client.tools.execute.call_args@@ -291,3 +315,669 @@ class TestToolExecution:# Reset mock for next iterationmock_client.tools.execute.reset_mock()++ def test_execute_raises_error_when_version_is_latest_without_skip_flag(self):+ """Test that execute raises ToolVersionRequiredError when version is 'latest' without skip flag."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance without toolkit versions (defaults to latest)+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ )++ # Create a mock GitHub tool with proper input_parameters for file helper+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")+ github_tool.input_parameters = {"type": "object", "properties": {}}++ # Mock the retrieve method+ mock_client.tools.retrieve.return_value = github_tool++ # Execute should raise ToolVersionRequiredError since version will be 'latest'+ with pytest.raises(ToolVersionRequiredError) as exc_info:+ tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ )++ assert "Toolkit version not specified" in str(exc_info.value)++ def test_execute_allows_latest_with_dangerously_skip_version_check(self):+ """Test that execute allows 'latest' version when dangerously_skip_version_check is True."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance without toolkit versions (defaults to latest)+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute should succeed with dangerously_skip_version_check=True+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ dangerously_skip_version_check=True,+ )++ # Verify execution succeeded+ assert result["successful"] is True+ assert result["data"] == {"result": "success"}++ # Verify the client was called with version="latest"+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["version"] == "latest"++ def test_execute_with_specific_version_no_error(self):+ """Test that execute works with specific version without raising error."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance without toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute with specific version should succeed+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ version="20251201_01",+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with the specific version+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["version"] == "20251201_01"++ def test_execute_uses_instance_toolkit_versions(self):+ """Test that execute method uses instance-level toolkit versions."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create toolkit versions configuration+ toolkit_versions = {"github": "20251201_01", "slack": "20251201_02"}++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions=toolkit_versions,+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute should use the configured toolkit version+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with the configured version+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["version"] == "20251201_01"++ def test_execute_version_parameter_overrides_toolkit_versions(self):+ """Test that explicit version parameter overrides instance toolkit versions."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create toolkit versions configuration+ toolkit_versions = {"github": "20251201_01"}++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions=toolkit_versions,+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute with explicit version should override instance version+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ version="20251201_03", # Explicit version+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with the explicit version, not instance version+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["version"] == "20251201_03"++ def test_execute_with_connected_account_id(self):+ """Test that execute passes connected_account_id correctly."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute with connected_account_id+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ connected_account_id="test-account-123",+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with the connected_account_id+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["connected_account_id"] == "test-account-123"++ def test_execute_with_custom_auth_params(self):+ """Test that execute passes custom_auth_params correctly."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute with custom_auth_params+ custom_auth = {"api_key": "test-key"}+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ custom_auth_params=custom_auth,+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with the custom_auth_params+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["custom_auth_params"] == custom_auth++ def test_execute_with_user_id_and_text(self):+ """Test that execute passes user_id and text parameters correctly."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute with user_id and text+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ user_id="user-123",+ text="Additional context",+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with user_id and text+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["user_id"] == "user-123"+ assert call_args.kwargs["text"] == "Additional context"++ def test_execute_custom_tool(self):+ """Test that execute works with custom tools."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"custom": "20251201_01"},+ )++ # Create a mock custom tool with proper structure+ custom_tool_info = self.create_mock_tool("CUSTOM_TOOL", "custom")+ custom_tool_info.input_parameters = {"type": "object", "properties": {}}++ # Mock the custom tool registry+ mock_custom_tool = Mock()+ mock_custom_tool.info = custom_tool_info+ tools._custom_tools.custom_tools_registry = {"CUSTOM_TOOL": mock_custom_tool}++ # Mock the get method to return the tool+ def mock_get(slug):+ return mock_custom_tool if slug == "CUSTOM_TOOL" else None++ tools._custom_tools.get = Mock(side_effect=mock_get)++ # Mock the execute method of custom tool+ def mock_execute(slug, request, user_id):+ return {"custom_result": "success"}++ tools._custom_tools.execute = Mock(side_effect=mock_execute)++ # Execute the custom tool+ result = tools.execute(+ slug="CUSTOM_TOOL",+ arguments={"param": "value"},+ user_id="user-123",+ )++ # Verify execution succeeded+ assert result["successful"] is True+ assert result["data"]["custom_result"] == "success"++ # Verify custom tool execute was called+ tools._custom_tools.execute.assert_called_once_with(+ slug="CUSTOM_TOOL",+ request={"param": "value"},+ user_id="user-123",+ )++ def test_execute_with_modifiers_before_execute(self):+ """Test that execute applies before_execute modifiers correctly."""+ from composio.core.models._modifiers import before_execute++ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Create a before_execute modifier that changes the arguments+ def modify_arguments(tool, toolkit, params):+ params["arguments"]["owner"] = "modified-owner"+ return params++ modifier = before_execute(modify_arguments)++ # Execute with modifier+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ modifiers=[modifier],+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with modified arguments+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["arguments"]["owner"] == "modified-owner"++ def test_execute_with_modifiers_after_execute(self):+ """Test that execute applies after_execute modifiers correctly."""+ from composio.core.models._modifiers import after_execute++ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Create an after_execute modifier that modifies the response+ def modify_response(tool, toolkit, response):+ response["data"]["modified"] = True+ return response++ modifier = after_execute(modify_response)++ # Execute with modifier+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ modifiers=[modifier],+ )++ # Verify execution succeeded and response was modified+ assert result["successful"] is True+ assert result["data"]["modified"] is True++ def test_execute_with_environment_variable_toolkit_version(self):+ """Test that execute uses environment variable for toolkit version."""+ import os++ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Set environment variable for github toolkit version+ os.environ["COMPOSIO_TOOLKIT_VERSION_GITHUB"] = "20251201_08"++ try:+ # Create Tools instance with explicit toolkit versions that match the env var+ # This simulates what happens when get_toolkit_version reads the env var+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_08"}, # This matches the env var+ )++ # Create a mock GitHub tool with proper structure+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")+ github_tool.input_parameters = {"type": "object", "properties": {}}++ # Mock the retrieve method+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute should use the environment variable version+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with the env variable version+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["version"] == "20251201_08"+ finally:+ # Clean up environment variable+ if "COMPOSIO_TOOLKIT_VERSION_GITHUB" in os.environ:+ del os.environ["COMPOSIO_TOOLKIT_VERSION_GITHUB"]++ def test_execute_raises_error_with_latest_via_env_variable(self):+ """Test that execute raises error when env variable sets version to 'latest'."""+ import os++ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Set environment variable for github toolkit version to 'latest'+ os.environ["COMPOSIO_TOOLKIT_VERSION_GITHUB"] = "latest"++ try:+ # Create Tools instance without explicit toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ )++ # Create a mock GitHub tool with proper structure+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")+ github_tool.input_parameters = {"type": "object", "properties": {}}++ # Mock the retrieve method+ mock_client.tools.retrieve.return_value = github_tool++ # Execute should raise ToolVersionRequiredError since version is 'latest'+ with pytest.raises(ToolVersionRequiredError):+ tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ )+ finally:+ # Clean up environment variable+ if "COMPOSIO_TOOLKIT_VERSION_GITHUB" in os.environ:+ del os.environ["COMPOSIO_TOOLKIT_VERSION_GITHUB"]++ def test_execute_with_custom_connection_data(self):+ """Test that execute passes custom_connection_data correctly."""+ # Mock client and provider+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ # Create Tools instance with toolkit versions+ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ # Create a mock GitHub tool+ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ # Mock the get_raw_composio_tool_by_slug and retrieve methods+ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ # Mock the client's execute method+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ # Execute with custom_connection_data+ custom_connection = {"token": "custom-token"}+ result = tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "test", "repo": "test"},+ custom_connection_data=custom_connection,+ )++ # Verify execution succeeded+ assert result["successful"] is True++ # Verify the client was called with custom_connection_data+ mock_client.tools.execute.assert_called_once()+ call_args = mock_client.tools.execute.call_args+ assert call_args.kwargs["custom_connection_data"] == custom_connectiondiff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.tsindex bc89b69f9..1dc9f7220 100644--- a/ts/packages/core/src/composio.ts+++ b/ts/packages/core/src/composio.ts@@ -76,12 +76,40 @@ export type ComposioConfig<*/disableVersionCheck?: boolean;/**- * The versions of the toolkits to fetch.- * Defaults to latest is nothing is provided.- * Alternatively you can specify individual toolkit versions in the env `COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00`- * @example- * { 'github': 'latest', 'slack': '20250902_00' }- * 'latest'+ * The versions of the toolkits to use for tool execution and retrieval.+ *+ * **Version Control:**+ * When executing tools manually (via `tools.execute()`), if this resolves to "latest",+ * you must either:+ * - Set `dangerouslySkipVersionCheck: true` in the execute params (not recommended for production)+ * - Specify a concrete version here or in environment variables+ * - Pass a specific `version` parameter to the execute call+ *+ * Defaults to 'latest' if nothing is provided.+ * You can specify individual toolkit versions via environment variables: `COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00`+ *+ * @example Global version for all toolkits+ * ```typescript+ * const composio = new Composio({ toolkitVersions: 'latest' });+ * ```+ *+ * @example Specific versions for different toolkits (recommended for production)+ * ```typescript+ * const composio = new Composio({+ * toolkitVersions: {+ * github: '20250909_00',+ * slack: '20250902_00'+ * }+ * });+ * ```+ *+ * @example Set via environment variables+ * ```typescript+ * // Set environment variables:+ * // COMPOSIO_TOOLKIT_VERSION_GITHUB=20250909_00+ * // COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00+ * const composio = new Composio(); // Will use env variables+ * ```*/toolkitVersions?: ToolkitVersionParam;};diff --git a/ts/packages/core/src/errors/ToolErrors.ts b/ts/packages/core/src/errors/ToolErrors.tsindex 8700bf48b..e550fae52 100644--- a/ts/packages/core/src/errors/ToolErrors.ts+++ b/ts/packages/core/src/errors/ToolErrors.ts@@ -10,6 +10,7 @@ export const ToolErrorCodes = {TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',GLOBAL_EXECUTE_TOOL_FN_NOT_SET: 'GLOBAL_EXECUTE_TOOL_FN_NOT_SET',+ TOOL_VERSION_REQUIRED: 'TOOL_VERSION_REQUIRED',} as const;export class ComposioProviderNotDefinedError extends ComposioError {@@ -124,6 +125,86 @@ export class ComposioGlobalExecuteToolFnNotSetError extends ComposioError {}}+/**+ * Error thrown when toolkit version is not specified for manual tool execution.+ *+ * This error is thrown when attempting to execute a tool manually (via `tools.execute()`)+ * and the resolved version is "latest" without `dangerouslySkipVersionCheck` set to true.+ *+ * **Why this error exists:**+ * Using "latest" version in manual execution can lead to unexpected behavior when new+ * toolkit versions are released, potentially breaking your application. For production+ * use, it's recommended to pin specific toolkit versions.+ *+ * **How to fix:**+ * 1. Specify a concrete version in the execute call+ * 2. Configure toolkit versions at SDK initialization+ * 3. Set toolkit version via environment variable+ * 4. Use dangerouslySkipVersionCheck (not recommended for production)+ *+ * @example ❌ This will throw ComposioToolVersionRequiredError if toolkitVersions is 'latest'+ * ```typescript+ * await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * arguments: { owner: 'composio' }+ * });+ * ```+ *+ * @example ✅ Fix 1: Pass specific version in execute call+ * ```typescript+ * await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * version: '20250909_00',+ * arguments: { owner: 'composio' }+ * });+ * ```+ *+ * @example ✅ Fix 2: Configure toolkit versions at SDK level+ * ```typescript+ * const composio = new Composio({+ * toolkitVersions: { github: '20250909_00' }+ * });+ * await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * arguments: { owner: 'composio' }+ * });+ * ```+ *+ * @example ✅ Fix 3: Use environment variable+ * ```typescript+ * // Set: COMPOSIO_TOOLKIT_VERSION_GITHUB=20250909_00+ * await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * arguments: { owner: 'composio' }+ * });+ * ```+ *+ * @example ⚠️ Fix 4: Skip version check (not recommended for production)+ * ```typescript+ * await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * dangerouslySkipVersionCheck: true,+ * arguments: { owner: 'composio' }+ * });+ * ```+ */+export class ComposioToolVersionRequiredError extends ComposioError {+ constructor(+ message: string = 'Toolkit version not specified. For manual execution of the tool please pass a specific toolkit version',+ options: Omit<ComposioErrorOptions, 'code'> = {}+ ) {+ super(message, {+ ...options,+ code: ToolErrorCodes.TOOL_VERSION_REQUIRED,+ possibleFixes: options.possibleFixes || [+ 'Pass the toolkit version as a parameter to the execute function ("latest" is not supported in manual execution)',+ 'Set the toolkit versions in the Composio config (toolkitVersions: { <toolkit-slug>: "<toolkit-version>" })',+ 'Set the toolkit version in the environment variable (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_SLUG>)',+ 'Set dangerouslySkipVersionCheck to true (this might cause unexpected behavior when new versions of the tools are released)',+ ],+ });+ }+}export interface ComposioAPIServerErrorBody {error: {message: string;diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.tsindex 3648a2a50..7786dca7b 100644--- a/ts/packages/core/src/models/Tools.ts+++ b/ts/packages/core/src/models/Tools.ts@@ -42,6 +42,7 @@ import {ComposioInvalidModifierError,ComposioToolNotFoundError,ComposioProviderNotDefinedError,+ ComposioToolVersionRequiredError,} from '../errors/ToolErrors';import { ValidationError } from '../errors/ValidationErrors';import { telemetry } from '../telemetry/Telemetry';@@ -599,6 +600,9 @@ export class Tools<{userId,arguments: input,+ // dangerously skip version check for agentic and non agentic tool execution via providers+ // this can be safe because most agentic flows users fetch latest version and then execute the tool+ dangerouslySkipVersionCheck: true,},modifiers);@@ -617,6 +621,12 @@ export class Tools<tool: Tool,body: ToolExecuteParams): Promise<ToolExecuteResponse> {+ const toolkitVersion =+ body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions);+ // if the version is latest and dangerouslySkipVersionCheck is not true, throw an error+ if (toolkitVersion === 'latest' && !body.dangerouslySkipVersionCheck) {+ throw new ComposioToolVersionRequiredError();+ }try {const result = await this.client.tools.execute(tool.slug, {allow_tracing: body.allowTracing,@@ -625,8 +635,7 @@ export class Tools<custom_connection_data: body.customConnectionData,arguments: body.arguments,user_id: body.userId,- version:- body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions),+ version: toolkitVersion,text: body.text,});// transform the response to the ToolExecuteResponse format@@ -643,34 +652,68 @@ export class Tools<* This method calls the Composio API or a custom tool handler to execute the tool and returns the response.* It automatically determines whether to use a custom tool or a Composio API tool based on the slug.*+ * **Version Control:**+ * By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest",+ * the execution will throw a `ComposioToolVersionRequiredError` unless `dangerouslySkipVersionCheck` is set to `true`.+ * This helps prevent unexpected behavior when new toolkit versions are released.+ ** @param {string} slug - The slug/ID of the tool to be executed* @param {ToolExecuteParams} body - The parameters to be passed to the tool+ * @param {string} [body.version] - The specific version of the tool to execute (e.g., "20250909_00")+ * @param {boolean} [body.dangerouslySkipVersionCheck] - Skip version validation for "latest" version (use with caution)+ * @param {string} [body.userId] - The user ID to execute the tool for+ * @param {string} [body.connectedAccountId] - The connected account ID to use for authenticated tools+ * @param {Record<string, unknown>} [body.arguments] - The arguments to pass to the tool* @param {ExecuteToolModifiers} [modifiers] - Optional modifiers to transform the request or response* @returns {Promise<ToolExecuteResponse>} - The response from the tool execution** @throws {ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account is not found* @throws {ComposioToolNotFoundError} If the tool with the given slug is not found+ * @throws {ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true* @throws {ComposioToolExecutionError} If there is an error during tool execution*- * @example+ * @example Execute with a specific version (recommended for production)+ * ```typescript+ * const result = await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * version: '20250909_00',+ * arguments: { owner: 'composio' }+ * });+ * ```+ *+ * @example Execute with dangerouslySkipVersionCheck (not recommended for production)* ```typescript- * // Execute a Composio API tool* const result = await composio.tools.execute('HACKERNEWS_GET_USER', {* userId: 'default',- * arguments: { userId: 'pg' }+ * arguments: { userId: 'pg' },+ * dangerouslySkipVersionCheck: true // Allows execution with "latest" version* });+ * ```*- * // Execute with modifiers+ * @example Execute with SDK-level toolkit versions configuration+ * ```typescript+ * // If toolkitVersions are set during Composio initialization, no need to pass version+ * const composio = new Composio({ toolkitVersions: { github: '20250909_00' } });+ * const result = await composio.tools.execute('GITHUB_GET_REPOS', {+ * userId: 'default',+ * arguments: { owner: 'composio' }+ * });+ * ```+ *+ * @example Execute with modifiers+ * ```typescript* const result = await composio.tools.execute('GITHUB_GET_ISSUES', {* userId: 'default',+ * version: '20250909_00',* arguments: { owner: 'composio', repo: 'sdk' }* }, {- * beforeExecute: (toolSlug, toolkitSlug, params) => {- * // Modify params before execution+ * beforeExecute: ({ toolSlug, toolkitSlug, params }) => {+ * console.log(`Executing ${toolSlug} from ${toolkitSlug}`);* return params;* },- * afterExecute: (toolSlug, toolkitSlug, result) => {- * // Transform result after execution+ * afterExecute: ({ toolSlug, toolkitSlug, result }) => {+ * console.log(`Completed ${toolSlug}`);* return result;* }* });diff --git a/ts/packages/core/src/types/tool.types.ts b/ts/packages/core/src/types/tool.types.tsindex e3b2b6414..2f47ce2df 100644--- a/ts/packages/core/src/types/tool.types.ts+++ b/ts/packages/core/src/types/tool.types.ts@@ -257,7 +257,40 @@ export const CustomAuthParamsSchema = z.object({export type CustomAuthParams = z.infer<typeof CustomAuthParamsSchema>;/**- * ToolExecuteParams is the parameters for the tool execution.+ * Parameters for tool execution.+ *+ * @property {boolean} [allowTracing] - Enable tracing for this tool execution+ * @property {string} [connectedAccountId] - The connected account ID to use for authenticated tools+ * @property {CustomAuthParams} [customAuthParams] - Custom authentication parameters+ * @property {CustomConnectionData} [customConnectionData] - Custom connection data (takes priority over customAuthParams)+ * @property {Record<string, unknown>} [arguments] - The arguments to pass to the tool+ * @property {string} [userId] - The user ID to execute the tool for (required for no-auth apps)+ * @property {string} [version] - The specific version of the tool to execute (e.g., "20250909_00" or "latest")+ * @property {boolean} [dangerouslySkipVersionCheck] - Skip version validation when using "latest" version.+ * **Warning:** This may cause unexpected behavior when new toolkit versions are released.+ * Only use this if you understand the risks. Recommended alternatives:+ * - Specify a concrete version in the `version` parameter+ * - Configure toolkit versions at SDK initialization level+ * - Set toolkit version via environment variable (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_SLUG>)+ * @property {string} [text] - Additional text input for the tool+ *+ * @example Recommended: Execute with a specific version+ * ```typescript+ * const params: ToolExecuteParams = {+ * userId: 'default',+ * version: '20250909_00',+ * arguments: { owner: 'composio', repo: 'sdk' }+ * };+ * ```+ *+ * @example With dangerouslySkipVersionCheck (use with caution)+ * ```typescript+ * const params: ToolExecuteParams = {+ * userId: 'default',+ * dangerouslySkipVersionCheck: true,+ * arguments: { userId: 'pg' }+ * };+ * ```*/export const ToolExecuteParamsSchema = z.object({allowTracing: z.boolean().optional(),@@ -265,8 +298,9 @@ export const ToolExecuteParamsSchema = z.object({customAuthParams: CustomAuthParamsSchema.optional(),customConnectionData: CustomConnectionDataSchema.optional(),arguments: z.record(z.string(), z.unknown()).optional(),- userId: z.string().optional(), // we have no auth apps which can be execute+ userId: z.string().optional(),version: z.union([z.literal('latest'), z.string()]).optional(),+ dangerouslySkipVersionCheck: z.boolean().optional(),text: z.string().optional(),});export type ToolExecuteParams = z.infer<typeof ToolExecuteParamsSchema>;diff --git a/ts/packages/core/test/tools/fileModifiers.test.ts b/ts/packages/core/test/tools/fileModifiers.test.tsindex c8e9f04ca..c9e3de815 100644--- a/ts/packages/core/test/tools/fileModifiers.test.ts+++ b/ts/packages/core/test/tools/fileModifiers.test.ts@@ -37,8 +37,8 @@ describe('FileToolModifier', () => {name: 'Test Tool',description: 'A test tool',tags: ['test'],- version: '20250902_00',- availableVersions: ['20250902_00'],+ version: '20251201_01',+ availableVersions: ['20251201_01'],};const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);@@ -51,8 +51,8 @@ describe('FileToolModifier', () => {name: 'Test Tool',description: 'A test tool',tags: ['test'],- version: '20250902_00',- availableVersions: ['20250902_00'],+ version: '20251201_01',+ availableVersions: ['20251201_01'],inputParameters: {type: 'object',properties: {@@ -91,8 +91,8 @@ describe('FileToolModifier', () => {},},},- version: '20250902_00',- availableVersions: ['20250902_00'],+ version: '20251201_01',+ availableVersions: ['20251201_01'],};it('should upload file for file_uploadable parameters', async () => {@@ -186,8 +186,8 @@ describe('FileToolModifier', () => {name: 'Test Tool',description: 'A test tool',tags: ['test'],- availableVersions: ['20250902_00'],- version: '20250902_00',+ availableVersions: ['20251201_01'],+ version: '20251201_01',};it('should download file from S3 URL', async () => {@@ -322,8 +322,8 @@ describe('Tools with autoUploadDownloadFiles', () => {},additionalProperties: false,},- version: '20250902_00',- availableVersions: ['20250902_00'],+ version: '20251201_01',+ availableVersions: ['20251201_01'],};const mockRawToolWithFileUpload = {@@ -362,8 +362,8 @@ describe('Tools with autoUploadDownloadFiles', () => {},additionalProperties: false,},- version: '20250902_00',- availableVersions: ['20250902_00'],+ version: '20251201_01',+ availableVersions: ['20251201_01'],};describe('when autoUploadDownloadFiles is false', () => {@@ -418,6 +418,7 @@ describe('Tools with autoUploadDownloadFiles', () => {file: '/path/to/file.txt',},userId: 'test-user',+ dangerouslySkipVersionCheck: true,});expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();@@ -472,6 +473,7 @@ describe('Tools with autoUploadDownloadFiles', () => {file: '/path/to/file.txt',},userId: 'test-user',+ dangerouslySkipVersionCheck: true,});expect(fileUtils.downloadFileFromS3).not.toHaveBeenCalled();diff --git a/ts/packages/core/test/tools/modifiers.test.ts b/ts/packages/core/test/tools/modifiers.test.tsindex 32f89962c..21caebc74 100644--- a/ts/packages/core/test/tools/modifiers.test.ts+++ b/ts/packages/core/test/tools/modifiers.test.ts@@ -74,6 +74,7 @@ describe('Tools Modifiers', () => {const body = {userId: 'test-user',arguments: { limit: 5 },+ dangerouslySkipVersionCheck: true,};const { beforeExecute } = createExecutionModifiers({@@ -103,7 +104,7 @@ describe('Tools Modifiers', () => {it('should apply afterExecute modifier after executing a tool', async () => {const slug = 'COMPOSIO_TOOL';- const body = { userId: 'test-user', arguments: {} };+ const body = { userId: 'test-user', arguments: {}, dangerouslySkipVersionCheck: true };const { afterExecute } = createExecutionModifiers({afterModifications: {diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.tsindex 902136b0d..e0880fd7f 100644--- a/ts/packages/core/test/tools/tools.test.ts+++ b/ts/packages/core/test/tools/tools.test.ts@@ -408,6 +408,7 @@ describe('Tools', () => {userId: 'test-user',connectedAccountId: undefined,arguments: { query: 'test' },+ dangerouslySkipVersionCheck: true,};await mockToolExecution(context.tools);@@ -433,6 +434,7 @@ describe('Tools', () => {userId: 'test-user',connectedAccountId: 'test-connected-account-id',arguments: { query: 'test' },+ dangerouslySkipVersionCheck: true,};await mockToolExecution(context.tools);@@ -741,7 +743,7 @@ describe('Tools', () => {it('should pass global version string when configured', async () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {- toolkitVersions: '20250902_00' as any,+ toolkitVersions: '20251201_03' as any,});mockClient.tools.list.mockResolvedValueOnce({@@ -753,7 +755,7 @@ describe('Tools', () => {expect(mockClient.tools.list).toHaveBeenCalledWith({toolkit_slug: 'github',- toolkit_versions: '20250902_00',+ toolkit_versions: '20251201_03',});});@@ -761,9 +763,9 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',- gmail: '20250901_01',+ gmail: '20251201_05',},});@@ -777,9 +779,9 @@ describe('Tools', () => {expect(mockClient.tools.list).toHaveBeenCalledWith({toolkit_slug: 'github',toolkit_versions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',- gmail: '20250901_01',+ gmail: '20251201_05',},});});@@ -788,7 +790,7 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',},});@@ -804,7 +806,7 @@ describe('Tools', () => {tool_slugs: 'GITHUB_CREATE_ISSUE,SLACK_SEND_MESSAGE',limit: 9999,toolkit_versions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',},});@@ -846,7 +848,7 @@ describe('Tools', () => {it('should pass global version when retrieving single tool', async () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {- toolkitVersions: '20250902_00' as any,+ toolkitVersions: '20251201_03' as any,});mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);@@ -854,7 +856,7 @@ describe('Tools', () => {await tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');expect(mockClient.tools.retrieve).toHaveBeenCalledWith('GITHUB_CREATE_ISSUE', {- toolkit_versions: '20250902_00',+ toolkit_versions: '20251201_03',});});@@ -862,9 +864,9 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',- gmail: '20250901_01',+ gmail: '20251201_05',},});@@ -874,9 +876,9 @@ describe('Tools', () => {expect(mockClient.tools.retrieve).toHaveBeenCalledWith('SLACK_SEND_MESSAGE', {toolkit_versions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',- gmail: '20250901_01',+ gmail: '20251201_05',},});});@@ -890,6 +892,7 @@ describe('Tools', () => {const executeParams: ToolExecuteParams = {arguments: { title: 'Test Issue' },connectedAccountId: 'test-account',+ dangerouslySkipVersionCheck: true, // Required when using 'latest' in manual execution};await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);@@ -909,7 +912,7 @@ describe('Tools', () => {it('should use global version when configured', async () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {- toolkitVersions: '20250902_00' as any,+ toolkitVersions: '20251201_03' as any,});const spies = await mockToolExecution(tools);@@ -927,7 +930,7 @@ describe('Tools', () => {custom_connection_data: undefined,arguments: { title: 'Test Issue' },user_id: undefined,- version: '20250902_00', // should use global version+ version: '20251201_03', // should use global versiontext: undefined,});});@@ -936,9 +939,9 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- 'test-toolkit': '20250902_00', // Use the actual toolkit slug from mock+ 'test-toolkit': '20251201_01', // Use the actual toolkit slug from mockslack: 'latest',- gmail: '20250901_01',+ gmail: '20251201_05',},});@@ -967,7 +970,7 @@ describe('Tools', () => {custom_connection_data: undefined,arguments: { title: 'Test Issue' },user_id: undefined,- version: '20250902_00', // should use test-toolkit-specific version+ version: '20251201_01', // should use test-toolkit-specific versiontext: undefined,});});@@ -976,7 +979,7 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',},});@@ -993,6 +996,7 @@ describe('Tools', () => {const executeParams: ToolExecuteParams = {arguments: { title: 'Test Page' },connectedAccountId: 'test-account',+ dangerouslySkipVersionCheck: true, // Required when fallback is 'latest'};await tools.execute('NOTION_CREATE_PAGE', executeParams);@@ -1013,7 +1017,7 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250902_00',+ github: '20251201_01',slack: 'latest',},});@@ -1023,7 +1027,7 @@ describe('Tools', () => {const executeParams: ToolExecuteParams = {arguments: { title: 'Test Issue' },connectedAccountId: 'test-account',- version: '20250903_00', // explicit version should override config+ version: '20251201_03', // explicit version should override config};await tools.execute('GITHUB_CREATE_ISSUE', executeParams);@@ -1035,7 +1039,7 @@ describe('Tools', () => {custom_connection_data: undefined,arguments: { title: 'Test Issue' },user_id: undefined,- version: '20250903_00', // explicit version takes precedence+ version: '20251201_03', // explicit version takes precedencetext: undefined,});});@@ -1044,7 +1048,7 @@ describe('Tools', () => {const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250902_00',+ github: '20251201_01',},});@@ -1062,6 +1066,7 @@ describe('Tools', () => {const executeParams: ToolExecuteParams = {arguments: { query: 'test' },connectedAccountId: 'test-account',+ dangerouslySkipVersionCheck: true, // Required when toolkit is undefined and version is 'latest'};await tools.execute('SOME_CUSTOM_TOOL', executeParams);@@ -1092,14 +1097,14 @@ describe('Tools', () => {it('should use environment variable versions when no user config provided', async () => {// Set environment variables- process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20250903_00';+ process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20251201_08';process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';const mockProvider = new MockProvider();// Pass the processed environment variables to the Tools constructorconst tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250903_00',+ github: '20251201_08',slack: 'latest',},});@@ -1114,7 +1119,7 @@ describe('Tools', () => {expect(mockClient.tools.list).toHaveBeenCalledWith({toolkit_slug: 'github',toolkit_versions: {- github: '20250903_00',+ github: '20251201_08',slack: 'latest',},});@@ -1122,14 +1127,14 @@ describe('Tools', () => {it('should prioritize user config over environment variables', async () => {// Set environment variables- process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20250903_00';+ process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20251201_08';process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {toolkitVersions: {- github: '20250904_00', // should override env- gmail: '20250902_00', // new toolkit not in env+ github: '20251201_04', // should override env+ gmail: '20251201_05', // new toolkit not in env},});@@ -1143,20 +1148,20 @@ describe('Tools', () => {expect(mockClient.tools.list).toHaveBeenCalledWith({toolkit_slug: 'github',toolkit_versions: {- github: '20250904_00', // user config wins- gmail: '20250902_00', // from user config+ github: '20251201_04', // user config wins+ gmail: '20251201_05', // from user config},});});it('should use global version string to override everything', async () => {// Set environment variables- process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20250903_00';+ process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20251201_08';process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';const mockProvider = new MockProvider();const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {- toolkitVersions: '20250905_00' as any, // global version overrides everything+ toolkitVersions: '20251201_09' as any, // global version overrides everything});mockClient.tools.list.mockResolvedValueOnce({@@ -1168,7 +1173,246 @@ describe('Tools', () => {expect(mockClient.tools.list).toHaveBeenCalledWith({toolkit_slug: 'github',- toolkit_versions: '20250905_00', // global version ignores env vars+ toolkit_versions: '20251201_09', // global version ignores env vars+ });+ });+ });++ describe('version check safety for manual execution', () => {+ it('should throw ComposioToolVersionRequiredError when version is "latest" without dangerouslySkipVersionCheck', async () => {+ const context = createTestContext();+ const spies = await mockToolExecution(context.tools);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ // dangerouslySkipVersionCheck is not set, should default to false+ };++ await expect(context.tools.execute('GITHUB_CREATE_ISSUE', executeParams)).rejects.toThrow(+ 'Toolkit version not specified. For manual execution of the tool please pass a specific toolkit version'+ );+ });++ it('should throw ComposioToolVersionRequiredError when version is "latest" with dangerouslySkipVersionCheck set to false', async () => {+ const context = createTestContext();+ const spies = await mockToolExecution(context.tools);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ dangerouslySkipVersionCheck: false,+ };++ await expect(context.tools.execute('GITHUB_CREATE_ISSUE', executeParams)).rejects.toThrow(+ 'Toolkit version not specified. For manual execution of the tool please pass a specific toolkit version'+ );+ });++ it('should succeed when version is "latest" with dangerouslySkipVersionCheck set to true', async () => {+ const context = createTestContext();+ const spies = await mockToolExecution(context.tools);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ dangerouslySkipVersionCheck: true,+ };++ const result = await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);++ expect(result).toEqual(toolMocks.toolExecuteResponse);+ expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {+ allow_tracing: undefined,+ connected_account_id: 'test-account',+ custom_auth_params: undefined,+ custom_connection_data: undefined,+ arguments: { title: 'Test Issue' },+ user_id: undefined,+ version: 'latest',+ text: undefined,+ });+ });++ it('should succeed when executing with a specific version (not "latest") without dangerouslySkipVersionCheck', async () => {+ const mockProvider = new MockProvider();+ const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {+ toolkitVersions: {+ 'test-toolkit': '20251201_01',+ },+ });++ const testTool = {+ ...toolMocks.transformedTool,+ toolkit: { slug: 'test-toolkit', name: 'Test Toolkit' },+ };++ const spies = await mockToolExecution(tools);+ spies.getRawComposioToolBySlugSpy.mockReset();+ spies.getRawComposioToolBySlugSpy.mockResolvedValueOnce(testTool as unknown as Tool);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ // No dangerouslySkipVersionCheck needed when version is specific+ };++ const result = await tools.execute('GITHUB_CREATE_ISSUE', executeParams);++ expect(result).toEqual(toolMocks.toolExecuteResponse);+ expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {+ allow_tracing: undefined,+ connected_account_id: 'test-account',+ custom_auth_params: undefined,+ custom_connection_data: undefined,+ arguments: { title: 'Test Issue' },+ user_id: undefined,+ version: '20251201_01', // specific version should work without skip flag+ text: undefined,+ });+ });++ it('should succeed when explicit version parameter overrides "latest" config', async () => {+ const context = createTestContext();+ const spies = await mockToolExecution(context.tools);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ version: '20251201_03', // explicit version overrides default "latest"+ // No dangerouslySkipVersionCheck needed+ };++ const result = await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);++ expect(result).toEqual(toolMocks.toolExecuteResponse);+ expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {+ allow_tracing: undefined,+ connected_account_id: 'test-account',+ custom_auth_params: undefined,+ custom_connection_data: undefined,+ arguments: { title: 'Test Issue' },+ user_id: undefined,+ version: '20251201_03',+ text: undefined,+ });+ });++ it('should throw error when explicit version parameter is "latest" without dangerouslySkipVersionCheck', async () => {+ const mockProvider = new MockProvider();+ const tools = new Tools(mockClient as unknown as ComposioClient, mockProvider, {+ toolkitVersions: {+ 'test-toolkit': '20251201_01', // specific version in config+ },+ });++ const testTool = {+ ...toolMocks.transformedTool,+ toolkit: { slug: 'test-toolkit', name: 'Test Toolkit' },+ };++ const spies = await mockToolExecution(tools);+ spies.getRawComposioToolBySlugSpy.mockReset();+ spies.getRawComposioToolBySlugSpy.mockResolvedValueOnce(testTool as unknown as Tool);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ version: 'latest', // explicit "latest" should still require skip flag+ };++ await expect(tools.execute('GITHUB_CREATE_ISSUE', executeParams)).rejects.toThrow(+ 'Toolkit version not specified. For manual execution of the tool please pass a specific toolkit version'+ );+ });++ it('should contain appropriate error properties and possible fixes in the cause', async () => {+ const context = createTestContext();+ const spies = await mockToolExecution(context.tools);++ const executeParams: ToolExecuteParams = {+ arguments: { title: 'Test Issue' },+ connectedAccountId: 'test-account',+ };++ try {+ await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);+ expect.fail('Should have thrown an error');+ } catch (error: any) {+ // The error should be wrapped in ComposioToolExecutionError+ expect(error).toBeDefined();++ // Check if the error has the right properties, whether wrapped or not+ if (error.cause) {+ // If wrapped, check the cause+ expect(error.cause.code).toContain('TOOL_VERSION_REQUIRED');+ expect(error.cause.message).toContain('Toolkit version not specified');+ expect(error.cause.possibleFixes).toBeDefined();+ expect(error.cause.possibleFixes).toContain(+ 'Pass the toolkit version as a parameter to the execute function ("latest" is not supported in manual execution)'+ );+ } else {+ // If not wrapped (direct error), check the error itself+ expect(error.code).toContain('TOOL_VERSION_REQUIRED');+ expect(error.message).toContain('Toolkit version not specified');+ expect(error.possibleFixes).toBeDefined();+ expect(error.possibleFixes).toContain(+ 'Pass the toolkit version as a parameter to the execute function ("latest" is not supported in manual execution)'+ );+ expect(error.possibleFixes).toContain(+ 'Set the toolkit versions in the Composio config (toolkitVersions: { <toolkit-slug>: "<toolkit-version>" })'+ );+ expect(error.possibleFixes).toContain(+ 'Set the toolkit version in the environment variable (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_SLUG>)'+ );+ expect(error.possibleFixes).toContain(+ 'Set dangerouslySkipVersionCheck to true (this might cause unexpected behavior when new versions of the tools are released)'+ );+ }+ }+ });++ it('should allow agentic provider execution with dangerouslySkipVersionCheck in createExecuteToolFn', async () => {+ const context = createTestContext();+ const userId = 'test-user';++ // Mock tool retrieval for the get method+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(+ toolMocks.transformedTool as unknown as Tool+ );++ // Mock provider wrapping+ context.mockProvider.wrapTools.mockImplementation((tools, executeToolFn) => {+ // Store the execute function so we can test it+ (context as any).storedExecuteToolFn = executeToolFn;+ return 'wrapped-tools-collection';+ });++ // Get the tool (this will internally create the execute tool function)+ await context.tools.get(userId, 'GITHUB_CREATE_ISSUE');++ // Now call the stored execute function (simulating agentic provider calling it)+ const storedExecuteToolFn = (context as any).storedExecuteToolFn;+ expect(storedExecuteToolFn).toBeDefined();++ // Setup mocks for the actual execution+ const spies = await mockToolExecution(context.tools);++ // Call the execute function that was passed to the provider+ // This should succeed because createExecuteToolFn sets dangerouslySkipVersionCheck: true+ const result = await storedExecuteToolFn('GITHUB_CREATE_ISSUE', { title: 'Test Issue' });++ expect(result).toEqual(toolMocks.toolExecuteResponse);+ expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {+ allow_tracing: undefined,+ connected_account_id: undefined,+ custom_auth_params: undefined,+ custom_connection_data: undefined,+ arguments: { title: 'Test Issue' },+ user_id: userId,+ version: 'latest',+ text: undefined,});});});diff --git a/ts/packages/core/test/utils/mocks/provider.mock.ts b/ts/packages/core/test/utils/mocks/provider.mock.tsindex f5295e770..740049d6a 100644--- a/ts/packages/core/test/utils/mocks/provider.mock.ts+++ b/ts/packages/core/test/utils/mocks/provider.mock.ts@@ -1,7 +1,7 @@import { vi } from 'vitest';import { BaseAgenticProvider } from '../../../src/provider/BaseProvider';-export class MockProvider extends BaseAgenticProvider<unknown, unknown> {+export class MockProvider extends BaseAgenticProvider<unknown, unknown, unknown> {readonly name = 'MockProvider';wrapTool = vi.fn();