Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Fix gemini provider (#1998)

Karan Vaidya1164158e36d8
diff --git a/python/composio/core/models/mcp.py b/python/composio/core/models/mcp.py
index 75b9b0b8e..67364cf66 100644
--- a/python/composio/core/models/mcp.py
+++ b/python/composio/core/models/mcp.py
@@ -9,15 +9,14 @@ from __future__ import annotations
import typing as t
import typing_extensions as te
-
from composio_client import omit
from composio_client.types.mcp.custom_create_response import CustomCreateResponse
+
from composio.client import HttpClient
from composio.core.models.base import Resource
from composio.core.types import MCPToolkitConfig
from composio.exceptions import ValidationError
-
# Data Types (matching TypeScript specification)
diff --git a/python/composio/core/models/tool_router.py b/python/composio/core/models/tool_router.py
index f534edf23..0f807e392 100644
--- a/python/composio/core/models/tool_router.py
+++ b/python/composio/core/models/tool_router.py
@@ -16,7 +16,6 @@ from composio.core.models.base import Resource
from composio.core.types import MCPToolkitConfig
from composio.exceptions import ValidationError
-
# Data Types
diff --git a/python/examples/mcp.py b/python/examples/mcp.py
index 9052ddc65..5b0c26409 100644
--- a/python/examples/mcp.py
+++ b/python/examples/mcp.py
@@ -1,8 +1,10 @@
import asyncio
-from composio import Composio
+
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
+from composio import Composio
+
composio = Composio()
mcp_config = composio.mcp.create(
@@ -10,7 +12,7 @@ mcp_config = composio.mcp.create(
toolkits=[{"toolkit": "slack", "auth_config_id": "<auth-config-id>"}],
)
-mcp_server = mcp_config.generate(user_id='<user-id>')
+mcp_server = mcp_config.generate(user_id="<user-id>")
client = MultiServerMCPClient(
{
@@ -21,11 +23,12 @@ client = MultiServerMCPClient(
}
)
+
async def langchain_mcp(message: str):
tools = await client.get_tools()
agent = create_react_agent("openai:gpt-4.1", tools)
response = await agent.ainvoke({"messages": message})
return response
-mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))
+mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))
diff --git a/python/providers/gemini/composio_gemini/provider.py b/python/providers/gemini/composio_gemini/provider.py
index ad4c2bdb6..6f715b4c5 100644
--- a/python/providers/gemini/composio_gemini/provider.py
+++ b/python/providers/gemini/composio_gemini/provider.py
@@ -1,62 +1,271 @@
-import types
+"""Gemini provider for Composio SDK."""
+
import typing as t
-from inspect import Signature
from composio.client.types import Tool
from composio.core.provider import AgenticProvider
from composio.core.provider.agentic import AgenticProviderExecuteFn
-from composio.utils.openapi import function_signature_from_jsonschema
+# Try to import Google GenAI types
+try:
+ from google.genai import types as genai_types
+
+ HAS_GENAI = True
+except ImportError:
+ genai_types = None # type: ignore
+ HAS_GENAI = False
+
+
+class GeminiTool:
+ """
+ Enhanced Gemini Tool wrapper that handles automatic function execution.
+ Acts as a drop-in replacement for genai_types.Tool with execution support.
+ """
+
+ def __init__(
+ self,
+ tool: Tool,
+ execute_tool: AgenticProviderExecuteFn,
+ function_declaration: t.Optional[t.Any] = None,
+ ):
+ self.tool = tool
+ self.execute_tool = execute_tool
+ self.function_declaration = function_declaration
+
+ # Create the actual Gemini Tool if we have genai support
+ self._genai_tool = None
+ if HAS_GENAI and function_declaration:
+ self._genai_tool = genai_types.Tool(
+ function_declarations=[function_declaration]
+ )
+
+ # Store executor for easy access
+ self._executors = {tool.slug: self}
+
+ # Copy function attributes for compatibility
+ self.__name__ = tool.slug
+ self.__module__ = "composio_gemini"
+ self.__doc__ = tool.description
-class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini"):
+ def __call__(self, **kwargs: t.Any) -> t.Dict:
+ """Execute the tool when called."""
+ result = self.execute_tool(slug=self.tool.slug, arguments=kwargs)
+
+ # Process the result for Gemini
+ if not isinstance(result, dict):
+ return {"result": result}
+
+ # Extract data field if present and successful
+ if result.get("successful", True) and "data" in result:
+ data = result["data"]
+ return data if isinstance(data, dict) else {"result": data}
+
+ # Return error info if failed
+ if not result.get("successful", True):
+ return {
+ "error": result.get("error", "Tool execution failed"),
+ "details": result,
+ }
+
+ return result
+
+ @property
+ def function_declarations(self):
+ """Pass through to the underlying Gemini tool."""
+ return self._genai_tool.function_declarations if self._genai_tool else []
+
+ def to_dict(self):
+ """Convert to dict for Gemini API."""
+ return self._genai_tool.to_dict() if self._genai_tool else {}
+
+
+class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):
"""
Composio toolset for Google AI Python Gemini framework.
+ Supports automatic function calling with native Gemini tools.
"""
__schema_skip_defaults__ = True
+ def _json_to_genai_schema(self, json_schema: dict) -> t.Optional[t.Any]:
+ """Convert JSON Schema to GenAI Schema format, handling composite types."""
+ if not HAS_GENAI:
+ return None
+
+ # Handle composite types (patterns from openapi.py)
+ if "oneOf" in json_schema:
+ # Gemini doesn't support unions directly, use first valid schema
+ # This is a limitation but better than failing
+ return self._json_to_genai_schema(json_schema["oneOf"][0])
+
+ if "anyOf" in json_schema:
+ # Similar to oneOf
+ return self._json_to_genai_schema(json_schema["anyOf"][0])
+
+ if "allOf" in json_schema:
+ # Merge all schemas (pattern from openapi.py's _all_of_to_parameter)
+ merged = {}
+ for subschema in json_schema["allOf"]:
+ merged.update(subschema)
+ return self._json_to_genai_schema(merged)
+
+ # Handle enum independently (can appear with or without type)
+ if "enum" in json_schema:
+ return self._handle_enum_schema(json_schema)
+
+ schema_type = json_schema.get("type", "string")
+
+ # Map type handlers
+ type_handlers = {
+ "array": self._handle_array_schema,
+ "object": self._handle_object_schema,
+ "string": self._handle_string_schema,
+ "number": lambda _: genai_types.Schema(type=genai_types.Type.NUMBER),
+ "integer": lambda _: genai_types.Schema(type=genai_types.Type.INTEGER),
+ "boolean": lambda _: genai_types.Schema(type=genai_types.Type.BOOLEAN),
+ "null": lambda _: genai_types.Schema(
+ type=genai_types.Type.STRING
+ ), # Gemini doesn't have null type
+ }
+
+ handler = type_handlers.get(
+ schema_type, lambda _: genai_types.Schema(type=genai_types.Type.STRING)
+ )
+ return handler(json_schema)
+
+ def _handle_array_schema(self, json_schema: dict) -> t.Any:
+ """Handle array type schema conversion."""
+ items = json_schema.get("items", {})
+ return genai_types.Schema(
+ type=genai_types.Type.ARRAY,
+ items=self._json_to_genai_schema(items)
+ if items
+ else genai_types.Schema(type=genai_types.Type.STRING),
+ )
+
+ def _handle_object_schema(self, json_schema: dict) -> t.Any:
+ """Handle object type schema conversion."""
+ properties = {
+ name: self._json_to_genai_schema(schema)
+ for name, schema in json_schema.get("properties", {}).items()
+ }
+ return genai_types.Schema(
+ type=genai_types.Type.OBJECT,
+ properties=properties,
+ required=json_schema.get("required", []),
+ )
+
+ def _handle_string_schema(self, json_schema: dict) -> t.Any:
+ """Handle string type schema conversion."""
+ schema_dict = {"type": genai_types.Type.STRING}
+ if enum_values := json_schema.get("enum"):
+ schema_dict["enum"] = enum_values
+ return genai_types.Schema(**schema_dict)
+
+ def _handle_enum_schema(self, json_schema: dict) -> t.Any:
+ """Handle enum schema conversion (pattern from openapi.py)."""
+ # Enum can be of any type, default to string if no type specified
+ base_type = json_schema.get("type", "string")
+ type_map = {
+ "string": genai_types.Type.STRING,
+ "integer": genai_types.Type.INTEGER,
+ "number": genai_types.Type.NUMBER,
+ }
+ schema_type = type_map.get(base_type, genai_types.Type.STRING)
+ return genai_types.Schema(type=schema_type, enum=json_schema["enum"])
+
+ def _create_function_declaration(self, tool: Tool) -> t.Optional[t.Any]:
+ """Create a native Gemini FunctionDeclaration if possible."""
+ if not HAS_GENAI:
+ return None
+
+ try:
+ genai_schema = self._json_to_genai_schema(tool.input_parameters)
+ return genai_types.FunctionDeclaration(
+ name=tool.slug,
+ description=tool.description or f"Execute {tool.slug}",
+ parameters=genai_schema,
+ )
+ except Exception as e:
+ print(f"Warning: Could not create FunctionDeclaration for {tool.slug}: {e}")
+ return None
+
def wrap_tool(
self,
tool: Tool,
execute_tool: AgenticProviderExecuteFn,
- ) -> t.Callable:
- """Wraps composio tool as Google Genai SDK compatible function calling object."""
-
- docstring = tool.description
- docstring += "\nArgs:"
- for _param, _schema in tool.input_parameters["properties"].items(): # type: ignore
- docstring += "\n "
- docstring += _param + ": " + _schema.get("description", _param.title())
-
- docstring += "\nReturns:"
- docstring += "\n A dictionary containing response from the action"
-
- def _execute(**kwargs: t.Any) -> t.Dict:
- return execute_tool(slug=tool.slug, arguments=kwargs)
-
- function = types.FunctionType(
- code=_execute.__code__,
- name=tool.slug,
- globals=globals(),
- closure=_execute.__closure__,
- )
- parameters = function_signature_from_jsonschema(
- schema=tool.input_parameters,
- skip_default=self.skip_default,
- )
- setattr(function, "__signature__", Signature(parameters=parameters))
- setattr(
- function,
- "__annotations__",
- {p.name: p.annotation for p in parameters} | {"return": dict},
+ ) -> GeminiTool:
+ """Wrap a Composio tool for Gemini compatibility."""
+ # Create native FunctionDeclaration
+ function_declaration = self._create_function_declaration(tool)
+
+ # Return the GeminiTool wrapper
+ return GeminiTool(
+ tool=tool,
+ execute_tool=execute_tool,
+ function_declaration=function_declaration,
)
- function.__doc__ = docstring
- return function
def wrap_tools(
self,
tools: t.Sequence[Tool],
execute_tool: AgenticProviderExecuteFn,
- ) -> list[t.Callable]:
- """Get composio tools wrapped as Google Genai SDK compatible function calling object."""
+ ) -> list[GeminiTool]:
+ """Wrap multiple tools for Gemini compatibility."""
return [self.wrap_tool(tool, execute_tool) for tool in tools]
+
+ @staticmethod
+ def handle_response(response, tools: list[GeminiTool]) -> tuple[list, bool]:
+ """
+ Automatically handle function calls in a Gemini response.
+
+ Args:
+ response: The response from Gemini chat
+ tools: The list of GeminiTool objects passed to the chat
+
+ Returns:
+ tuple: (function_responses, executed) where function_responses are ready
+ to send back and executed is True if functions were executed
+ """
+ # Check if we have a valid response with candidates
+ if not (hasattr(response, "candidates") and response.candidates):
+ return [], False
+
+ candidate = response.candidates[0]
+ if not (hasattr(candidate, "content") and candidate.content.parts):
+ return [], False
+
+ # Build executor map from tools
+ executors = {}
+ for tool in tools:
+ if isinstance(tool, GeminiTool):
+ executors.update(tool._executors)
+
+ # Process function calls
+ function_responses = []
+ executed = False
+
+ for part in candidate.content.parts:
+ if not (hasattr(part, "function_call") and part.function_call):
+ continue
+
+ fc = part.function_call
+ if fc.name not in executors:
+ continue
+
+ # Execute the function
+ executor = executors[fc.name]
+ result = executor(**fc.args)
+
+ # Create function response
+ if HAS_GENAI:
+ function_responses.append(
+ genai_types.Part(
+ function_response=genai_types.FunctionResponse(
+ name=fc.name, response=result
+ )
+ )
+ )
+ executed = True
+
+ return function_responses, executed