@devries-cameron20 / composio Mirror · read-only
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 21, 03:37 UTC

next
py 180 lines 5.38 KB
Raw
1 """
2 Example demonstrating the use of ToolRouter in Composio SDK.
3
4 This example shows how to create a tool router session for a user,
5 get provider-wrapped tools, and authorize toolkits.
6 """
7
8 import os
9
10 from composio import Composio
11
12 # Initialize Composio SDK
13 composio = Composio()
14
15 # Provisioned project state (raises KeyError when unset). The backend validates
16 # auth config ids, so a placeholder would abort session creation.
17 user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]
18 github_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GITHUB_AUTH_CONFIG_ID"]
19
20
21 # Example 1: Create a basic tool router session
22 def basic_session_example():
23 """Create a basic tool router session."""
24 print("=== Basic Session Example ===")
25
26 # Create a tool router session. mcp=True surfaces session.mcp on the
27 # returned type; without it the endpoint exists but is not typed.
28 session = composio.tool_router.create(user_id=user_id, mcp=True)
29
30 print(f"Session ID: {session.session_id}")
31 print(f"MCP Server Type: {session.mcp.type}")
32 print(f"MCP Server URL: {session.mcp.url}")
33
34 # Get tools wrapped for the provider
35 tools = session.tools()
36 print(
37 f"Number of tools available: {len(tools) if isinstance(tools, list) else 'N/A'}"
38 )
39
40 return session
41
42
43 # Example 2: Create a session with connection management
44 def session_with_connections_example():
45 """Create a session with connection management enabled."""
46 print("\n=== Session with Connection Management ===")
47
48 # Create a tool router session with connection management
49 session = composio.tool_router.create(user_id=user_id, manage_connections=True)
50
51 print(f"Session ID: {session.session_id}")
52 print("Connection management enabled")
53
54 # Get tools (now includes COMPOSIO_MANAGE_CONNECTIONS)
55 tools = session.tools()
56 print(
57 f"Number of tools available: {len(tools) if isinstance(tools, list) else 'N/A'}"
58 )
59
60 return session
61
62
63 # Example 3: Authorize a toolkit
64 def authorize_toolkit_example():
65 """Demonstrate toolkit authorization."""
66 print("\n=== Authorize Toolkit Example ===")
67
68 # Create a session
69 session = composio.tool_router.create(user_id=user_id)
70
71 # Authorize GitHub toolkit for the user
72 try:
73 connection_request = session.authorize("github")
74
75 print(f"Connection Request ID: {connection_request.id}")
76 print(f"Connection Status: {connection_request.status}")
77
78 if connection_request.redirect_url:
79 print(f"Redirect URL: {connection_request.redirect_url}")
80 print("User should visit this URL to complete authorization")
81
82 return connection_request
83 except Exception as e:
84 print(f"Error authorizing toolkit: {e}")
85 raise
86
87
88 # Example 4: Get toolkit connection states
89 def get_toolkits_example():
90 """Get toolkit connection states for a session."""
91 print("\n=== Get Toolkits Example ===")
92
93 # Create a session
94 session = composio.tool_router.create(user_id=user_id)
95
96 # Get toolkit connection states
97 toolkits = session.toolkits()
98
99 print(f"Current toolkits: {toolkits}")
100
101 return toolkits
102
103
104 # Example 5: Full workflow with advanced configuration
105 def full_workflow_example():
106 """Complete workflow with session, tools, and authorization."""
107 print("\n=== Full Workflow Example ===")
108
109 # 1. Create session with multiple configurations
110 session = composio.tool_router.create(
111 user_id=user_id,
112 toolkits=["github", "slack"],
113 manage_connections=True,
114 auth_configs={"github": github_auth_config_id},
115 )
116
117 print(f"✓ Created session: {session.session_id}")
118
119 # 2. Get tools for the session
120 tools = session.tools()
121 print(f"✓ Retrieved {len(tools) if isinstance(tools, list) else 'N/A'} tools")
122
123 # 3. Check toolkits
124 toolkits_result = session.toolkits()
125 print(f"✓ Current toolkits: {len(toolkits_result.items)} toolkit(s)")
126
127 # 4. Authorize a toolkit if needed
128 try:
129 connection_request = session.authorize("slack")
130 print("✓ Initiated authorization for Slack")
131
132 if connection_request.redirect_url:
133 print(f" → Redirect URL: {connection_request.redirect_url}")
134 except Exception as e:
135 print(f"✗ Authorization error: {e}")
136 raise
137
138 return session
139
140
141 # Example 6: Using with custom modifiers
142 def session_with_modifiers_example():
143 """Create a session and use tools with custom modifiers."""
144 print("\n=== Session with Modifiers Example ===")
145
146 # Create session
147 session = composio.tool_router.create(user_id=user_id)
148
149 # Modifiers are a list of before/after execute hooks; an empty list means
150 # "no modifiers", which is what this example passes.
151 modifiers: list = []
152
153 tools = session.tools(modifiers=modifiers or None)
154 print(
155 f"✓ Retrieved {len(tools) if isinstance(tools, list) else 'N/A'} tools with modifiers"
156 )
157
158 return session
159
160
161 if __name__ == "__main__":
162 """Run all examples."""
163 print("Composio ToolRouter Examples\n")
164 print("=" * 50)
165
166 # Run examples
167 try:
168 basic_session_example()
169 session_with_connections_example()
170 authorize_toolkit_example()
171 get_toolkits_example()
172 full_workflow_example()
173 session_with_modifiers_example()
174
175 print("\n" + "=" * 50)
176 print("✓ All examples completed successfully!")
177
178 except Exception as e:
179 print(f"\n✗ Error running examples: {e}")
180 raise