@devries-cameron20 / composio Mirror · read-only / commits / f0e67c435
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 18:15 UTC

Fix tool router types from latest API changes (#2227)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

Musthaq Ahamad committed Dec 5, 2025 at 15:50 UTC f0e67c435cda13e1758f1f6a230d7ba2dd6364d6
39 files changed +1230 -252
.changeset/shaggy-zoos-give.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Update API client and tool router types
pnpm-lock.yaml
+7 -7
@@ -13,8 +13,8 @@ catalogs:
13 specifier: ^4.20250917.0
14 version: 4.20251126.0
15 '@composio/client':
16 - specifier: 0.1.0-alpha.46
17 - version: 0.1.0-alpha.46
16 + specifier: 0.1.0-alpha.47
17 + version: 0.1.0-alpha.47
18 '@modelcontextprotocol/sdk':
19 specifier: ^1.22.0
20 version: 1.23.0
@@ -774,7 +774,7 @@ importers:
774 version: 1.0.0-alpha.1
775 '@composio/client':
776 specifier: 'catalog:'
777 - version: 0.1.0-alpha.46
777 + version: 0.1.0-alpha.47
778 '@composio/core':
779 specifier: workspace:*
780 version: link:../core
@@ -868,7 +868,7 @@ importers:
868 dependencies:
869 '@composio/client':
870 specifier: 'catalog:'
871 - version: 0.1.0-alpha.46
871 + version: 0.1.0-alpha.47
872 '@composio/json-schema-to-zod':
873 specifier: workspace:*
874 version: link:../json-schema-to-zod
@@ -1536,8 +1536,8 @@ packages:
1536 '@cloudflare/workers-types@4.20251126.0':
1537 resolution: {integrity: sha512-DSeI1Q7JYmh5/D/tw5eZCjrKY34v69rwj63hHt60nSQW5QLwWCbj/lLtNz9f2EPa+JCACwpLXHgCXfzJ29x66w==}
1538
1539 - '@composio/client@0.1.0-alpha.46':
1540 - resolution: {integrity: sha512-lhVAf3p2yqjmRfhBsZ+2l7znTPXmcmfD7liZA9a7h9w9qbk5g9D+yn1OhVuc3pnih1W+ahF2uPiFflCRhXfXSw==}
1539 + '@composio/client@0.1.0-alpha.47':
1540 + resolution: {integrity: sha512-ggrfbsDrntwBhRn+kncKluISKys9lePNQsJLGS6j/mfH4RBFjtDT4almw3N9vnOwJb0q4OIb/hrmAxZvwsc0Iw==}
1541
1542 '@composio/mcp@1.0.3-0':
1543 resolution: {integrity: sha512-IpbfST0SSs/CEv+PIf6+EL0feNuJhQyUrOHJLPge8NhyLLrCyVqvujRIPyRUUjy0NDsked/Mm5VpJmYM6OACbg==}
@@ -7691,7 +7691,7 @@ snapshots:
7691
7692 '@cloudflare/workers-types@4.20251126.0': {}
7693
7694 - '@composio/client@0.1.0-alpha.46': {}
7694 + '@composio/client@0.1.0-alpha.47': {}
7695
7696 '@composio/mcp@1.0.3-0': {}
7697
pnpm-workspace.yaml
+1 -1
@@ -15,7 +15,7 @@ packages:
15 catalog:
16 '@cloudflare/vitest-pool-workers': ^0.9.2
17 '@cloudflare/workers-types': ^4.20250917.0
18 - '@composio/client': 0.1.0-alpha.46
18 + '@composio/client': 0.1.0-alpha.47
19 '@modelcontextprotocol/sdk': ^1.22.0
20 ai: 5.0.52
21 openai: ^5.20.3
python/composio/core/models/tool_router.py
+222 -45
@@ -9,6 +9,7 @@ from __future__ import annotations
9
10 import typing as t
11 from dataclasses import dataclass
12 +from enum import Enum
13
14 from composio_client import omit
15 import typing_extensions as te
@@ -22,8 +23,13 @@ if t.TYPE_CHECKING:
23 from composio.core.models._modifiers import Modifiers
24
25 # Type aliases
25 -AuthorizeFn = t.Callable[[str, t.Optional[t.Dict[str, str]]], ConnectionRequest]
26 -ToolkitsFn = t.Callable[[t.Optional[t.Dict[str, t.Any]]], "ToolkitConnectionsDetails"]
26 +AuthorizeFn = t.Callable[..., ConnectionRequest]
27 +
28 +
29 +ToolkitsFn = t.Callable[
30 + ...,
31 + "ToolkitConnectionsDetails",
32 +]
33
34
35 class ToolRouterToolkitsEnabledConfig(te.TypedDict, total=False):
@@ -132,13 +138,13 @@ class ToolRouterManageConnectionsConfig(te.TypedDict, total=False):
138 Attributes:
139 enabled: Whether to use tools to manage connections. Defaults to True.
140 If False, you need to manage connections manually.
135 - callback_uri: Optional callback URI to use for OAuth redirects.
141 + callback_uri: Optional callback URL to use for OAuth redirects.
142 infer_scopes_from_tools: Whether to infer scopes from tools in the tool router session.
143 Defaults to False.
144 """
145
146 enabled: bool
141 - callback_uri: str
147 + callback_url: str
148 infer_scopes_from_tools: bool
149
150
@@ -200,7 +206,7 @@ class ToolkitConnectionState:
206 slug: str
207 name: str
208 is_no_auth: bool
203 - connection: ToolkitConnection
209 + connection: t.Optional[ToolkitConnection] = None
210 logo: t.Optional[str] = None
211
212
@@ -219,12 +225,26 @@ class ToolkitConnectionsDetails:
225 next_cursor: t.Optional[str] = None
226
227
228 +class ToolRouterMCPServerType(str, Enum):
229 + """Enum for MCP server types."""
230 +
231 + HTTP = "http"
232 + SSE = "sse"
233 +
234 +
235 @dataclass
236 class ToolRouterMCPServerConfig:
224 - """Configuration for MCP server."""
237 + """Configuration for MCP server.
238 +
239 + Attributes:
240 + type: The type of MCP server (HTTP or SSE)
241 + url: The URL of the MCP server
242 + headers: Optional authentication headers (includes x-api-key)
243 + """
244
226 - type: str
245 + type: ToolRouterMCPServerType
246 url: str
247 + headers: t.Optional[t.Dict[str, t.Optional[str]]] = None
248
249
250 @dataclass
@@ -289,6 +309,26 @@ class ToolRouter(Resource, t.Generic[TProvider]):
309 super().__init__(client)
310 self._provider = provider
311
312 + def _create_mcp_server_config(
313 + self,
314 + mcp_type: ToolRouterMCPServerType,
315 + url: str,
316 + ) -> ToolRouterMCPServerConfig:
317 + """
318 + Create an MCP server config object with authentication headers.
319 +
320 + :param mcp_type: The type of MCP server (HTTP or SSE)
321 + :param url: The URL of the MCP server
322 + :return: MCP server config with headers
323 + """
324 + return ToolRouterMCPServerConfig(
325 + type=mcp_type,
326 + url=url,
327 + headers={
328 + "x-api-key": self._client.api_key,
329 + },
330 + )
331 +
332 def _create_authorize_fn(self, session_id: str) -> AuthorizeFn:
333 """
334 Create an authorization function for the session.
@@ -299,18 +339,44 @@ class ToolRouter(Resource, t.Generic[TProvider]):
339
340 def authorize_fn(
341 toolkit: str,
302 - options: t.Optional[t.Dict[str, str]] = None,
342 + *,
343 + callback_url: t.Optional[str] = None,
344 ) -> ConnectionRequest:
345 """
305 - Authorize a toolkit for the user.
346 + Authorize a toolkit for the user and get a connection request.
347 +
348 + This method initiates the OAuth flow for a toolkit and returns a
349 + ConnectionRequest object containing the redirect URL for user authorization.
350 +
351 + Args:
352 + toolkit: The toolkit slug to authorize (e.g., 'github', 'slack', 'gmail')
353 + callback_url: Optional URL to redirect user after OAuth authorization completes.
354 + Use this to redirect users back to your application after they authorize.
355 +
356 + Returns:
357 + ConnectionRequest: Object containing:
358 + - id: The connected account ID
359 + - redirect_url: URL to redirect user for OAuth authorization
360 + - status: Connection status ('INITIATED')
361 + - wait_for_connection(): Method to poll until connection is active
362 +
363 + Example:
364 + ```python
365 + # Basic authorization
366 + connection = session.authorize('github')
367 + print(f"Redirect user to: {connection.redirect_url}")
368 +
369 + # With custom callback URL
370 + connection = session.authorize(
371 + 'slack',
372 + callback_url='https://myapp.com/oauth/callback'
373 + )
374
307 - :param toolkit: The toolkit to authorize
308 - :param options: Optional options dict with 'callback_url' key for OAuth redirect
309 - :return: Connection request object
375 + # Wait for user to complete authorization
376 + connected_account = connection.wait_for_connection(timeout=300)
377 + print(f"Connected! Account ID: {connected_account.id}")
378 + ```
379 """
311 - # Make API call to create authorization link
312 - callback_url = options.get("callback_url") if options else None
313 -
380 response = self._client.tool_router.session.link(
381 session_id=session_id,
382 toolkit=toolkit,
@@ -336,20 +402,78 @@ class ToolRouter(Resource, t.Generic[TProvider]):
402 """
403
404 def toolkits_fn(
339 - options: t.Optional[t.Dict[str, t.Any]] = None,
405 + *,
406 + toolkits: t.Optional[t.List[str]] = None,
407 + next_cursor: t.Optional[str] = None,
408 + limit: t.Optional[int] = None,
409 + is_connected: t.Optional[bool] = None,
410 ) -> ToolkitConnectionsDetails:
411 """
412 Get toolkit connection states for the session.
413
344 - :param options: Optional dict with 'next_cursor' and 'limit' keys
345 - :return: Toolkit connections details with items, next_cursor, and total_pages
414 + Retrieves information about toolkits available in this session, including
415 + their connection status, auth configuration, and metadata.
416 +
417 + Args:
418 + toolkits: List of toolkit slugs to filter by (e.g., ['github', 'slack']).
419 + If None, returns all toolkits in the session.
420 + next_cursor: Cursor for pagination to fetch the next page of results.
421 + Use the `next_cursor` from a previous response to get more results.
422 + limit: Maximum number of toolkit items to return per page.
423 + is_connected: Filter by connection status:
424 + - True: Only return toolkits with active connections
425 + - False: Only return toolkits without active connections
426 + - None: Return all toolkits regardless of connection status
427 +
428 + Returns:
429 + ToolkitConnectionsDetails: Object containing:
430 + - items: List of ToolkitConnectionState objects with:
431 + - slug: Toolkit identifier (e.g., 'github')
432 + - name: Display name (e.g., 'GitHub')
433 + - logo: URL to toolkit logo
434 + - is_no_auth: Whether toolkit requires no authentication
435 + - connection: Connection details (is_active, auth_config, connected_account)
436 + - next_cursor: Cursor for fetching next page (None if no more pages)
437 + - total_pages: Total number of pages available
438 +
439 + Example:
440 + ```python
441 + # Get all toolkits in the session
442 + result = session.toolkits()
443 + for toolkit in result.items:
444 + status = "Connected" if toolkit.connection.is_active else "Not connected"
445 + print(f"{toolkit.name}: {status}")
446 +
447 + # Filter by specific toolkits
448 + result = session.toolkits(toolkits=['github', 'slack', 'gmail'])
449 +
450 + # Get only connected toolkits
451 + connected = session.toolkits(is_connected=True)
452 + print(f"You have {len(connected.items)} connected toolkits")
453 +
454 + # Get only disconnected toolkits (need authorization)
455 + disconnected = session.toolkits(is_connected=False)
456 + for toolkit in disconnected.items:
457 + print(f"Please connect: {toolkit.name}")
458 +
459 + # Pagination example
460 + result = session.toolkits(limit=10)
461 + all_toolkits = list(result.items)
462 + while result.next_cursor:
463 + result = session.toolkits(limit=10, next_cursor=result.next_cursor)
464 + all_toolkits.extend(result.items)
465 + ```
466 """
347 - options = options or {}
467 toolkits_params: t.Dict[str, t.Any] = {}
349 - if "next_cursor" in options and options["next_cursor"]:
350 - toolkits_params["cursor"] = options["next_cursor"]
351 - if "limit" in options and options["limit"]:
352 - toolkits_params["limit"] = options["limit"]
468 +
469 + if next_cursor is not None:
470 + toolkits_params["cursor"] = next_cursor
471 + if limit is not None:
472 + toolkits_params["limit"] = limit
473 + if toolkits is not None:
474 + toolkits_params["toolkits"] = toolkits
475 + if is_connected is not None:
476 + toolkits_params["is_connected"] = is_connected
477
478 result = self._client.tool_router.session.toolkits(
479 session_id=session_id,
@@ -375,21 +499,25 @@ class ToolRouter(Resource, t.Generic[TProvider]):
499 status=connected_account.status,
500 )
501
378 - connection = ToolkitConnection(
379 - is_active=(
380 - connected_account.status == "ACTIVE"
381 - if connected_account
382 - else False
383 - ),
384 - auth_config=auth_config,
385 - connected_account=connected_acc,
502 + connection = (
503 + None
504 + if item.is_no_auth
505 + else ToolkitConnection(
506 + is_active=(
507 + connected_account.status == "ACTIVE"
508 + if connected_account
509 + else False
510 + ),
511 + auth_config=auth_config,
512 + connected_account=connected_acc,
513 + )
514 )
515
516 toolkit_state = ToolkitConnectionState(
517 slug=item.slug,
518 name=item.name,
519 logo=item.meta.logo if item.meta else None,
392 - is_no_auth=False,
520 + is_no_auth=item.is_no_auth if item.is_no_auth else False,
521 connection=connection,
522 )
523 toolkit_states.append(toolkit_state)
@@ -429,10 +557,58 @@ class ToolRouter(Resource, t.Generic[TProvider]):
557
558 def tools_fn(modifiers: t.Optional[Modifiers] = None) -> t.Any:
559 """
432 - Get provider-wrapped tools for execution.
560 + Get provider-wrapped tools for execution with your AI framework.
561 +
562 + Returns tools configured for this session, wrapped in the format expected
563 + by your AI provider (OpenAI, Anthropic, LangChain, etc.). The tools are
564 + ready to be passed directly to your AI model for function calling.
565 +
566 + Args:
567 + modifiers: Optional execution modifiers to customize tool behavior:
568 + - Custom pre/post processing hooks
569 + - Schema modifications
570 + - Execution callbacks
571 +
572 + Returns:
573 + Provider-wrapped tools in the format expected by your AI framework.
574 + The exact type depends on the provider configured during initialization.
575 +
576 + Example:
577 + ```python
578 + # Basic usage - get tools for your AI model
579 + tools = session.tools()
580 +
581 + # Use with OpenAI
582 + from openai import OpenAI
583 + client = OpenAI()
584 +
585 + response = client.chat.completions.create(
586 + model="gpt-4",
587 + messages=[{"role": "user", "content": "Star the composio repo"}],
588 + tools=tools,
589 + )
590 +
591 + # Use with Anthropic
592 + from anthropic import Anthropic
593 + client = Anthropic()
594 +
595 + response = client.messages.create(
596 + model="claude-3-opus-20240229",
597 + messages=[{"role": "user", "content": "Send an email"}],
598 + tools=tools,
599 + )
600
434 - :param modifiers: Optional execution modifiers
435 - :return: Provider-wrapped tools
601 + # With custom modifiers
602 + tools = session.tools(modifiers={
603 + 'pre_execute': lambda tool, args: print(f"Executing {tool}"),
604 + 'post_execute': lambda tool, result: print(f"Result: {result}"),
605 + })
606 + ```
607 +
608 + Note:
609 + The tools returned are specific to this session and user. They include
610 + only the tools enabled for this session based on the configuration
611 + provided during session creation.
612 """
613 router_tools = tools_model.get(
614 user_id=user_id, tools=list(tool_slugs), modifiers=modifiers
@@ -474,7 +650,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
650 Example: ['important'] or {'enabled': ['safe']} or {'disabled': ['dangerous']}
651 :param manage_connections: Whether to enable connection management tools.
652 - Boolean: True/False
477 - - Dict with keys: 'enabled', 'callback_uri', 'infer_scopes_from_tools'
653 + - Dict with keys: 'enabled', 'callback_url', 'infer_scopes_from_tools'
654 :param auth_configs: Optional mapping of toolkit slug to auth config ID.
655 Example: {'github': 'ac_xxx', 'slack': 'ac_yyy'}
656 :param connected_accounts: Optional mapping of toolkit slug to connected account ID.
@@ -520,7 +696,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
696 'user_123',
697 manage_connections={
698 'enabled': True,
523 - 'callback_uri': 'https://example.com/callback',
699 + 'callback_url': 'https://example.com/callback',
700 'infer_scopes_from_tools': True
701 }
702 )
@@ -606,8 +782,8 @@ class ToolRouter(Resource, t.Generic[TProvider]):
782 )
783
784 # Parse callback_uri
609 - callback_uri = (
610 - manage_connections.get("callback_uri")
785 + callback_url = (
786 + manage_connections.get("callback_url")
787 if isinstance(manage_connections, dict)
788 else omit
789 )
@@ -622,8 +798,8 @@ class ToolRouter(Resource, t.Generic[TProvider]):
798 "auto_manage_connections": auto_manage_connections,
799 "infer_scopes_from_tools": infer_scopes_from_tools,
800 }
625 - if callback_uri is not None and callback_uri is not omit:
626 - connections_config["callback_uri"] = callback_uri
801 + if callback_url is not None and callback_url is not omit:
802 + connections_config["callback_url"] = callback_url
803
804 create_params["connections"] = connections_config
805
@@ -658,8 +834,8 @@ class ToolRouter(Resource, t.Generic[TProvider]):
834 # Create and return the session
835 return ToolRouterSession(
836 session_id=session.session_id,
661 - mcp=ToolRouterMCPServerConfig(
662 - type=session.mcp.type.upper(),
837 + mcp=self._create_mcp_server_config(
838 + mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
839 url=session.mcp.url,
840 ),
841 tools=self._create_tools_fn(user_id, session.tool_router_tools),
@@ -699,8 +875,8 @@ class ToolRouter(Resource, t.Generic[TProvider]):
875 # Create and return the session
876 return ToolRouterSession(
877 session_id=session.session_id,
702 - mcp=ToolRouterMCPServerConfig(
703 - type=session.mcp.type.upper(),
878 + mcp=self._create_mcp_server_config(
879 + mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
880 url=session.mcp.url,
881 ),
882 tools=self._create_tools_fn(user_id, session.tool_router_tools),
@@ -724,4 +900,5 @@ __all__ = [
900 "ToolkitConnectionState",
901 "ToolkitConnectionsDetails",
902 "ToolRouterMCPServerConfig",
903 + "ToolRouterMCPServerType",
904 ]
python/docs/tool-router.md new
+647
@@ -0,0 +1,647 @@
1 +# Tool Router
2 +
3 +The Tool Router provides a powerful way to create isolated MCP (Model Context Protocol) sessions for users with scoped access to toolkits and tools. It enables dynamic configuration of which tools are available within a session and manages authentication for multiple toolkits.
4 +
5 +## Overview
6 +
7 +Tool Router allows you to:
8 +
9 +- Create isolated sessions with specific toolkit configurations
10 +- Manage authentication flows for users across multiple toolkits
11 +- Access tools via an MCP-compatible server URL
12 +- Query toolkit connection states
13 +- Integrate with multiple AI frameworks (OpenAI, Anthropic, LangChain, LlamaIndex, CrewAI)
14 +
15 +> **Note:** When using MCP clients to connect to Tool Router, you don't need to pass a provider to the Composio constructor. A provider is only required when using `session.tools()` to get framework-specific tool objects.
16 +
17 +## Installation
18 +
19 +```bash
20 +pip install composio
21 +```
22 +
23 +## Quick Start
24 +
25 +### Using MCP (Recommended)
26 +
27 +When using Tool Router with MCP clients, you don't need to pass a provider:
28 +
29 +```python
30 +from composio import Composio
31 +
32 +composio = Composio()
33 +
34 +# Create a session for a user with access to Gmail tools
35 +session = composio.tool_router.create(
36 + user_id='user_123',
37 + toolkits=['gmail']
38 +)
39 +
40 +# Use the MCP URL with any MCP-compatible client
41 +print(session.mcp.url)
42 +```
43 +
44 +### Using Framework-Specific Tools
45 +
46 +If you want to use `session.tools()` to get tools formatted for a specific AI framework, pass the appropriate provider:
47 +
48 +```python
49 +from composio import Composio
50 +from composio_openai import OpenAIProvider
51 +
52 +composio = Composio(provider=OpenAIProvider())
53 +
54 +# Create a session for a user with access to Gmail tools
55 +session = composio.tool_router.create(
56 + user_id='user_123',
57 + toolkits=['gmail']
58 +)
59 +
60 +# Get the tools formatted for OpenAI
61 +tools = session.tools()
62 +```
63 +
64 +## Creating Sessions
65 +
66 +### Basic Session Creation
67 +
68 +Use `composio.tool_router.create()` to create a new Tool Router session:
69 +
70 +```python
71 +from composio import Composio
72 +
73 +composio = Composio()
74 +
75 +# Create a session with Gmail access
76 +session = composio.tool_router.create(
77 + user_id='user_123',
78 + toolkits=['gmail']
79 +)
80 +
81 +print(f"Session ID: {session.session_id}")
82 +print(f"MCP URL: {session.mcp.url}")
83 +```
84 +
85 +### Using an Existing Session
86 +
87 +If you have an existing session ID, you can retrieve it using `composio.tool_router.use()`:
88 +
89 +```python
90 +session = composio.tool_router.use('existing_session_id')
91 +
92 +# Access session properties
93 +print(session.session_id)
94 +print(session.mcp.url)
95 +```
96 +
97 +## Configuration Options
98 +
99 +The session creation accepts the following configuration options:
100 +
101 +### `toolkits`
102 +
103 +Specify which toolkits to enable or disable in the session.
104 +
105 +```python
106 +# Simple list of toolkit slugs to enable
107 +session = composio.tool_router.create(
108 + user_id='user_123',
109 + toolkits=['gmail', 'slack', 'github']
110 +)
111 +
112 +# Explicit enabled configuration
113 +session = composio.tool_router.create(
114 + user_id='user_123',
115 + toolkits={'enabled': ['gmail', 'slack']}
116 +)
117 +
118 +# Disable specific toolkits (enable all others)
119 +session = composio.tool_router.create(
120 + user_id='user_123',
121 + toolkits={'disabled': ['calendar']}
122 +)
123 +```
124 +
125 +### `tools`
126 +
127 +Fine-grained control over which tools are available within toolkits.
128 +
129 +```python
130 +session = composio.tool_router.create(
131 + user_id='user_123',
132 + toolkits=['gmail'],
133 + tools={
134 + # Override tools per toolkit
135 + 'overrides': {
136 + 'gmail': ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'], # Only these tools
137 + # OR use enabled/disabled dicts
138 + # 'gmail': {'enabled': ['GMAIL_FETCH_EMAILS']}
139 + # 'gmail': {'disabled': ['GMAIL_DELETE_EMAIL']}
140 + },
141 + # Filter by tags
142 + 'tags': ['email', 'messaging']
143 + # OR use enabled/disabled
144 + # 'tags': {'enabled': ['email']}
145 + # 'tags': {'disabled': ['destructive']}
146 + }
147 +)
148 +```
149 +
150 +### `auth_configs`
151 +
152 +Map toolkits to specific authentication configurations:
153 +
154 +```python
155 +session = composio.tool_router.create(
156 + user_id='user_123',
157 + toolkits=['gmail', 'github'],
158 + auth_configs={
159 + 'gmail': 'ac_gmail_work',
160 + 'github': 'ac_github_personal'
161 + }
162 +)
163 +```
164 +
165 +### `connected_accounts`
166 +
167 +Map toolkits to specific connected account IDs:
168 +
169 +```python
170 +session = composio.tool_router.create(
171 + user_id='user_123',
172 + toolkits=['gmail'],
173 + connected_accounts={
174 + 'gmail': 'ca_abc123'
175 + }
176 +)
177 +```
178 +
179 +### `manage_connections`
180 +
181 +Control how connections are managed within the session:
182 +
183 +```python
184 +# Boolean: enable/disable automatic connection management
185 +session = composio.tool_router.create(
186 + user_id='user_123',
187 + toolkits=['gmail'],
188 + manage_connections=True # default
189 +)
190 +
191 +# Dict: fine-grained control
192 +session = composio.tool_router.create(
193 + user_id='user_123',
194 + toolkits=['gmail'],
195 + manage_connections={
196 + 'enabled': True,
197 + 'callback_url': 'https://your-app.com/auth/callback',
198 + 'infer_scopes_from_tools': True # Infer OAuth scopes from allowed tools
199 + }
200 +)
201 +```
202 +
203 +### `execution`
204 +
205 +Configure tool execution behavior:
206 +
207 +```python
208 +session = composio.tool_router.create(
209 + user_id='user_123',
210 + toolkits=['gmail'],
211 + execution={
212 + 'proxy_execution_enabled': True,
213 + 'timeout_seconds': 30
214 + }
215 +)
216 +```
217 +
218 +## Session Properties and Methods
219 +
220 +A Tool Router session provides the following properties and methods:
221 +
222 +### `session_id`
223 +
224 +The unique identifier for this session.
225 +
226 +```python
227 +print(session.session_id)
228 +```
229 +
230 +### `mcp`
231 +
232 +The MCP server configuration for this session, including authentication headers.
233 +
234 +```python
235 +print(session.mcp.url) # The URL to connect to
236 +print(session.mcp.type) # ToolRouterMCPServerType.HTTP or ToolRouterMCPServerType.SSE
237 +print(session.mcp.headers) # Authentication headers (includes x-api-key)
238 +```
239 +
240 +### `tools(modifiers=None)`
241 +
242 +Retrieve the tools available in the session, formatted for your AI framework.
243 +
244 +```python
245 +# Basic usage
246 +tools = session.tools()
247 +
248 +# With modifiers
249 +tools = session.tools(modifiers={
250 + 'pre_execute': lambda tool, args: print(f"Executing {tool}"),
251 + 'post_execute': lambda tool, result: print(f"Result: {result}"),
252 +})
253 +```
254 +
255 +### `authorize(toolkit, *, callback_url=None)`
256 +
257 +Initiate an authorization flow for a toolkit.
258 +
259 +```python
260 +# Start authorization for Gmail
261 +connection_request = session.authorize('gmail')
262 +
263 +print(connection_request.redirect_url) # URL to redirect user for auth
264 +
265 +# Wait for the user to complete authorization
266 +connected_account = connection_request.wait_for_connection()
267 +print(f"Connected: {connected_account}")
268 +
269 +# With custom callback URL
270 +connection_request = session.authorize(
271 + 'gmail',
272 + callback_url='https://your-app.com/auth/callback'
273 +)
274 +```
275 +
276 +### `toolkits(...)`
277 +
278 +Query the connection state of toolkits in the session.
279 +
280 +```python
281 +# Get all toolkits
282 +result = session.toolkits()
283 +
284 +for toolkit in result.items:
285 + print(f"{toolkit.name} ({toolkit.slug})")
286 + if toolkit.connection:
287 + print(f" Connected: {toolkit.connection.is_active}")
288 + if toolkit.connection.connected_account:
289 + print(f" Account ID: {toolkit.connection.connected_account.id}")
290 + print(f" Status: {toolkit.connection.connected_account.status}")
291 +
292 +# With pagination
293 +result = session.toolkits(limit=10, next_cursor='cursor_abc')
294 +
295 +# Filter by specific toolkits
296 +result = session.toolkits(toolkits=['gmail', 'slack'])
297 +
298 +# Filter by connection status
299 +connected_toolkits = session.toolkits(is_connected=True)
300 +disconnected_toolkits = session.toolkits(is_connected=False)
301 +
302 +# Combine all options
303 +result = session.toolkits(
304 + toolkits=['gmail', 'github'],
305 + limit=5,
306 + is_connected=True
307 +)
308 +```
309 +
310 +## Framework Integrations
311 +
312 +### OpenAI
313 +
314 +```python
315 +from openai import OpenAI
316 +from composio import Composio
317 +from composio_openai import OpenAIProvider
318 +
319 +composio = Composio(provider=OpenAIProvider())
320 +client = OpenAI()
321 +
322 +session = composio.tool_router.create(
323 + user_id='user_123',
324 + toolkits=['gmail']
325 +)
326 +
327 +tools = session.tools()
328 +
329 +response = client.chat.completions.create(
330 + model="gpt-4",
331 + messages=[{"role": "user", "content": "Find my last email from gmail"}],
332 + tools=tools,
333 +)
334 +
335 +print(response.choices[0].message)
336 +```
337 +
338 +### Anthropic
339 +
340 +```python
341 +from anthropic import Anthropic
342 +from composio import Composio
343 +from composio_anthropic import AnthropicProvider
344 +
345 +composio = Composio(provider=AnthropicProvider())
346 +client = Anthropic()
347 +
348 +session = composio.tool_router.create(
349 + user_id='user_123',
350 + toolkits=['gmail']
351 +)
352 +
353 +tools = session.tools()
354 +
355 +response = client.messages.create(
356 + model="claude-3-opus-20240229",
357 + max_tokens=1024,
358 + messages=[{"role": "user", "content": "Find my last email from gmail"}],
359 + tools=tools,
360 +)
361 +
362 +print(response.content)
363 +```
364 +
365 +### LangChain
366 +
367 +```python
368 +from langchain_openai import ChatOpenAI
369 +from langchain.agents import create_tool_calling_agent, AgentExecutor
370 +from langchain_core.prompts import ChatPromptTemplate
371 +from composio import Composio
372 +from composio_langchain import LangChainProvider
373 +
374 +composio = Composio(provider=LangChainProvider())
375 +
376 +session = composio.tool_router.create(
377 + user_id='user_123',
378 + toolkits=['gmail']
379 +)
380 +
381 +tools = session.tools()
382 +llm = ChatOpenAI(model="gpt-4")
383 +
384 +prompt = ChatPromptTemplate.from_messages([
385 + ("system", "You are a helpful assistant."),
386 + ("human", "{input}"),
387 + ("placeholder", "{agent_scratchpad}"),
388 +])
389 +
390 +agent = create_tool_calling_agent(llm, tools, prompt)
391 +agent_executor = AgentExecutor(agent=agent, tools=tools)
392 +
393 +result = agent_executor.invoke({"input": "Find my last email from gmail"})
394 +print(result)
395 +```
396 +
397 +### Using MCP URL Directly
398 +
399 +You can also use the MCP URL directly with any MCP-compatible client:
400 +
401 +```python
402 +from composio import Composio
403 +
404 +composio = Composio()
405 +
406 +session = composio.tool_router.create(
407 + user_id='user_123',
408 + toolkits=['gmail'],
409 + manage_connections=True
410 +)
411 +
412 +# Use with any MCP client
413 +mcp_url = session.mcp.url
414 +mcp_headers = session.mcp.headers # Pre-configured authentication headers
415 +print(f"MCP URL: {mcp_url}")
416 +print(f"MCP Type: {session.mcp.type}") # 'http' or 'sse'
417 +print(f"MCP Headers: {mcp_headers}") # {'x-api-key': 'your-api-key'}
418 +```
419 +
420 +## Authorization Flow
421 +
422 +When a user needs to connect a toolkit, use the `authorize()` method:
423 +
424 +```python
425 +from composio import Composio
426 +
427 +composio = Composio()
428 +
429 +session = composio.tool_router.create(
430 + user_id='user_123',
431 + toolkits=['gmail']
432 +)
433 +
434 +# Initiate authorization for Gmail
435 +connection_request = session.authorize('gmail')
436 +
437 +# Log the redirect URL for the user
438 +print(f"Redirect URL: {connection_request.redirect_url}")
439 +
440 +# Wait for the user to complete the authorization (with timeout)
441 +connected_account = connection_request.wait_for_connection(timeout=300)
442 +print(f"Connected Account: {connected_account}")
443 +```
444 +
445 +You can also provide a custom callback URL:
446 +
447 +```python
448 +connection_request = session.authorize(
449 + 'gmail',
450 + callback_url='https://your-app.com/auth/callback'
451 +)
452 +```
453 +
454 +## Querying Toolkit States
455 +
456 +Use the `toolkits()` method to check connection states:
457 +
458 +```python
459 +from composio import Composio
460 +
461 +composio = Composio()
462 +
463 +session = composio.tool_router.create(user_id='user_123')
464 +
465 +# Get all toolkits
466 +result = session.toolkits()
467 +
468 +for toolkit in result.items:
469 + status = "Connected" if toolkit.connection and toolkit.connection.is_active else "Not connected"
470 + print(f"{toolkit.name}: {status}")
471 +
472 +# Get only connected toolkits
473 +connected = session.toolkits(is_connected=True)
474 +print(f"You have {len(connected.items)} connected toolkits")
475 +
476 +# Get only disconnected toolkits (need authorization)
477 +disconnected = session.toolkits(is_connected=False)
478 +for toolkit in disconnected.items:
479 + print(f"Please connect: {toolkit.name}")
480 +
481 +# Pagination example
482 +result = session.toolkits(limit=10)
483 +all_toolkits = list(result.items)
484 +while result.next_cursor:
485 + result = session.toolkits(limit=10, next_cursor=result.next_cursor)
486 + all_toolkits.extend(result.items)
487 +```
488 +
489 +The response structure:
490 +
491 +```python
492 +{
493 + 'items': [
494 + {
495 + 'slug': 'gmail',
496 + 'name': 'Gmail',
497 + 'logo': 'https://...',
498 + 'is_no_auth': False,
499 + 'connection': {
500 + 'is_active': True,
501 + 'auth_config': {
502 + 'id': 'ac_xxx',
503 + 'mode': 'OAUTH2',
504 + 'is_composio_managed': True
505 + },
506 + 'connected_account': {
507 + 'id': 'ca_xxx',
508 + 'status': 'ACTIVE'
509 + }
510 + }
511 + }
512 + ],
513 + 'next_cursor': 'cursor_abc',
514 + 'total_pages': 1
515 +}
516 +```
517 +
518 +## Best Practices
519 +
520 +1. **User Isolation**: Create separate sessions per user to ensure proper isolation of connections and tools.
521 +
522 +2. **Toolkit Selection**: Only enable toolkits that are necessary for the use case to maintain security and reduce complexity.
523 +
524 +3. **Connection Management**: Use `manage_connections=True` (default) for interactive applications where users can be prompted to connect accounts.
525 +
526 +4. **Scope Inference**: Enable `infer_scopes_from_tools` when you want OAuth scopes to be automatically derived from the tools you've enabled.
527 +
528 +5. **Session Reuse**: Store and reuse `session_id` to maintain user sessions across requests.
529 +
530 +```python
531 +import redis
532 +
533 +# Store session ID after creation
534 +session = composio.tool_router.create(user_id='user_123', toolkits=['gmail'])
535 +redis_client.set(f"session:user_123", session.session_id)
536 +
537 +# Retrieve existing session
538 +session_id = redis_client.get(f"session:user_123")
539 +if session_id:
540 + session = composio.tool_router.use(session_id)
541 +```
542 +
543 +## Type Reference
544 +
545 +### ToolRouterSession
546 +
547 +```python
548 +@dataclass
549 +class ToolRouterSession:
550 + session_id: str
551 + mcp: ToolRouterMCPServerConfig
552 + tools: Callable[[Optional[Modifiers]], Any]
553 + authorize: Callable[..., ConnectionRequest]
554 + toolkits: Callable[..., ToolkitConnectionsDetails]
555 +```
556 +
557 +### ToolRouterMCPServerConfig
558 +
559 +```python
560 +class ToolRouterMCPServerType(str, Enum):
561 + HTTP = "http"
562 + SSE = "sse"
563 +
564 +@dataclass
565 +class ToolRouterMCPServerConfig:
566 + type: ToolRouterMCPServerType
567 + url: str
568 + headers: Optional[Dict[str, Optional[str]]] = None # Authentication headers (includes x-api-key)
569 +```
570 +
571 +### ToolkitConnectionState
572 +
573 +```python
574 +@dataclass
575 +class ToolkitConnectionState:
576 + slug: str
577 + name: str
578 + is_no_auth: bool
579 + connection: Optional[ToolkitConnection] = None
580 + logo: Optional[str] = None
581 +
582 +@dataclass
583 +class ToolkitConnection:
584 + is_active: bool
585 + auth_config: Optional[ToolkitConnectionAuthConfig] = None
586 + connected_account: Optional[ToolkitConnectedAccount] = None
587 +
588 +@dataclass
589 +class ToolkitConnectionAuthConfig:
590 + id: str
591 + mode: str
592 + is_composio_managed: bool
593 +
594 +@dataclass
595 +class ToolkitConnectedAccount:
596 + id: str
597 + status: str
598 +```
599 +
600 +### ToolkitConnectionsDetails
601 +
602 +```python
603 +@dataclass
604 +class ToolkitConnectionsDetails:
605 + items: List[ToolkitConnectionState]
606 + total_pages: int
607 + next_cursor: Optional[str] = None
608 +```
609 +
610 +### Configuration Types
611 +
612 +```python
613 +# Toolkits configuration
614 +toolkits: Union[
615 + List[str], # ['gmail', 'slack']
616 + Dict[str, List[str]] # {'enabled': [...]} or {'disabled': [...]}
617 +]
618 +
619 +# Tools configuration
620 +tools: TypedDict({
621 + 'overrides': Dict[str, Union[
622 + List[str], # ['TOOL_1', 'TOOL_2']
623 + Dict[str, List[str]] # {'enabled': [...]} or {'disabled': [...]}
624 + ]],
625 + 'tags': Union[
626 + List[str], # ['tag1', 'tag2']
627 + Dict[str, List[str]] # {'enabled': [...]} or {'disabled': [...]}
628 + ]
629 +})
630 +
631 +# Manage connections configuration
632 +manage_connections: Union[
633 + bool,
634 + TypedDict({
635 + 'enabled': bool,
636 + 'callback_url': str,
637 + 'infer_scopes_from_tools': bool
638 + })
639 +]
640 +
641 +# Execution configuration
642 +execution: TypedDict({
643 + 'proxy_execution_enabled': bool,
644 + 'timeout_seconds': int
645 +})
646 +```
647 +
python/examples/tool_router/claude_agent.py
+1 -10
@@ -1,7 +1,6 @@
1 from composio import Composio
2 from claude_agent_sdk import query, ClaudeAgentOptions
3 import asyncio
4 -import os
4
5 composio = Composio()
6 session = composio.experimental.create(
@@ -13,15 +12,7 @@ async def main():
12 options = ClaudeAgentOptions(
13 system_prompt="You are an expert Python developer",
14 permission_mode="bypassPermissions",
16 - mcp_servers={
17 - "composio": {
18 - "type": "http",
19 - "url": session.mcp.url,
20 - "headers": {
21 - "x-api-key": os.getenv("COMPOSIO_API_KEY"),
22 - },
23 - }
24 - },
15 + mcp_servers={"composio": session.mcp},
16 )
17
18 async for message in query(
python/examples/tool_router/crewai_agent.py
+1 -4
@@ -1,7 +1,6 @@
1 from crewai import Agent, Task, Crew
2 from composio import Composio
3 from crewai.mcp import MCPServerHTTP
4 -import os
4
5
6 composio = Composio()
@@ -16,9 +15,7 @@ agent = Agent(
15 mcps=[
16 MCPServerHTTP(
17 url=session.mcp.url,
19 - headers={
20 - "x-api-key": os.getenv("COMPOSIO_API_KEY"),
21 - },
18 + headers=session.mcp.headers,
19 )
20 ],
21 )
python/examples/tool_router/langchain_agent.py
+1 -4
@@ -2,7 +2,6 @@ from composio import Composio
2 from langchain_mcp_adapters.client import MultiServerMCPClient
3 from langchain.agents import create_agent
4 from langchain_openai.chat_models import ChatOpenAI
5 -import os
5 import asyncio
6
7 composio = Composio()
@@ -18,9 +17,7 @@ async def main():
17 "composio": {
18 "transport": "streamable_http",
19 "url": session.mcp.url,
21 - "headers": {
22 - "x-api-key": os.getenv("COMPOSIO_API_KEY"),
23 - },
20 + "headers": session.mcp.headers,
21 }
22 }
23 )
python/examples/tool_router/openai_agents.py
+2 -3
@@ -1,13 +1,12 @@
1 from composio import Composio
2 from agents import Agent, Runner, HostedMCPTool
3 -import os
3
4 composio = Composio()
5 session = composio.experimental.create(
6 user_id="user_123",
7 )
8
10 -print(session.mcp.url)
9 +print(session.mcp)
10
11 composio_mcp = HostedMCPTool(
12 tool_config={
@@ -15,7 +14,7 @@ composio_mcp = HostedMCPTool(
14 "server_label": "tool_router",
15 "server_url": session.mcp.url,
16 "require_approval": "never",
18 - "headers": {"x-api-key": os.getenv("COMPOSIO_API_KEY")},
17 + "headers": session.mcp.headers,
18 }
19 )
20
python/examples/tool_router/tool_router_mcp.py
+1 -3
@@ -36,9 +36,7 @@ async def main():
36 "server_label": "tool_router",
37 "server_url": session.mcp.url,
38 "require_approval": "never",
39 - "headers": {
40 - "x-api-key": api_key,
41 - },
39 + "headers": session.mcp.headers,
40 }
41 )
42
python/providers/anthropic/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-anthropic"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your Anthropic LLMs."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/anthropic/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_anthropic",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Anthropic LLMs.",
python/providers/autogen/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-autogen"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your autogen agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/autogen/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_autogen",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Autogen agent.",
python/providers/crewai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-crewai"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your CrewAI agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/crewai/setup.py
+1 -1
@@ -6,7 +6,7 @@ from setuptools import setup
6
7 setup(
8 name="composio_crewai",
9 - version="0.9.5-rc.1",
9 + version="0.9.5-rc.2",
10 author="Composio",
11 author_email="tech@composio.dev",
12 description="Use Composio to get an array of tools with your CrewAI agent.",
python/providers/gemini/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-gemini"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your Gemini agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/gemini/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_gemini",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Gemini agent.",
python/providers/google/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/google_adk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google-adk"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google_adk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google_adk",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/langchain/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langchain"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your Langchain agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langchain/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langchain",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Langchain agent.",
python/providers/langgraph/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langgraph"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get array of tools with LangGraph Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langgraph/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langgraph",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LangGraph Agent Workflows",
python/providers/llamaindex/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-llamaindex"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/llamaindex/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_llamaindex",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
python/providers/openai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get an array of tools with your OpenAI Function Call."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_openai",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your OpenAI Function Call.",
python/providers/openai_agents/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai-agents"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai_agents/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_openai_agents",
11 - version="0.9.5-rc.1",
11 + version="0.9.5-rc.2",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of strongly typed tools for OpenAI Agents",
python/pyproject.toml
+2 -2
@@ -1,13 +1,13 @@
1 [project]
2 name = "composio"
3 -version = "0.9.5-rc.1"
3 +version = "0.9.5-rc.2"
4 description = "SDK for integrating Composio with your applications."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
7 dependencies = [
8 "pysher>=1.0.8",
9 "pydantic>=2.6.4",
10 - "composio-client>=1.17.1",
10 + "composio-client>=1.18.0",
11 "typing-extensions>=4.0.0",
12 "openai",
13 ]
python/tests/test_tool_router.py
+46 -25
@@ -12,6 +12,7 @@ from composio.core.models.tool_router import (
12 ToolRouterManageConnectionsConfig,
13 ToolkitConnectionState,
14 ToolkitConnectionsDetails,
15 + ToolRouterMCPServerType,
16 )
17
18
@@ -19,12 +20,13 @@ from composio.core.models.tool_router import (
20 def mock_client():
21 """Create a mock HTTP client."""
22 client = MagicMock()
23 + client.api_key = "test-api-key"
24
25 # Mock session responses
26 mock_session_response = MagicMock()
27 mock_session_response.session_id = "session_123"
28 mock_session_response.mcp = MagicMock()
27 - mock_session_response.mcp.type = "HTTP"
29 + mock_session_response.mcp.type = "http"
30 mock_session_response.mcp.url = "https://mcp.example.com/session_123"
31 mock_session_response.tool_router_tools = [
32 "GMAIL_FETCH_EMAILS",
@@ -48,6 +50,7 @@ def mock_client():
50 mock_toolkit_item_active.slug = "gmail"
51 mock_toolkit_item_active.name = "Gmail"
52 mock_toolkit_item_active.meta.logo = "https://example.com/gmail-logo.png"
53 + mock_toolkit_item_active.is_no_auth = False
54 mock_toolkit_item_active.connected_account = MagicMock()
55 mock_toolkit_item_active.connected_account.id = "conn_123"
56 mock_toolkit_item_active.connected_account.status = "ACTIVE"
@@ -60,6 +63,7 @@ def mock_client():
63 mock_toolkit_item_inactive.slug = "github"
64 mock_toolkit_item_inactive.name = "GitHub"
65 mock_toolkit_item_inactive.meta.logo = "https://example.com/github-logo.png"
66 + mock_toolkit_item_inactive.is_no_auth = False
67 mock_toolkit_item_inactive.connected_account = None
68
69 mock_toolkits_response = MagicMock()
@@ -101,8 +105,9 @@ class TestToolRouter:
105
106 # Verify session properties
107 assert session.session_id == "session_123"
104 - assert session.mcp.type == "HTTP"
108 + assert session.mcp.type == ToolRouterMCPServerType.HTTP
109 assert session.mcp.url == "https://mcp.example.com/session_123"
110 + assert session.mcp.headers == {"x-api-key": "test-api-key"}
111 assert callable(session.tools)
112 assert callable(session.authorize)
113 assert callable(session.toolkits)
@@ -223,7 +228,7 @@ class TestToolRouter:
228 user_id="user_123",
229 manage_connections={
230 "enabled": True,
226 - "callback_uri": "https://example.com/callback",
231 + "callback_url": "https://example.com/callback",
232 "infer_scopes_from_tools": True,
233 },
234 )
@@ -233,7 +238,7 @@ class TestToolRouter:
238 call_args = mock_client.tool_router.session.create.call_args
239 kwargs = call_args.kwargs
240 assert kwargs["connections"]["auto_manage_connections"] is True
236 - assert kwargs["connections"]["callback_uri"] == "https://example.com/callback"
241 + assert kwargs["connections"]["callback_url"] == "https://example.com/callback"
242 assert kwargs["connections"]["infer_scopes_from_tools"] is True
243
244 def test_create_session_with_auth_configs(self, tool_router, mock_client):
@@ -297,7 +302,7 @@ class TestToolRouter:
302 )
303
304 assert session.session_id == "session_123"
300 - assert session.mcp.type == "HTTP"
305 + assert session.mcp.type == ToolRouterMCPServerType.HTTP
306
307 # Verify all parameters were passed correctly
308 call_args = mock_client.tool_router.session.create.call_args
@@ -324,8 +329,9 @@ class TestToolRouter:
329
330 # Verify session properties
331 assert session.session_id == "session_123"
327 - assert session.mcp.type == "HTTP"
332 + assert session.mcp.type == ToolRouterMCPServerType.HTTP
333 assert session.mcp.url == "https://mcp.example.com/session_123"
334 + assert session.mcp.headers == {"x-api-key": "test-api-key"}
335 assert callable(session.tools)
336 assert callable(session.authorize)
337 assert callable(session.toolkits)
@@ -338,7 +344,7 @@ class TestToolRouter:
344 mock_retrieve_response = MagicMock()
345 mock_retrieve_response.session_id = "session_456"
346 mock_retrieve_response.mcp = MagicMock()
341 - mock_retrieve_response.mcp.type = "HTTP"
347 + mock_retrieve_response.mcp.type = "http"
348 mock_retrieve_response.mcp.url = "https://mcp.example.com/session_456"
349 mock_retrieve_response.tool_router_tools = ["TOOL_1"]
350 mock_retrieve_response.config = MagicMock()
@@ -349,7 +355,7 @@ class TestToolRouter:
355 session = tool_router.use(session_id="session_456")
356
357 assert session.session_id == "session_456"
352 - assert session.mcp.type == "HTTP"
358 + assert session.mcp.type == ToolRouterMCPServerType.HTTP
359
360 def test_use_session_throws_error_on_failure(self, tool_router, mock_client):
361 """Test that use() throws error if retrieve fails."""
@@ -376,9 +382,7 @@ class TestToolRouter:
382 """Test the authorize function with callback URL."""
383 session = tool_router.create(user_id="user_123")
384
379 - session.authorize(
380 - "github", options={"callback_url": "https://myapp.com/callback"}
381 - )
385 + session.authorize("github", callback_url="https://myapp.com/callback")
386
387 # Verify link was called with callback_url
388 call_args = mock_client.tool_router.session.link.call_args
@@ -405,7 +409,7 @@ class TestToolRouter:
409 """Test the toolkits function with pagination options."""
410 session = tool_router.create(user_id="user_123")
411
408 - session.toolkits(options={"next_cursor": "cursor_abc", "limit": 10})
412 + session.toolkits(next_cursor="cursor_abc", limit=10)
413
414 # Verify toolkits was called with pagination params
415 call_args = mock_client.tool_router.session.toolkits.call_args
@@ -487,18 +491,19 @@ class TestToolRouter:
491 call_args = mock_tools_instance.get.call_args
492 assert call_args.kwargs.get("modifiers") == modifiers
493
490 - def test_session_mcp_type_uppercase(self, tool_router, mock_client):
491 - """Test that MCP type is uppercase."""
494 + def test_session_mcp_type_http(self, tool_router, mock_client):
495 + """Test that MCP type is correctly set to HTTP enum."""
496 session = tool_router.create(user_id="user_123")
497
494 - assert session.mcp.type == "HTTP"
498 + assert session.mcp.type == ToolRouterMCPServerType.HTTP
499 + assert session.mcp.type.value == "http"
500
501 def test_session_mcp_sse_type(self, tool_router, mock_client):
502 """Test that SSE MCP type is handled correctly."""
503 mock_sse_response = MagicMock()
504 mock_sse_response.session_id = "session_sse"
505 mock_sse_response.mcp = MagicMock()
501 - mock_sse_response.mcp.type = "SSE"
506 + mock_sse_response.mcp.type = "sse"
507 mock_sse_response.mcp.url = "https://mcp.example.com/sse/session_sse"
508 mock_sse_response.tool_router_tools = ["TOOL_1"]
509
@@ -506,7 +511,8 @@ class TestToolRouter:
511
512 session = tool_router.create(user_id="user_123")
513
509 - assert session.mcp.type == "SSE"
514 + assert session.mcp.type == ToolRouterMCPServerType.SSE
515 + assert session.mcp.type.value == "sse"
516 assert session.mcp.url == "https://mcp.example.com/sse/session_sse"
517
518 def test_multiple_sessions_independently(self, tool_router, mock_client):
@@ -514,14 +520,14 @@ class TestToolRouter:
520 mock_session_1 = MagicMock()
521 mock_session_1.session_id = "session_1"
522 mock_session_1.mcp = MagicMock()
517 - mock_session_1.mcp.type = "HTTP"
523 + mock_session_1.mcp.type = "http"
524 mock_session_1.mcp.url = "https://mcp.example.com/session_1"
525 mock_session_1.tool_router_tools = ["TOOL_1"]
526
527 mock_session_2 = MagicMock()
528 mock_session_2.session_id = "session_2"
529 mock_session_2.mcp = MagicMock()
524 - mock_session_2.mcp.type = "HTTP"
530 + mock_session_2.mcp.type = "http"
531 mock_session_2.mcp.url = "https://mcp.example.com/session_2"
532 mock_session_2.tool_router_tools = ["TOOL_2"]
533
@@ -543,14 +549,14 @@ class TestToolRouter:
549 mock_create_response = MagicMock()
550 mock_create_response.session_id = "created_session"
551 mock_create_response.mcp = MagicMock()
546 - mock_create_response.mcp.type = "HTTP"
552 + mock_create_response.mcp.type = "http"
553 mock_create_response.mcp.url = "https://mcp.example.com/created"
554 mock_create_response.tool_router_tools = ["TOOL_1"]
555
556 mock_retrieve_response = MagicMock()
557 mock_retrieve_response.session_id = "retrieved_session"
558 mock_retrieve_response.mcp = MagicMock()
553 - mock_retrieve_response.mcp.type = "HTTP"
559 + mock_retrieve_response.mcp.type = "http"
560 mock_retrieve_response.mcp.url = "https://mcp.example.com/retrieved"
561 mock_retrieve_response.tool_router_tools = ["TOOL_2"]
562 mock_retrieve_response.config = MagicMock()
@@ -590,16 +596,31 @@ class TestToolRouterTypes:
596 """Test ToolRouterManageConnectionsConfig type."""
597 config: ToolRouterManageConnectionsConfig = {
598 "enabled": True,
593 - "callback_uri": "https://example.com/callback",
599 + "callback_url": "https://example.com/callback",
600 }
601 assert config["enabled"] is True
596 - assert config["callback_uri"] == "https://example.com/callback"
602 + assert config["callback_url"] == "https://example.com/callback"
603
604 def test_mcp_server_config(self):
605 """Test ToolRouterMCPServerConfig dataclass."""
600 - mcp = ToolRouterMCPServerConfig(type="HTTP", url="https://mcp.example.com")
601 - assert mcp.type == "HTTP"
606 + mcp = ToolRouterMCPServerConfig(
607 + type=ToolRouterMCPServerType.HTTP, url="https://mcp.example.com"
608 + )
609 + assert mcp.type == ToolRouterMCPServerType.HTTP
610 + assert mcp.type.value == "http"
611 + assert mcp.url == "https://mcp.example.com"
612 + assert mcp.headers is None # Headers are optional
613 +
614 + def test_mcp_server_config_with_headers(self):
615 + """Test ToolRouterMCPServerConfig dataclass with headers."""
616 + mcp = ToolRouterMCPServerConfig(
617 + type=ToolRouterMCPServerType.HTTP,
618 + url="https://mcp.example.com",
619 + headers={"x-api-key": "test-api-key"},
620 + )
621 + assert mcp.type == ToolRouterMCPServerType.HTTP
622 assert mcp.url == "https://mcp.example.com"
623 + assert mcp.headers == {"x-api-key": "test-api-key"}
624
625 def test_toolkit_connection_state(self):
626 """Test ToolkitConnectionState dataclass."""
ts/docs/api/tool-router.md
+10 -16
@@ -226,11 +226,12 @@ console.log(session.sessionId);
226
227 ### `mcp`
228
229 -The MCP server configuration for this session.
229 +The MCP server configuration for this session, including authentication headers.
230
231 ```typescript
232 -console.log(session.mcp.url); // The URL to connect to
233 -console.log(session.mcp.type); // 'HTTP' or 'SSE'
232 +console.log(session.mcp.url); // The URL to connect to
233 +console.log(session.mcp.type); // 'HTTP' or 'SSE'
234 +console.log(session.mcp.headers); // Authentication headers (includes x-api-key)
235 ```
236
237 ### `tools()`
@@ -354,14 +355,12 @@ const { mcp } = await composio.experimental.create('user_123', {
355 manageConnections: true
356 });
357
357 -// Create MCP client using the session URL
358 +// Create MCP client using the session URL and headers
359 const client = await createMCPClient({
360 transport: {
361 type: 'http',
362 url: mcp.url,
362 - headers: {
363 - 'x-api-key': process.env.COMPOSIO_API_KEY!,
364 - }
363 + headers: mcp.headers, // Uses pre-configured authentication headers
364 }
365 });
366
@@ -411,9 +410,7 @@ const client = new MultiServerMCPClient({
410 composio: {
411 transport: "http",
412 url: session.mcp.url,
414 - headers: {
415 - 'x-api-key': process.env.COMPOSIO_API_KEY!,
416 - }
413 + headers: session.mcp.headers, // Uses pre-configured authentication headers
414 },
415 });
416
@@ -454,9 +451,7 @@ console.log(`Connecting to MCP server: ${session.mcp.url}`);
451 const mcpTool = hostedMcpTool({
452 serverLabel: 'ComposioApps',
453 serverUrl: session.mcp.url,
457 - headers: {
458 - 'x-api-key': process.env.COMPOSIO_API_KEY!,
459 - }
454 + headers: session.mcp.headers, // Uses pre-configured authentication headers
455 });
456
457 const agent = new Agent({
@@ -502,9 +497,7 @@ const stream = await query({
497 composio: {
498 type: 'http',
499 url: session.mcp.url,
505 - headers: {
506 - 'x-api-key': process.env.COMPOSIO_API_KEY!,
507 - }
500 + headers: session.mcp.headers, // Uses pre-configured authentication headers
501 }
502 },
503 }
@@ -676,6 +669,7 @@ interface ToolRouterSession {
669 mcp: {
670 type: 'HTTP' | 'SSE';
671 url: string;
672 + headers?: Record<string, string | undefined>; // Authentication headers (includes x-api-key)
673 };
674 tools: (modifiers?: ProviderOptions) => Promise<Tools>;
675 authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;
ts/packages/core/src/models/ToolRouter.ts
+61 -35
@@ -22,6 +22,10 @@ import {
22 ToolRouterCreateSessionConfig,
23 ToolRouterSession,
24 ToolkitConnectionStateSchema,
25 + ToolRouterToolkitsOptions,
26 + ToolRouterToolkitsOptionsSchema,
27 + MCPServerType,
28 + ToolRouterMCPServerConfig,
29 } from '../types/toolRouter.types';
30 import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
31 import { Tools } from './Tools';
@@ -31,7 +35,7 @@ import { createConnectionRequest } from './ConnectionRequest';
35 import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';
36 import { transform } from '../utils/transform';
37 import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
34 -import { transformToolRouterToolsParams } from '../lib/toolRouterParams';
38 +import { ValidationError } from '../errors';
39
40 export class ToolRouter<
41 TToolCollection,
@@ -88,15 +92,19 @@ export class ToolRouter<
92 * ```
93 */
94 private createToolkitsFn = (sessionId: string): ToolRouterToolkitsFn => {
91 - const connectionsFn = async (options?: {
92 - toolkits?: Array<string>;
93 - nextCursor?: string;
94 - limit?: number;
95 - }) => {
95 + const connectionsFn = async (options?: ToolRouterToolkitsOptions) => {
96 + const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {});
97 + if (!toolkitOptions.success) {
98 + throw new ValidationError('Failed to parse toolkits options', {
99 + cause: toolkitOptions.error,
100 + });
101 + }
102 +
103 const result = await this.client.toolRouter.session.toolkits(sessionId, {
97 - cursor: options?.nextCursor,
98 - limit: options?.limit,
99 - toolkits: options?.toolkits,
104 + cursor: toolkitOptions.data.nextCursor,
105 + limit: toolkitOptions.data.limit,
106 + toolkits: toolkitOptions.data.toolkits,
107 + is_connected: toolkitOptions.data.isConnected,
108 });
109
110 const toolkitConnectedStates = result.items.map(item => {
@@ -105,22 +113,24 @@ export class ToolRouter<
113 .using(item => ({
114 slug: item.slug,
115 name: item.name,
108 - logo: item.meta.logo,
109 - isNoAuth: false,
110 - connection: {
111 - isActive: item.connected_account?.status === 'ACTIVE',
112 - authConfig: item.connected_account && {
113 - id: item.connected_account?.auth_config.id,
114 - mode: item.connected_account?.auth_config.auth_scheme,
115 - isComposioManaged: item.connected_account?.auth_config.is_composio_managed,
116 - },
117 - connectedAccount: item.connected_account
118 - ? {
119 - id: item.connected_account.id,
120 - status: item.connected_account.status,
121 - }
122 - : undefined,
123 - },
116 + logo: item.meta?.logo,
117 + isNoAuth: item.is_no_auth,
118 + connection: item.is_no_auth
119 + ? undefined
120 + : {
121 + isActive: item.connected_account?.status === 'ACTIVE',
122 + authConfig: item.connected_account && {
123 + id: item.connected_account?.auth_config.id,
124 + mode: item.connected_account?.auth_config.auth_scheme,
125 + isComposioManaged: item.connected_account?.auth_config.is_composio_managed,
126 + },
127 + connectedAccount: item.connected_account
128 + ? {
129 + id: item.connected_account.id,
130 + status: item.connected_account.status,
131 + }
132 + : undefined,
133 + },
134 }));
135 return connectedState;
136 });
@@ -161,6 +171,28 @@ export class ToolRouter<
171 };
172 };
173
174 + /**
175 + * Creates a MCP server config object.
176 + * @param type {MCPServerType} The type of the MCP server
177 + * @param url {string} The URL of the MCP server
178 + * @returns {ToolRouterMCPServerConfig} The MCP server config object
179 + */
180 + private createMCPServerConfig = ({
181 + type,
182 + url,
183 + }: {
184 + type: MCPServerType;
185 + url: string;
186 + }): ToolRouterMCPServerConfig => {
187 + return {
188 + type,
189 + url,
190 + headers: {
191 + 'x-api-key': this.config?.apiKey ?? undefined,
192 + },
193 + };
194 + };
195 +
196 /**
197 * Creates a new tool router session for a user.
198 *
@@ -216,9 +248,9 @@ export class ToolRouter<
248 connections: {
249 infer_scopes_from_tools: inferScopesFromTools,
250 auto_manage_connections: manageConnectedAccounts,
219 - callback_uri:
251 + callback_url:
252 typeof routerConfig.manageConnections === 'object'
221 - ? routerConfig.manageConnections.callbackUri
253 + ? routerConfig.manageConnections.callbackUrl
254 : undefined,
255 },
256 execution: routerConfig.execution
@@ -232,10 +264,7 @@ export class ToolRouter<
264
265 return {
266 sessionId: session.session_id,
235 - mcp: {
236 - type: session.mcp.type,
237 - url: session.mcp.url,
238 - },
267 + mcp: this.createMCPServerConfig(session.mcp),
268 tools: this.createToolsFn(userId, session.tool_router_tools),
269 authorize: this.createAuthorizeFn(session.session_id),
270 toolkits: this.createToolkitsFn(session.session_id),
@@ -260,10 +289,7 @@ export class ToolRouter<
289 const session = await this.client.toolRouter.session.retrieve(id);
290 return {
291 sessionId: session.session_id,
263 - mcp: {
264 - type: session.mcp.type,
265 - url: session.mcp.url,
266 - },
292 + mcp: this.createMCPServerConfig(session.mcp),
293 tools: this.createToolsFn(session.config.user_id, session.tool_router_tools),
294 authorize: this.createAuthorizeFn(session.session_id),
295 toolkits: this.createToolkitsFn(session.session_id),
ts/packages/core/src/types/toolRouter.types.ts
+43 -27
@@ -3,7 +3,7 @@ import { BaseComposioProvider } from '../provider/BaseProvider';
3 import { ExecuteToolModifiers, ProviderOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5
6 -export const MCPServerTypeSchema = z.enum(['HTTP', 'SSE']);
6 +export const MCPServerTypeSchema = z.enum(['http', 'sse']);
7 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
8
9 // manage connections
@@ -16,7 +16,7 @@ export const ToolRouterConfigManageConnectionsSchema = z
16 .describe(
17 'Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually'
18 ),
19 - callbackUri: z
19 + callbackUrl: z
20 .string()
21 .optional()
22 .describe('The callback uri to use in the tool router session'),
@@ -207,7 +207,7 @@ export const ToolRouterCreateSessionConfigSchema = z
207 * @param {Record<string, string>} connectedAccounts - The connected accounts to use in the tool router session
208 * @param {ToolRouterConfigManageConnectionsSchema | boolean} manageConnections - The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings.
209 * @param {boolean} [manageConnections.enabled] - Whether to use tools to manage connections in the tool router session @default true
210 - * @param {string} [manageConnections.callbackUri] - The callback uri to use in the tool router session
210 + * @param {string} [manageConnections.callbackUrl] - The callback uri to use in the tool router session
211 * @param {boolean} [manageConnections.inferScopesFromTools] - Whether to infer scopes from tools in the tool router session @default false
212 */
213 export type ToolRouterCreateSessionConfig = z.infer<typeof ToolRouterCreateSessionConfigSchema>;
@@ -218,24 +218,29 @@ export const ToolkitConnectionStateSchema = z
218 name: z.string().describe('The name of a toolkit'),
219 logo: z.string().optional().describe('The logo of a toolkit'),
220 isNoAuth: z.boolean().default(false).describe('Whether the toolkit is no auth or not'),
221 - connection: z.object({
222 - isActive: z.boolean().describe('Whether the connection is active or not'),
223 - authConfig: z
224 - .object({
225 - id: z.string().describe('The id of the auth config'),
226 - mode: z.string().describe('The auth scheme used by the auth config'),
227 - isComposioManaged: z.boolean().describe('Whether the auth config is managed by Composio'),
228 - })
229 - .nullish()
230 - .describe('The auth config of a toolkit'),
231 - connectedAccount: z
232 - .object({
233 - id: z.string().describe('The id of the connected account'),
234 - status: z.string().describe('The status of the connected account'),
235 - })
236 - .optional()
237 - .describe('The connected account of a toolkit'),
238 - }),
221 + connection: z
222 + .object({
223 + isActive: z.boolean().describe('Whether the connection is active or not'),
224 + authConfig: z
225 + .object({
226 + id: z.string().describe('The id of the auth config'),
227 + mode: z.string().describe('The auth scheme used by the auth config'),
228 + isComposioManaged: z
229 + .boolean()
230 + .describe('Whether the auth config is managed by Composio'),
231 + })
232 + .nullish()
233 + .describe('The auth config of a toolkit'),
234 + connectedAccount: z
235 + .object({
236 + id: z.string().describe('The id of the connected account'),
237 + status: z.string().describe('The status of the connected account'),
238 + })
239 + .optional()
240 + .describe('The connected account of a toolkit'),
241 + })
242 + .optional()
243 + .describe('The connection of a toolkit'),
244 })
245 .describe('The connection state of a toolkit');
246
@@ -248,7 +253,12 @@ export type ToolkitConnectionsDetails = z.infer<typeof ToolkitConnectionsDetails
253
254 export type ToolkitConnectionState = z.infer<typeof ToolkitConnectionStateSchema>;
255
251 -export type ToolRouterMCPServerConfig = { type: MCPServerType; url: string };
256 +export const ToolRouterMCPServerConfigSchema = z.object({
257 + type: MCPServerTypeSchema,
258 + url: z.string(),
259 + headers: z.record(z.string(), z.string().optional()).optional(),
260 +});
261 +export type ToolRouterMCPServerConfig = z.infer<typeof ToolRouterMCPServerConfigSchema>;
262
263 export type ToolRouterToolsFn<
264 TToolCollection,
@@ -261,11 +271,17 @@ export type ToolRouterAuthorizeFn = (
271 options?: { callbackUrl?: string }
272 ) => Promise<ConnectionRequest>;
273
264 -export type ToolRouterToolkitsFn = (options?: {
265 - toolkits?: Array<string>;
266 - nextCursor?: string;
267 - limit?: number;
268 -}) => Promise<ToolkitConnectionsDetails>;
274 +export const ToolRouterToolkitsOptionsSchema = z.object({
275 + toolkits: z.array(z.string()).optional(),
276 + nextCursor: z.string().optional(),
277 + limit: z.number().optional(),
278 + isConnected: z.boolean().optional(),
279 +});
280 +export type ToolRouterToolkitsOptions = z.infer<typeof ToolRouterToolkitsOptionsSchema>;
281 +
282 +export type ToolRouterToolkitsFn = (
283 + options?: ToolRouterToolkitsOptions
284 +) => Promise<ToolkitConnectionsDetails>;
285 export interface ToolRouterSession<
286 TToolCollection,
287 TTool,
ts/packages/core/test/models/toolRouter.test.ts
+145 -35
@@ -45,7 +45,7 @@ const createMockClient = () => ({
45 const mockSessionCreateResponse = {
46 session_id: 'session_123',
47 mcp: {
48 - type: 'HTTP',
48 + type: 'http',
49 url: 'https://mcp.example.com/session_123',
50 },
51 tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
@@ -59,7 +59,7 @@ const mockLinkResponse = {
59 const mockSessionRetrieveResponse = {
60 session_id: 'session_123',
61 mcp: {
62 - type: 'HTTP',
62 + type: 'http',
63 url: 'https://mcp.example.com/session_123',
64 },
65 tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
@@ -83,6 +83,7 @@ const mockToolkitsResponse = {
83 meta: {
84 logo: 'https://example.com/gmail-logo.png',
85 },
86 + is_no_auth: false,
87 connected_account: {
88 id: 'conn_123',
89 status: 'ACTIVE',
@@ -99,6 +100,7 @@ const mockToolkitsResponse = {
100 meta: {
101 logo: 'https://example.com/slack-logo.png',
102 },
103 + is_no_auth: false,
104 connected_account: {
105 id: 'conn_456',
106 status: 'INITIATED',
@@ -115,6 +117,7 @@ const mockToolkitsResponse = {
117 meta: {
118 logo: 'https://example.com/github-logo.png',
119 },
120 + is_no_auth: false,
121 connected_account: null,
122 },
123 ],
@@ -131,13 +134,13 @@ describe('ToolRouter', () => {
134 const createExpectedConnections = (
135 overrides: {
136 manageConnections?: boolean;
134 - callbackUri?: string;
137 + callbackUrl?: string;
138 inferScopesFromTools?: boolean;
139 } = {}
140 ) => ({
141 infer_scopes_from_tools: overrides.inferScopesFromTools ?? false,
142 auto_manage_connections: overrides.manageConnections ?? true,
140 - callback_uri: overrides.callbackUri ?? undefined,
143 + callback_url: overrides.callbackUrl ?? undefined,
144 });
145
146 beforeEach(() => {
@@ -146,6 +149,7 @@ describe('ToolRouter', () => {
149 mockProvider = new MockProvider();
150 toolRouter = new ToolRouter(mockClient as unknown as ComposioClient, {
151 provider: mockProvider,
152 + apiKey: 'test-api-key',
153 });
154 });
155
@@ -160,7 +164,7 @@ describe('ToolRouter', () => {
164 });
165
166 it('should store the config reference', () => {
163 - expect(toolRouter['config']).toEqual({ provider: mockProvider });
167 + expect(toolRouter['config']).toEqual({ provider: mockProvider, apiKey: 'test-api-key' });
168 });
169 });
170
@@ -186,8 +190,11 @@ describe('ToolRouter', () => {
190 expect(session).toHaveProperty('sessionId', 'session_123');
191 expect(session).toHaveProperty('mcp');
192 expect(session.mcp).toEqual({
189 - type: 'HTTP',
193 + type: 'http',
194 url: 'https://mcp.example.com/session_123',
195 + headers: {
196 + 'x-api-key': 'test-api-key',
197 + },
198 });
199 expect(session).toHaveProperty('tools');
200 expect(session).toHaveProperty('authorize');
@@ -217,7 +224,7 @@ describe('ToolRouter', () => {
224
225 const session = await toolRouter.create(userId);
226
220 - expect(session.mcp.type).toBe('HTTP');
227 + expect(session.mcp.type).toBe('http');
228 expect(mockClient.toolRouter.session.create).toHaveBeenCalledTimes(1);
229 });
230 });
@@ -562,13 +569,13 @@ describe('ToolRouter', () => {
569 });
570 });
571
565 - it('should create a session with manageConnections object with callbackUri', async () => {
572 + it('should create a session with manageConnections object with callbackUrl', async () => {
573 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
574
575 const config: ToolRouterCreateSessionConfig = {
576 manageConnections: {
577 enabled: true,
571 - callbackUri: 'https://myapp.com/callback',
578 + callbackUrl: 'https://myapp.com/callback',
579 inferScopesFromTools: false,
580 },
581 };
@@ -583,7 +590,7 @@ describe('ToolRouter', () => {
590 tools: undefined,
591 connections: createExpectedConnections({
592 manageConnections: true,
586 - callbackUri: 'https://myapp.com/callback',
593 + callbackUrl: 'https://myapp.com/callback',
594 }),
595 execution: undefined,
596 });
@@ -621,7 +628,7 @@ describe('ToolRouter', () => {
628 const config: ToolRouterCreateSessionConfig = {
629 manageConnections: {
630 enabled: true,
624 - callbackUri: 'https://myapp.com/callback',
631 + callbackUrl: 'https://myapp.com/callback',
632 inferScopesFromTools: true,
633 },
634 };
@@ -637,7 +644,7 @@ describe('ToolRouter', () => {
644 connections: createExpectedConnections({
645 manageConnections: true,
646 inferScopesFromTools: true,
640 - callbackUri: 'https://myapp.com/callback',
647 + callbackUrl: 'https://myapp.com/callback',
648 }),
649 execution: undefined,
650 });
@@ -1020,26 +1027,26 @@ describe('ToolRouter', () => {
1027
1028 describe('response handling', () => {
1029 it('should handle MCP type correctly', async () => {
1023 - const responseWithUppercase = {
1030 + const responseWithHttp = {
1031 ...mockSessionCreateResponse,
1032 mcp: {
1026 - type: 'HTTP',
1033 + type: 'http',
1034 url: 'https://mcp.example.com/session_123',
1035 },
1036 };
1037
1031 - mockClient.toolRouter.session.create.mockResolvedValueOnce(responseWithUppercase);
1038 + mockClient.toolRouter.session.create.mockResolvedValueOnce(responseWithHttp);
1039
1040 const session = await toolRouter.create(userId);
1041
1035 - expect(session.mcp.type).toBe('HTTP');
1042 + expect(session.mcp.type).toBe('http');
1043 });
1044
1045 it('should handle SSE MCP type correctly', async () => {
1046 const sseResponse = {
1047 ...mockSessionCreateResponse,
1048 mcp: {
1042 - type: 'SSE',
1049 + type: 'sse',
1050 url: 'https://mcp.example.com/sse/session_123',
1051 },
1052 };
@@ -1048,7 +1055,7 @@ describe('ToolRouter', () => {
1055
1056 const session = await toolRouter.create(userId);
1057
1051 - expect(session.mcp.type).toBe('SSE');
1058 + expect(session.mcp.type).toBe('sse');
1059 expect(session.mcp.url).toBe('https://mcp.example.com/sse/session_123');
1060 });
1061
@@ -1187,6 +1194,7 @@ describe('ToolRouter', () => {
1194 cursor: undefined,
1195 limit: undefined,
1196 toolkits: undefined,
1197 + is_connected: undefined,
1198 });
1199
1200 expect(result).toHaveProperty('items');
@@ -1208,6 +1216,7 @@ describe('ToolRouter', () => {
1216 cursor: 'cursor_abc',
1217 limit: 10,
1218 toolkits: undefined,
1219 + is_connected: undefined,
1220 });
1221
1222 expect(result.items).toHaveLength(3);
@@ -1225,6 +1234,25 @@ describe('ToolRouter', () => {
1234 cursor: undefined,
1235 limit: undefined,
1236 toolkits: ['gmail', 'slack'],
1237 + is_connected: undefined,
1238 + });
1239 +
1240 + expect(result.items).toHaveLength(3);
1241 + });
1242 +
1243 + it('should fetch toolkits with isConnected filter option', async () => {
1244 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce(mockToolkitsResponse);
1245 +
1246 + const session = await toolRouter.create(userId);
1247 + const result = await session.toolkits({
1248 + isConnected: true,
1249 + });
1250 +
1251 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
1252 + cursor: undefined,
1253 + limit: undefined,
1254 + toolkits: undefined,
1255 + is_connected: true,
1256 });
1257
1258 expect(result.items).toHaveLength(3);
@@ -1244,6 +1272,28 @@ describe('ToolRouter', () => {
1272 cursor: 'cursor_xyz',
1273 limit: 5,
1274 toolkits: ['github'],
1275 + is_connected: undefined,
1276 + });
1277 +
1278 + expect(result.items).toHaveLength(3);
1279 + });
1280 +
1281 + it('should fetch toolkits with all options combined', async () => {
1282 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce(mockToolkitsResponse);
1283 +
1284 + const session = await toolRouter.create(userId);
1285 + const result = await session.toolkits({
1286 + limit: 5,
1287 + nextCursor: 'cursor_xyz',
1288 + toolkits: ['github', 'gmail'],
1289 + isConnected: false,
1290 + });
1291 +
1292 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
1293 + cursor: 'cursor_xyz',
1294 + limit: 5,
1295 + toolkits: ['github', 'gmail'],
1296 + is_connected: false,
1297 });
1298
1299 expect(result.items).toHaveLength(3);
@@ -1260,13 +1310,13 @@ describe('ToolRouter', () => {
1310 expect(gmailToolkit.name).toBe('Gmail');
1311 expect(gmailToolkit.logo).toBe('https://example.com/gmail-logo.png');
1312 expect(gmailToolkit.isNoAuth).toBe(false);
1263 - expect(gmailToolkit.connection.isActive).toBe(true);
1264 - expect(gmailToolkit.connection.authConfig).toEqual({
1313 + expect(gmailToolkit.connection?.isActive).toBe(true);
1314 + expect(gmailToolkit.connection?.authConfig).toEqual({
1315 id: 'auth_config_123',
1316 mode: 'OAUTH2',
1317 isComposioManaged: true,
1318 });
1269 - expect(gmailToolkit.connection.connectedAccount).toEqual({
1319 + expect(gmailToolkit.connection?.connectedAccount).toEqual({
1320 id: 'conn_123',
1321 status: 'ACTIVE',
1322 });
@@ -1280,8 +1330,8 @@ describe('ToolRouter', () => {
1330
1331 const slackToolkit = result.items[1];
1332 expect(slackToolkit.slug).toBe('slack');
1283 - expect(slackToolkit.connection.isActive).toBe(false);
1284 - expect(slackToolkit.connection.connectedAccount?.status).toBe('INITIATED');
1333 + expect(slackToolkit.connection?.isActive).toBe(false);
1334 + expect(slackToolkit.connection?.connectedAccount?.status).toBe('INITIATED');
1335 });
1336
1337 it('should transform toolkit connection state correctly for no connection', async () => {
@@ -1292,9 +1342,38 @@ describe('ToolRouter', () => {
1342
1343 const githubToolkit = result.items[2];
1344 expect(githubToolkit.slug).toBe('github');
1295 - expect(githubToolkit.connection.isActive).toBe(false);
1296 - expect(githubToolkit.connection.authConfig).toBeNull();
1297 - expect(githubToolkit.connection.connectedAccount).toBeUndefined();
1345 + expect(githubToolkit.connection?.isActive).toBe(false);
1346 + expect(githubToolkit.connection?.authConfig).toBeNull();
1347 + expect(githubToolkit.connection?.connectedAccount).toBeUndefined();
1348 + });
1349 +
1350 + it('should transform toolkit connection state correctly for no-auth toolkit', async () => {
1351 + const noAuthToolkitsResponse = {
1352 + items: [
1353 + {
1354 + slug: 'codeinterpreter',
1355 + name: 'Code Interpreter',
1356 + meta: {
1357 + logo: 'https://example.com/codeinterpreter-logo.png',
1358 + },
1359 + is_no_auth: true,
1360 + connected_account: null,
1361 + },
1362 + ],
1363 + next_cursor: undefined,
1364 + total_pages: 1,
1365 + };
1366 +
1367 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce(noAuthToolkitsResponse);
1368 +
1369 + const session = await toolRouter.create(userId);
1370 + const result = await session.toolkits();
1371 +
1372 + const codeinterpreterToolkit = result.items[0];
1373 + expect(codeinterpreterToolkit.slug).toBe('codeinterpreter');
1374 + expect(codeinterpreterToolkit.name).toBe('Code Interpreter');
1375 + expect(codeinterpreterToolkit.isNoAuth).toBe(true);
1376 + expect(codeinterpreterToolkit.connection).toBeUndefined();
1377 });
1378
1379 it('should handle empty toolkits response', async () => {
@@ -1356,12 +1435,12 @@ describe('ToolRouter', () => {
1435 await expect(session.toolkits()).rejects.toThrow('Failed to fetch toolkits');
1436 });
1437
1359 - it('should handle malformed response data', async () => {
1438 + it('should handle malformed response data gracefully with undefined values', async () => {
1439 const malformedResponse = {
1440 items: [
1441 {
1442 slug: 'gmail',
1364 - // Missing required fields
1443 + // Missing required fields like name, meta, is_no_auth
1444 },
1445 ],
1446 next_cursor: undefined,
@@ -1372,8 +1451,24 @@ describe('ToolRouter', () => {
1451
1452 const session = await toolRouter.create(userId);
1453
1375 - // Should throw transformation error due to missing required fields
1376 - await expect(session.toolkits()).rejects.toThrow();
1454 + // The code handles malformed data gracefully with undefined values
1455 + const result = await session.toolkits();
1456 + expect(result.items).toHaveLength(1);
1457 + expect(result.items[0].slug).toBe('gmail');
1458 + expect(result.items[0].name).toBeUndefined();
1459 + expect(result.items[0].logo).toBeUndefined();
1460 + expect(result.items[0].isNoAuth).toBeUndefined();
1461 + });
1462 +
1463 + it('should throw validation error for invalid options', async () => {
1464 + const session = await toolRouter.create(userId);
1465 +
1466 + // Invalid options should throw a validation error
1467 + await expect(
1468 + session.toolkits({
1469 + limit: 'invalid' as unknown as number, // Invalid type
1470 + })
1471 + ).rejects.toThrow();
1472 });
1473 });
1474
@@ -1394,7 +1489,10 @@ describe('ToolRouter', () => {
1489 const session = await toolRouter.create(userId);
1490 const tools = await session.tools();
1491
1397 - expect(Tools).toHaveBeenCalledWith(mockClient, { provider: mockProvider });
1492 + expect(Tools).toHaveBeenCalledWith(mockClient, {
1493 + provider: mockProvider,
1494 + apiKey: 'test-api-key',
1495 + });
1496
1497 const toolsInstance = (Tools as any).mock.results[0].value;
1498 expect(toolsInstance.get).toHaveBeenCalledWith(
@@ -1491,7 +1589,10 @@ describe('ToolRouter', () => {
1589 const newSession = await toolRouter.create(userId);
1590 await newSession.tools();
1591
1494 - expect(Tools).toHaveBeenCalledWith(mockClient, { provider: mockProvider });
1592 + expect(Tools).toHaveBeenCalledWith(mockClient, {
1593 + provider: mockProvider,
1594 + apiKey: 'test-api-key',
1595 + });
1596 const toolsInstance = (Tools as any).mock.results[0].value;
1597 expect(toolsInstance.get).toHaveBeenCalledWith(
1598 userId,
@@ -1514,7 +1615,10 @@ describe('ToolRouter', () => {
1615 const session = await toolRouter.create(userId);
1616 await session.tools();
1617
1517 - expect(Tools).toHaveBeenCalledWith(mockClient, { provider: mockProvider });
1618 + expect(Tools).toHaveBeenCalledWith(mockClient, {
1619 + provider: mockProvider,
1620 + apiKey: 'test-api-key',
1621 + });
1622 const toolsInstance = (Tools as any).mock.results[0].value;
1623 expect(toolsInstance.get).toHaveBeenCalledWith(
1624 userId,
@@ -1591,11 +1695,13 @@ describe('ToolRouter', () => {
1695 cursor: undefined,
1696 limit: undefined,
1697 toolkits: undefined,
1698 + is_connected: undefined,
1699 });
1700 expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith('session_2', {
1701 cursor: undefined,
1702 limit: undefined,
1703 toolkits: undefined,
1704 + is_connected: undefined,
1705 });
1706 });
1707
@@ -1631,8 +1737,11 @@ describe('ToolRouter', () => {
1737 expect(session).toHaveProperty('sessionId', 'session_123');
1738 expect(session).toHaveProperty('mcp');
1739 expect(session.mcp).toEqual({
1634 - type: 'HTTP',
1740 + type: 'http',
1741 url: 'https://mcp.example.com/session_123',
1742 + headers: {
1743 + 'x-api-key': 'test-api-key',
1744 + },
1745 });
1746 expect(session).toHaveProperty('tools');
1747 expect(session).toHaveProperty('authorize');
@@ -1695,6 +1804,7 @@ describe('ToolRouter', () => {
1804 cursor: undefined,
1805 limit: undefined,
1806 toolkits: undefined,
1807 + is_connected: undefined,
1808 });
1809 expect(toolkitsResult.items).toHaveLength(3);
1810 expect(toolkitsResult.items[0].slug).toBe('gmail');
@@ -1728,7 +1838,7 @@ describe('ToolRouter', () => {
1838
1839 const session = await toolRouter.use(sessionId);
1840
1731 - expect(session.mcp.type).toBe('HTTP');
1841 + expect(session.mcp.type).toBe('http');
1842 expect(session.mcp.url).toBe('https://mcp.example.com/session_123');
1843 });
1844
uv.lock
+13 -13
@@ -468,7 +468,7 @@ wheels = [
468
469 [[package]]
470 name = "composio"
471 -version = "0.9.4"
471 +version = "0.9.5rc1"
472 source = { virtual = "python" }
473 dependencies = [
474 { name = "composio-client" },
@@ -497,7 +497,7 @@ dev = [
497
498 [package.metadata]
499 requires-dist = [
500 - { name = "composio-client", specifier = ">=1.17.1" },
500 + { name = "composio-client", specifier = ">=1.18.0" },
501 { name = "openai" },
502 { name = "pydantic", specifier = ">=2.6.4" },
503 { name = "pysher", specifier = ">=1.0.8" },
@@ -523,7 +523,7 @@ dev = [
523
524 [[package]]
525 name = "composio-anthropic"
526 -version = "0.9.4"
526 +version = "0.9.5rc1"
527 source = { virtual = "python/providers/anthropic" }
528 dependencies = [
529 { name = "anthropic" },
@@ -538,7 +538,7 @@ requires-dist = [
538
539 [[package]]
540 name = "composio-client"
541 -version = "1.17.1"
541 +version = "1.18.0"
542 source = { registry = "https://pypi.org/simple" }
543 dependencies = [
544 { name = "anyio" },
@@ -548,14 +548,14 @@ dependencies = [
548 { name = "sniffio" },
549 { name = "typing-extensions" },
550 ]
551 -sdist = { url = "https://files.pythonhosted.org/packages/8a/ac/2194260234ef364f7bd4b3dc7a4ae08b6e819ab22935218207795bf77c27/composio_client-1.17.1.tar.gz", hash = "sha256:c5e9d593bc2497f3c57614f544a7c5cf3601f310b2f1e65ccfa9a69dcb496733", size = 182234 }
551 +sdist = { url = "https://files.pythonhosted.org/packages/75/e0/b0d32c293a70d0469bf9fe435d6a3b04a0c1b5148030f7f693197222cb78/composio_client-1.18.0.tar.gz", hash = "sha256:c973fc8538ae358051f8094801b067887e35f23d5ae60b12c9c181bc2da82586", size = 182540 }
552 wheels = [
553 - { url = "https://files.pythonhosted.org/packages/30/4c/7dc1647fba7cdeeb3a62f1ddb03c57d556a81de731ac58b58ae43f2d0ff9/composio_client-1.17.1-py3-none-any.whl", hash = "sha256:ccf7f07e34e67d90eae33034eeccf76ecc98cbf36ebc167f8f4327f3180050c7", size = 198420 },
553 + { url = "https://files.pythonhosted.org/packages/02/c3/4f078e5dc9d24449838fd63145c2d3e4c301b343a7bed469b8cbebb3a25e/composio_client-1.18.0-py3-none-any.whl", hash = "sha256:27e020cb876748507a49df1ca36b8b3a3b5dedef91355e60e8c8563f794cfa6a", size = 198537 },
554 ]
555
556 [[package]]
557 name = "composio-crewai"
558 -version = "0.9.4"
558 +version = "0.9.5rc1"
559 source = { virtual = "python/providers/crewai" }
560 dependencies = [
561 { name = "composio" },
@@ -570,7 +570,7 @@ requires-dist = [
570
571 [[package]]
572 name = "composio-gemini"
573 -version = "0.9.4"
573 +version = "0.9.5rc1"
574 source = { virtual = "python/providers/gemini" }
575 dependencies = [
576 { name = "composio" },
@@ -585,7 +585,7 @@ requires-dist = [
585
586 [[package]]
587 name = "composio-google"
588 -version = "0.9.4"
588 +version = "0.9.5rc1"
589 source = { virtual = "python/providers/google" }
590 dependencies = [
591 { name = "composio" },
@@ -600,7 +600,7 @@ requires-dist = [
600
601 [[package]]
602 name = "composio-google-adk"
603 -version = "0.9.4"
603 +version = "0.9.5rc1"
604 source = { virtual = "python/providers/google_adk" }
605 dependencies = [
606 { name = "composio" },
@@ -615,7 +615,7 @@ requires-dist = [
615
616 [[package]]
617 name = "composio-langchain"
618 -version = "0.9.4"
618 +version = "0.9.5rc1"
619 source = { virtual = "python/providers/langchain" }
620 dependencies = [
621 { name = "composio" },
@@ -630,7 +630,7 @@ requires-dist = [
630
631 [[package]]
632 name = "composio-openai"
633 -version = "0.9.4"
633 +version = "0.9.5rc1"
634 source = { virtual = "python/providers/openai" }
635 dependencies = [
636 { name = "composio" },
@@ -645,7 +645,7 @@ requires-dist = [
645
646 [[package]]
647 name = "composio-openai-agents"
648 -version = "0.9.4"
648 +version = "0.9.5rc1"
649 source = { virtual = "python/providers/openai_agents" }
650 dependencies = [
651 { name = "composio" },