Files
Soumya Medapati 760f8d0367 fix(sdk): route provider tool calls through sessions (#4098)
## Problem

Provider tool-call helpers always used the globally injected direct
`Tools.execute` function. When a model received tools from
`session.tools()`, calling `handleToolCalls` or `handle_tool_calls`
therefore discarded the Tool Router session context and caused session
meta-tools such as `COMPOSIO_SEARCH_TOOLS` to fail.

Calling `session.execute()` manually preserved the session, but bypassed
provider behavior such as Anthropic input normalization and schema-alias
restoration.

## Root fix

- Add an explicit execution target to the non-agentic provider helpers:
- TypeScript: `handleToolCalls(session, response)` and
`executeToolCall(session, call)`
- Python: `handle_tool_calls(response=response, session=session)` and
`execute_tool_call(tool_call=call, session=session)`
- Route normalized provider arguments through the supplied Tool Router
session.
- Map session responses back to each helper's existing result shape.
- Keep provider-specific normalization before execution, including
Anthropic schema-alias restoration.
- Reject direct-only options and modifiers when the selected target is a
session, including plain JavaScript calls that bypass the TypeScript
overloads.
- Update OpenAI and Anthropic examples to use the session-aware helpers.
- Harden the docs policy test so setup and execution split across fences
in one sample are still detected.

## Docs review follow-ups

- Reword the concepts-page prohibition so it forbids user-ID-bound
helper calls, not the helpers themselves, matching the provider pages in
this PR.
- Add minimum-version callouts to the OpenAI and Anthropic provider
pages (Python `composio` newer than 0.19.0; TypeScript `@composio/core`
≥ 0.17.0 with `@composio/openai` ≥ 0.12.0 / `@composio/anthropic` ≥
0.11.0), pointing older versions at `session.execute()`.
- Bump `docs/package.json` to `@composio/core` `^0.15.0` and
`@composio/openai` `^0.11.0` (the published majors at the time of the
bump; `@composio/core` 0.16.0 and `composio` 0.19.0 have since released
from `next` without this PR, so its changeset will publish core 0.17.0
and the next Python minor) and annotate each `@errors: 2345` Twoslash
marker with a TODO naming the minor version that retires it; since this
changeset releases minors, all three pins need a manual range bump to
retire the markers. This version of twoslash only throws on *unlisted*
errors, so a stale marker cannot break the build — it would only mask
future TS2345s, which the TODOs now track.
- Update `SESSION_GUARDRAILS` (the block appended to `.md` responses for
agents): add a session-execution bullet (scoped to the OpenAI and
Anthropic helpers, with `session.execute()` for every other provider)
and qualify the direct-execution list with "with a user ID". The
session-execution static test now scans the guardrail blocks like the
execute-version test already did.
- Tighten the docs detector: the Python branch is bounded to the helper
call's argument list (tolerating one level of nested calls) instead of
running past the closing paren, and the TypeScript branch catches whole
user-ID identifiers (`userId`, `user_id`, `uid`) without flagging
session variables like `userSession` — each edge has a regression test.
- Note on the Google provider page that its `executeToolCall` is not
session-aware yet.

## Compatibility and release

Existing user-ID calls remain unchanged and continue to use direct tool
execution. The new session call forms are additive.

The changeset applies minor releases to `@composio/core`,
`@composio/openai`, and `@composio/anthropic` — the new session
overloads are a type-level break for provider subclasses, so patch was
too small. The configured fixed group also includes `@composio/slim`.

The docs site intentionally checks examples against currently published
SDK declarations. The three new TypeScript calls therefore carry exact
Twoslash `TS2345` release-skew annotations; remove them (per the inline
TODOs) once `docs/package.json` picks up `@composio/core` ≥ 0.17.0,
`@composio/openai` ≥ 0.12.0, and `@composio/anthropic` ≥ 0.11.0.

## Verification

- `@composio/core`: 1,061 tests passed; typecheck passed
- `@composio/openai`: 34 tests passed; typecheck passed
- `@composio/anthropic`: 53 tests passed; typecheck passed
- Python provider and aliasing suites: 40 passed, 4 skipped
- Focused Python mypy and Ruff checks passed
- Docs static suite: 208 tests passed (including the new guardrail-scan
and detector cases)
- Docs production build passed with the bumped `@composio/core` 0.15.0 /
`@composio/openai` 0.11.0, including Twoslash, TypeScript, and all
generated pages
- Docs lint passed; lint reports only existing warnings
- Changeset status reports the expected minor packages

---------

Co-authored-by: Soumya Medapati <soumyamedapati@soumyas-air.local.meter>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: jkomyno <alberto@composio.dev>
2026-08-18 23:55:11 +02:00

130 lines
3.7 KiB
Python

"""
BaseProvider module
Defines the barebones provider metaclass that needs to be subclassed for every provider.
"""
from __future__ import annotations
import typing as t
import typing_extensions as te
if t.TYPE_CHECKING:
from composio.core.models.tools import Modifiers, ToolExecutionResponse
TTool = t.TypeVar("TTool")
TToolCollection = t.TypeVar("TToolCollection")
class ExecuteToolFn(t.Protocol):
def __call__(
self,
slug: str,
arguments: t.Dict,
*,
modifiers: t.Optional[Modifiers] = None,
user_id: t.Optional[str] = None,
) -> ToolExecutionResponse:
"""
Execute a wrapped tool by slug, passing an arbitrary input dict.
This function is used by the providers to execute tools for the helper methods.
Returns a dict with the following keys:
- data: The data returned by the tool.
- error: The error returned by the tool.
- successful: Whether the tool was successful.
"""
...
class ToolCallSession(t.Protocol):
"""Execution contract implemented by ToolRouterSession."""
def execute(
self,
tool_slug: str,
*,
arguments: t.Optional[t.Dict[str, t.Any]] = None,
) -> t.Any: ...
ToolCallExecutionTarget: t.TypeAlias = t.Union[str, ToolCallSession]
class SchemaConfig(te.TypedDict):
skip_defaults: te.NotRequired[bool]
class BaseProviderConfig(te.TypedDict):
schema_config: te.NotRequired[SchemaConfig]
class BaseProvider(t.Generic[TTool, TToolCollection]):
"""
BaseProvider class
All providers should inherit from this class and implement `wrap_tools` so that
they can be used with the core Composio class.
"""
name: str
"""Name of the provider"""
__schema_skip_defaults__ = False
execute_tool: ExecuteToolFn
"""
The function to execute a tool for the provider's helper methods.
This is automatically injected by the core SDK.
"""
def __init__(self, **kwargs: t.Unpack[BaseProviderConfig]) -> None:
self.skip_default = kwargs.get("schema_config", {}).get(
"skip_defaults", self.__schema_skip_defaults__
)
def set_execute_tool_fn(self, execute_tool_fn: ExecuteToolFn) -> None:
self.execute_tool = execute_tool_fn
def resolve_tool_call_execution_target(
self,
*,
user_id: t.Optional[str],
session: t.Optional[ToolCallSession],
) -> ToolCallExecutionTarget:
"""Resolve exactly one direct user or Tool Router session target."""
if (user_id is None) == (session is None):
raise ValueError("Provide exactly one of user_id or session")
if session is not None:
return session
return t.cast(str, user_id)
def execute_tool_for_target(
self,
*,
target: ToolCallExecutionTarget,
slug: str,
arguments: t.Dict[str, t.Any],
modifiers: t.Optional[Modifiers] = None,
) -> ToolExecutionResponse:
"""Execute normalized arguments through the matching SDK boundary."""
if isinstance(target, str):
return self.execute_tool(
slug=slug,
arguments=arguments,
modifiers=modifiers,
user_id=target,
)
if modifiers is not None:
raise ValueError(
"Direct execution modifiers cannot be used with a Tool Router session"
)
result = target.execute(tool_slug=slug, arguments=arguments)
return {
"data": t.cast(t.Dict, result.data),
"error": result.error,
"successful": result.error is None,
}