@devries-cameron20 / composio Mirror · read-only / commits / 1c2ff77df
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, 15:45 UTC

Add Tools and Triggers documentation section

- Add authenticating-tools page with auth configs, Connect Link, OAuth/API key flows - Add executing-tools page covering chat completions, agentic frameworks, direct execution - Add using-triggers page with webhooks, subscriptions, and payload types - Add custom-tools page for standalone and toolkit-based tools - Add toolkit-versioning page for version pinning - Add modify-tool-behavior collapsible section with schema, input, and output modifiers - Create reusable Figure component with click-to-zoom and size variants - Create reusable Video component with performance optimizations - Add supporting images and video assets 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

Sushmithamallesh committed Dec 30, 2025 at 13:16 UTC 1c2ff77dfe33eb012fbbfa08ccc21f10da6ef5ab
22 files changed +2482 -3
fumadocs/app/(home)/docs/layout.tsx
+2 -2
@@ -8,8 +8,8 @@ const pageTree = {
8 children: source.pageTree.children.flatMap((child) =>
9 child.type === 'separator' && child.name === 'Tools and Triggers'
10 ? [changelogPage, child]
11 - : child
12 - ),
11 + : [child]
12 + ) as typeof source.pageTree.children,
13 };
14
15 export default function Layout({ children }: LayoutProps<'/docs'>) {
fumadocs/components/figure.tsx new
+47
@@ -0,0 +1,47 @@
1 +'use client';
2 +
3 +import Zoom from 'react-medium-image-zoom';
4 +import 'react-medium-image-zoom/dist/styles.css';
5 +import { cn } from '@/lib/utils';
6 +
7 +type FigureSize = 'sm' | 'md' | 'lg' | 'full';
8 +
9 +interface FigureProps {
10 + src: string;
11 + alt: string;
12 + caption?: string;
13 + size?: FigureSize;
14 + className?: string;
15 +}
16 +
17 +const sizeClasses: Record<FigureSize, string> = {
18 + sm: 'max-w-[300px]', // Small dialogs, icons
19 + md: 'max-w-[500px]', // Medium screenshots
20 + lg: 'max-w-[700px]', // Large screenshots
21 + full: 'max-w-full', // Full-width diagrams
22 +};
23 +
24 +export function Figure({ src, alt, caption, size = 'full', className }: FigureProps) {
25 + const isConstrained = size !== 'full';
26 +
27 + return (
28 + <figure className={cn('my-8', isConstrained && 'flex flex-col items-center', className)}>
29 + <Zoom>
30 + <img
31 + src={src}
32 + alt={alt}
33 + className={cn(
34 + 'rounded-lg border border-fd-border',
35 + sizeClasses[size],
36 + isConstrained ? 'w-auto' : 'w-full'
37 + )}
38 + />
39 + </Zoom>
40 + {caption && (
41 + <figcaption className="mt-3 text-sm text-fd-muted-foreground text-center">
42 + {caption}
43 + </figcaption>
44 + )}
45 + </figure>
46 + );
47 +}
fumadocs/components/video.tsx new
+46
@@ -0,0 +1,46 @@
1 +'use client';
2 +
3 +import { cn } from '@/lib/utils';
4 +
5 +interface VideoProps {
6 + src: string;
7 + caption?: string;
8 + poster?: string;
9 + autoPlay?: boolean;
10 + loop?: boolean;
11 + muted?: boolean;
12 + controls?: boolean;
13 + className?: string;
14 +}
15 +
16 +export function Video({
17 + src,
18 + caption,
19 + poster,
20 + autoPlay = false,
21 + loop = true,
22 + muted = true,
23 + controls = true,
24 + className,
25 +}: VideoProps) {
26 + return (
27 + <figure className={cn('my-8', className)}>
28 + <video
29 + src={src}
30 + poster={poster}
31 + autoPlay={autoPlay}
32 + loop={loop}
33 + muted={muted}
34 + controls={controls}
35 + playsInline
36 + preload="metadata"
37 + className="w-full rounded-lg border border-fd-border"
38 + />
39 + {caption && (
40 + <figcaption className="mt-3 text-sm text-fd-muted-foreground text-center">
41 + {caption}
42 + </figcaption>
43 + )}
44 + </figure>
45 + );
46 +}
fumadocs/content/docs/authenticating-tools.mdx new
+484
@@ -0,0 +1,484 @@
1 +---
2 +title: Authenticating Tools
3 +description: Create auth configs and connect user accounts
4 +---
5 +
6 +The first step in authenticating your users is to create an **Auth Config**. Every toolkit has its own authentication method such as `OAuth`, `API key`, `Basic Auth`, or custom schemes.
7 +
8 +An **Auth Config** is a blueprint that defines how authentication works for a toolkit across all your users. It defines:
9 +
10 +1. **Authentication method** - `OAuth2`, `Bearer token`, `API key`, or `Basic Auth`
11 +2. **Scopes** - what actions your tools can perform
12 +3. **Credentials** - whether you'll use your own app credentials or Composio's managed auth
13 +
14 +## Creating an auth config
15 +
16 +### Using the Dashboard
17 +
18 +<Steps>
19 +<Step>
20 +### Selecting a toolkit
21 +
22 +Navigate to [Auth Configs](https://platform.composio.dev?next_page=%2Fauth-configs) tab in your dashboard and click "**Create Auth Config**". Find and select the toolkit you want to integrate (e.g., **Gmail**, **Slack**, **GitHub**).
23 +</Step>
24 +
25 +<Step>
26 +### Selecting the Authentication method
27 +
28 +Each toolkit supports different authentication methods such as **OAuth**, **API Key**, **Bearer Token**. Select from the available options for your toolkit.
29 +</Step>
30 +
31 +<Step>
32 +### Configure scopes
33 +
34 +Depending on your authentication method, you may need to configure scopes:
35 +- **OAuth2**: Configure scopes for what data and actions your integration can access.
36 +- **API Key/Bearer Token**: Permissions are typically fixed based on the key's access level.
37 +</Step>
38 +
39 +<Step>
40 +### Authentication Management
41 +
42 +**For OAuth toolkits:**
43 +- **Development/Testing**: Use Composio's managed authentication (no setup required)
44 +- **Production**: Generate your own OAuth credentials from the toolkit's developer portal
45 +
46 +**For custom authentication schemes:**
47 +
48 +You must provide your own credentials regardless of environment.
49 +
50 +<Callout type="info">
51 +Want to remove Composio branding from OAuth screens? See [Custom Auth Configs](/docs/custom-auth-configs#white-labeling-the-oauth-consent-screen) for white-labeling options.
52 +</Callout>
53 +</Step>
54 +
55 +<Step>
56 +### You are all set!
57 +
58 +Click "**Create Auth Configuration**" button and you have completed your first step! Now you can move ahead to authenticating your users by [Connecting an Account](#connecting-an-account).
59 +</Step>
60 +</Steps>
61 +
62 +<Callout type="info" title="Auth configs are reusable">
63 +Auth configs contain your developer credentials and app-level settings (*scopes*, *authentication method*, etc.). Once created, you can reuse the same auth config for all your users.
64 +</Callout>
65 +
66 +### When to create multiple auth configs?
67 +
68 +You should create multiple auth configs for the same toolkit when you need:
69 +
70 +- **Different authentication methods** - One OAuth config and one API key config
71 +- **Different scopes** - Separate configs for read-only vs full access
72 +- **Different OAuth apps** - Using separate client credentials for different environments
73 +- **Different permission levels** - Limiting actions for specific use cases
74 +
75 +<Cards>
76 + <Card title="Programmatic creation" href="/docs/programmatic-auth-configs">
77 + For managing auth configs across multiple projects, you can create them programmatically via the API
78 + </Card>
79 + <Card title="Production white-labeling" href="/docs/custom-auth-configs#white-labeling-the-oauth-consent-screen">
80 + Remove Composio branding from OAuth screens for a fully white-labeled authentication experience
81 + </Card>
82 +</Cards>
83 +
84 +## Connecting an account
85 +
86 +With an auth config created, you're ready to authenticate your users!
87 +
88 +You can either use [**Connect Link**](#hosted-authentication-connect-link) for a hosted authentication flow, or use [**Direct SDK Integration**](#direct-sdk-integration).
89 +
90 +<Callout>
91 +User authentication requires a User ID - a unique identifier that groups connected accounts together. Learn more about [User Management](/docs/user-management) to understand how to structure User IDs for your application.
92 +</Callout>
93 +
94 +**Choose the section below that matches your toolkit's authentication method:**
95 +
96 +### Hosted Authentication (Connect Link)
97 +
98 +Redirect users to a Composio-hosted URL that handles the entire authentication process—OAuth flows, API key collection, or custom fields like subdomain. You can specify a callback URL to control where users return after authentication.
99 +
100 +<Figure
101 + src="/images/auth-screen-example.png"
102 + alt="Connect Link authentication screen"
103 + caption="Connect Link authentication screen"
104 + size="sm"
105 +/>
106 +
107 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
108 + <Tab value="Python">
109 +```python
110 +from composio import Composio
111 +
112 +composio = Composio(api_key="your_api_key")
113 +
114 +# Use the "AUTH CONFIG ID" from your dashboard
115 +auth_config_id = "your_auth_config_id"
116 +
117 +# Use a unique identifier for each user in your application
118 +user_id = 'user-1349-129-12'
119 +
120 +connection_request = composio.connected_accounts.link(
121 + user_id=user_id,
122 + auth_config_id=auth_config_id,
123 + callback_url='https://your-app.com/callback'
124 +)
125 +
126 +redirect_url = connection_request.redirect_url
127 +print(f"Visit: {redirect_url} to authenticate your account")
128 +```
129 + </Tab>
130 + <Tab value="TypeScript">
131 +```typescript
132 +import { Composio } from '@composio/core';
133 +
134 +const composio = new Composio({apiKey: "your_api_key"});
135 +
136 +// Use the "AUTH CONFIG ID" from your dashboard
137 +const authConfigId = 'your_auth_config_id';
138 +
139 +// Use a unique identifier for each user in your application
140 +const userId = 'user-1349-129-12';
141 +
142 +const connectionRequest = await composio.connectedAccounts.link(userId, authConfigId, {
143 + callbackUrl: 'https://your-app.com/callback'
144 +});
145 +const redirectUrl = connectionRequest.redirectUrl;
146 +console.log(`Visit: ${redirectUrl} to authenticate your account`);
147 +```
148 + </Tab>
149 +</Tabs>
150 +
151 +#### Customizing Connect Link
152 +
153 +By default, users will see a Composio-branded authentication experience when connecting their accounts. To customize this interface with your application's branding:
154 +
155 +1. Navigate to your Project Settings and select [Auth Screen](https://platform.composio.dev?next_page=/settings/auth-screen)
156 +2. Configure your **Logo** and **App Title**
157 +
158 +These settings will apply to all authentication flows using Connect Link, providing a white-labeled experience that maintains your brand identity throughout the authentication process.
159 +
160 +<Callout>
161 +For complete white-labeling including OAuth consent screens (removing Composio's domain), see [Custom Auth Configs - White-labeling](/docs/custom-auth-configs#white-labeling-the-oauth-consent-screen).
162 +</Callout>
163 +
164 +### Direct SDK Integration
165 +
166 +**Choose the section below that matches your toolkit's authentication method:**
167 +
168 +#### OAuth Connections
169 +
170 +For OAuth flows, you'll redirect users to complete authorization. You can specify a callback URL to control where users return after authentication:
171 +
172 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
173 + <Tab value="Python">
174 +```python
175 +from composio import Composio
176 +
177 +composio = Composio(api_key="YOUR_COMPOSIO_API_KEY")
178 +
179 +# Use the "AUTH CONFIG ID" from your dashboard
180 +auth_config_id = "your_auth_config_id"
181 +
182 +# Use a unique identifier for each user in your application
183 +user_id = "user-1349-129-12"
184 +
185 +connection_request = composio.connected_accounts.initiate(
186 + user_id=user_id,
187 + auth_config_id=auth_config_id,
188 + config={"auth_scheme": "OAUTH2"},
189 + callback_url="https://www.yourapp.com/callback"
190 +)
191 +print(f"Redirect URL: {connection_request.redirect_url}")
192 +
193 +connected_account = connection_request.wait_for_connection()
194 +
195 +# Alternative: if you only have the connection request ID
196 +# connected_account = composio.connected_accounts.wait_for_connection(
197 +# connection_request.id)
198 +# Recommended when the connection_request object is no longer available
199 +
200 +print(f"Connection established: {connected_account.id}")
201 +```
202 + </Tab>
203 + <Tab value="TypeScript">
204 +```typescript
205 +import { Composio } from '@composio/core';
206 +
207 +const composio = new Composio({apiKey: "YOUR_COMPOSIO_API_KEY"});
208 +
209 +// Use the "AUTH CONFIG ID" from your dashboard
210 +const authConfigId = 'your_auth_config_id';
211 +// Use a unique identifier for each user in your application
212 +const userId = 'user_4567';
213 +
214 +const connRequest = await composio.connectedAccounts.initiate(
215 + userId,
216 + authConfigId,
217 + {
218 + callbackUrl: 'https://www.yourapp.com/callback',
219 + }
220 +);
221 +console.log(`Redirect URL: ${connRequest.redirectUrl}`);
222 +
223 +const connectedAccount = await connRequest.waitForConnection();
224 +
225 +// Alternative: if you only have the connection request ID
226 +// const connectedAccount = await composio.connectedAccounts
227 +// .waitForConnection(connRequest.id);
228 +// Recommended when the connRequest object is no longer available
229 +
230 +console.log(`Connection established: ${connectedAccount.id}`);
231 +```
232 + </Tab>
233 +</Tabs>
234 +
235 +#### Services with Additional Parameters
236 +
237 +Some services like Zendesk require additional parameters such as `subdomain`:
238 +
239 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
240 + <Tab value="Python">
241 +```python
242 +# For Zendesk - include subdomain
243 +connection_request = composio.connected_accounts.initiate(
244 + user_id=user_id,
245 + auth_config_id=auth_config_id,
246 + config=auth_scheme.oauth2(subdomain="mycompany") # For mycompany.zendesk.com
247 +)
248 +```
249 + </Tab>
250 + <Tab value="TypeScript">
251 +```typescript
252 +import { AuthScheme } from '@composio/core';
253 +// For Zendesk - include subdomain
254 +const connRequest = await composio.connectedAccounts.initiate(userId, authConfigId, {
255 + config: AuthScheme.OAuth2({
256 + subdomain: 'mycompany',
257 + }),
258 +});
259 +```
260 + </Tab>
261 +</Tabs>
262 +
263 +#### API Key Connections
264 +
265 +For API key authentication, you can either collect API keys from each user or use your own API key for all users. Popular toolkits that use API keys include Stripe, Perplexity, etc.
266 +
267 +Here is how to initiate the flow:
268 +
269 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
270 + <Tab value="Python">
271 +```python
272 +from composio import Composio
273 +
274 +composio = Composio(api_key="your_api_key")
275 +
276 +# Use the "AUTH CONFIG ID" from your dashboard
277 +auth_config_id = "your_auth_config_id"
278 +
279 +# Use a unique identifier for each user in your application
280 +user_id = "user_12323"
281 +
282 +# API key provided by the user (collected from your app's UI)
283 +# or use your own key
284 +user_api_key = "user_api_key_here"
285 +
286 +connection_request = composio.connected_accounts.initiate(
287 + user_id=user_id,
288 + auth_config_id=auth_config_id,
289 + config={
290 + "auth_scheme": "API_KEY", "val": {"api_key": user_api_key}
291 + }
292 +)
293 +
294 +print(f"Connection established: {connection_request.id}")
295 +```
296 + </Tab>
297 + <Tab value="TypeScript">
298 +```typescript
299 +import { Composio, AuthScheme } from '@composio/core';
300 +
301 +const composio = new Composio({ apiKey: 'your_api_key' });
302 +
303 +// Use the "AUTH CONFIG ID" from your dashboard
304 +const authConfigId = 'your_auth_config_id';
305 +// Use a unique identifier for each user in your application
306 +const userId = 'user12345678';
307 +// API key provided by the user (collected from your app's UI)
308 +const userApiKey = 'user_api_key_here';
309 +
310 +const connectionRequest = await composio.connectedAccounts.initiate(userId, authConfigId, {
311 + config: AuthScheme.APIKey({
312 + api_key: userApiKey,
313 + }),
314 +});
315 +
316 +console.log(`Connection established: ${connectionRequest.id}`);
317 +```
318 + </Tab>
319 +</Tabs>
320 +
321 +## Fetching the required config parameters for an Auth Config
322 +
323 +When working with any toolkit, you can inspect an auth config to understand its authentication requirements and expected parameters.
324 +
325 +Here is how you would fetch the authentication method and input fields:
326 +
327 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
328 + <Tab value="Python">
329 +```python
330 +from composio import Composio
331 +
332 +composio = Composio(api_key="your_api_key")
333 +
334 +# Use the "AUTH CONFIG ID" from your dashboard
335 +auth_config_id = "your_auth_config_id"
336 +
337 +# Fetch the auth configuration details
338 +auth_config = composio.auth_configs.get(auth_config_id)
339 +
340 +# Check what authentication method this config uses
341 +print(f"Authentication method: {auth_config.auth_scheme}")
342 +
343 +# See what input fields are required
344 +print(f"Required fields: {auth_config.expected_input_fields}")
345 +```
346 + </Tab>
347 + <Tab value="TypeScript">
348 +```typescript
349 +import { Composio } from '@composio/core';
350 +
351 +const composio = new Composio({ apiKey: 'your_api_key' });
352 +
353 +// Use the "AUTH CONFIG ID" from your dashboard
354 +const authConfigId = 'your_auth_config_id';
355 +
356 +// Fetch the auth configuration details
357 +const authConfig = await composio.authConfigs.get(authConfigId);
358 +
359 +console.log(`Authentication method: ${authConfig.authScheme}`);
360 +console.log(`Required fields:`, authConfig.expectedInputFields);
361 +```
362 + </Tab>
363 +</Tabs>
364 +
365 +## Other Authentication Methods
366 +
367 +Composio also supports a wide range of other auth schemas:
368 +
369 +**Bearer Token** - Similar to API keys, provide the user's bearer token directly when creating the connection.
370 +
371 +**Basic Auth** - Provide username and password credentials for services that use HTTP Basic Authentication.
372 +
373 +**Custom Schemes** - Some toolkits use their own custom authentication methods. Follow the toolkit-specific requirements for such cases.
374 +
375 +<Callout title="Fetching auth config">
376 +For any of these methods, [fetch the config parameter](#fetching-the-required-config-parameters-for-an-auth-config) to determine the exact fields required. Every toolkit has its own requirements, and understanding these is essential for successfully creating connections.
377 +</Callout>
378 +
379 +Learn how to [Manage connected accounts](/docs/connected-accounts) after users authenticate.
380 +
381 +## Connection Statuses
382 +
383 +After creating a connection, it will have one of the following statuses that indicates its current state:
384 +
385 +| Status | Description |
386 +|--------|-------------|
387 +| **ACTIVE** | Connection is established and working. You can execute tools with this connection. |
388 +| **INACTIVE** | Connection is temporarily disabled. Re-enable it to use the connection again. |
389 +| **PENDING** | Connection is being processed. Wait for it to become active. |
390 +| **INITIATED** | Connection request has started but not yet completed. User may still need to complete authentication. |
391 +| **EXPIRED** | Connection credentials have expired. Composio automatically attempts to refresh credentials before marking as expired. Re-authenticate to restore access. |
392 +| **FAILED** | Connection attempt failed. Check error details and try creating a new connection. |
393 +
394 +<Callout>
395 +When credentials expire for OAuth connections, Composio automatically attempts to refresh them using the refresh token. The connection is only marked as **EXPIRED** after multiple refresh attempts have failed.
396 +</Callout>
397 +
398 +### Waiting for Connection Establishment
399 +
400 +The `waitForConnection` method allows you to poll for a connection to become active after initiating authentication. This is useful when you need to ensure a connection is ready before proceeding.
401 +
402 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
403 + <Tab value="Python">
404 +```python
405 +# Wait for the connection to be established
406 +connected_account = connection_request.wait_for_connection()
407 +print(connected_account.id)
408 +
409 +# Alternative: Wait with custom timeout
410 +# connected_account = connection_request.wait_for_connection(120) # 2 minute timeout
411 +
412 +# Alternative: If you only have the connection request ID (e.g., stored in database)
413 +# connection_id = connection_request.id # You can store this ID in your database
414 +# connected_account = composio.connected_accounts.wait_for_connection(connection_id, 60)
415 +```
416 + </Tab>
417 + <Tab value="TypeScript">
418 +```typescript
419 +// Wait for the connection to be established
420 +const connectedAccount = await connectionRequest.waitForConnection();
421 +console.log(connectedAccount.id);
422 +
423 +// Alternative: Wait with custom timeout
424 +// const connectedAccount = await connectionRequest.waitForConnection(120000); // 2 minutes
425 +
426 +// Alternative: If you only have the connection request ID (e.g., stored in database)
427 +// const connectionId = connectionRequest.id; // You can store this ID in your database
428 +// const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionId, 60000);
429 +```
430 + </Tab>
431 +</Tabs>
432 +
433 +The method continuously polls the Composio API until the connection:
434 +- Becomes **ACTIVE** (returns the connected account)
435 +- Enters a terminal state like **FAILED** or **EXPIRED** (throws an error)
436 +- Exceeds the specified timeout (throws a timeout error)
437 +
438 +### Checking Connection Status
439 +
440 +You can check the status of a connected account programmatically:
441 +
442 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
443 + <Tab value="Python">
444 +```python
445 +# Get a specific connected account
446 +connected_account = composio.connected_accounts.get("your_connected_account_id")
447 +print(f"Status: {connected_account.status}")
448 +
449 +# Filter connections by user_id, auth_config_id, and status (only active accounts)
450 +filtered_connections = composio.connected_accounts.list(
451 + user_ids=["user_123"],
452 + auth_config_ids=["your_auth_config_id"],
453 + statuses=["ACTIVE"]
454 +)
455 +for connection in filtered_connections.items:
456 + print(f"{connection.id}: {connection.status}")
457 +```
458 + </Tab>
459 + <Tab value="TypeScript">
460 +```typescript
461 +// Get a specific connected account by its nanoid
462 +const connectedAccount = await composio.connectedAccounts.get('your_connected_account_id');
463 +console.log(`Status: ${connectedAccount.status}`);
464 +
465 +// Filter connections by user_id, auth_config_id, and status (only active accounts)
466 +const filteredConnections = await composio.connectedAccounts.list({
467 + userIds: ['user_123'],
468 + authConfigIds: ['your_auth_config_id'],
469 + statuses: ['ACTIVE']
470 +});
471 +filteredConnections.items.forEach(connection => {
472 + console.log(`${connection.id}: ${connection.status}`);
473 +});
474 +```
475 + </Tab>
476 +</Tabs>
477 +
478 +<Callout>
479 +Only connections with **ACTIVE** status can be used to execute tools. If a connection is in any other state, you'll need to take appropriate action (re-authenticate, wait for processing, etc.) before using it.
480 +</Callout>
481 +
482 +## Next Step
483 +
484 +With authentication set up, you can now fetch and execute tools. See [Executing Tools](/docs/executing-tools) to get started.
fumadocs/content/docs/custom-tools.mdx new
+344
@@ -0,0 +1,344 @@
1 +---
2 +title: Creating Custom Tools
3 +description: Learn how to extend Composio's toolkits with your own tools
4 +---
5 +
6 +Custom tools allow you to create your own tools that can be used with Composio.
7 +
8 +1. **Standalone tools** - Simple tools that don't require any authentication
9 +2. **Toolkit-based tools** - Tools that require authentication and can use toolkit credentials
10 +
11 +## Creating a Custom Tool
12 +
13 +### Standalone Tool
14 +
15 +A standalone tool is the simplest form of custom tool. It only requires input parameters and an execute function:
16 +
17 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
18 + <Tab value="Python">
19 +```python
20 +from pydantic import BaseModel, Field
21 +
22 +from composio import Composio
23 +from composio.types import ExecuteRequestFn
24 +
25 +composio = Composio()
26 +
27 +
28 +class AddTwoNumbersInput(BaseModel):
29 + a: int = Field(
30 + ...,
31 + description="The first number to add",
32 + )
33 + b: int = Field(
34 + ...,
35 + description="The second number to add",
36 + )
37 +
38 +# function name will be used as slug
39 +@composio.tools.custom_tool
40 +def add_two_numbers(request: AddTwoNumbersInput) -> int:
41 + """Add two numbers."""
42 + return request.a + request.b
43 +```
44 + </Tab>
45 + <Tab value="TypeScript">
46 +```typescript
47 +const tool = await composio.tools.createCustomTool({
48 + slug: 'CALCULATE_SQUARE',
49 + name: 'Calculate Square',
50 + description: 'Calculates the square of a number',
51 + inputParams: z.object({
52 + number: z.number().describe('The number to calculate the square of'),
53 + }),
54 + execute: async input => {
55 + const { number } = input;
56 + return {
57 + data: { result: number * number },
58 + error: null,
59 + successful: true,
60 + };
61 + },
62 +});
63 +```
64 + </Tab>
65 +</Tabs>
66 +
67 +### Toolkit-based Tool
68 +
69 +A toolkit-based tool has access to two ways of making authenticated requests:
70 +
71 +**1. Using `executeToolRequest`** - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection and baseURL resolution:
72 +
73 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
74 + <Tab value="Python">
75 +```python
76 +class GetIssueInfoInput(BaseModel):
77 + issue_number: int = Field(
78 + ...,
79 + description="The number of the issue to get information about",
80 + )
81 +
82 +# function name will be used as slug
83 +@composio.tools.custom_tool(toolkit="github")
84 +def get_issue_info(
85 + request: GetIssueInfoInput,
86 + execute_request: ExecuteRequestFn,
87 + auth_credentials: dict,
88 +) -> dict:
89 + """Get information about a GitHub issue."""
90 + response = execute_request(
91 + endpoint=f"/repos/composiohq/composio/issues/{request.issue_number}",
92 + method="GET",
93 + parameters=[
94 + {
95 + "name": "Accept",
96 + "value": "application/vnd.github.v3+json",
97 + "type": "header",
98 + },
99 + {
100 + "name": "Authorization",
101 + "value": f"Bearer {auth_credentials['access_token']}",
102 + "type": "header",
103 + },
104 + ],
105 + )
106 + return {"data": response.data}
107 +```
108 + </Tab>
109 + <Tab value="TypeScript">
110 +```typescript
111 +const tool = await composio.tools.createCustomTool({
112 + slug: 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY',
113 + name: 'Github star composio repositories',
114 + toolkitSlug: 'github',
115 + description: 'Star any specified repo of `composiohq` user',
116 + inputParams: z.object({
117 + repository: z.string().describe('The repository to star'),
118 + page: z.number().optional().describe('Pagination page number'),
119 + customHeader: z.string().optional().describe('Custom header'),
120 + }),
121 + execute: async (input, connectionConfig, executeToolRequest) => {
122 + // This method makes authenticated requests to the relevant API
123 + // You can use relative paths!
124 + // Composio will automatically inject the baseURL
125 + const result = await executeToolRequest({
126 + endpoint: `/user/starred/composiohq/${input.repository}`,
127 + method: 'PUT',
128 + body: {},
129 + // Add custom headers or query parameters
130 + parameters: [
131 + // Add query parameters
132 + {
133 + name: 'page',
134 + value: input.page?.toString() || '1',
135 + in: 'query',
136 + },
137 + // Add custom headers
138 + {
139 + name: 'x-custom-header',
140 + value: input.customHeader || 'default-value',
141 + in: 'header',
142 + },
143 + ],
144 + });
145 + return result;
146 + },
147 +});
148 +```
149 + </Tab>
150 +</Tabs>
151 +
152 +**2. Using `connectionConfig`** - For making direct API calls when needed:
153 +
154 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
155 + <Tab value="Python">
156 +```python
157 +import requests
158 +
159 +@composio.tools.custom_tool(toolkit="github")
160 +def get_issue_info_direct(
161 + request: GetIssueInfoInput,
162 + execute_request: ExecuteRequestFn,
163 + auth_credentials: dict,
164 +) -> dict:
165 + """Get information about a GitHub issue."""
166 + response = requests.get(
167 + f"https://api.github.com/repos/composiohq/composio/issues/{request.issue_number}",
168 + headers={
169 + "Accept": "application/vnd.github.v3+json",
170 + "Authorization": f"Bearer {auth_credentials['access_token']}",
171 + },
172 + )
173 + return {"data": response.json()}
174 +```
175 + </Tab>
176 + <Tab value="TypeScript">
177 +```typescript
178 +const tool = await composio.tools.createCustomTool({
179 + slug: 'GITHUB_DIRECT_API',
180 + name: 'Direct GitHub API Call',
181 + description: 'Makes direct calls to GitHub API',
182 + toolkitSlug: 'github',
183 + inputParams: z.object({
184 + repo: z.string().describe('Repository name'),
185 + }),
186 + execute: async (input, connectionConfig, executeToolRequest) => {
187 + // Use connectionConfig for direct API calls
188 + const result = await fetch(`https://api.github.com/repos/${input.repo}`, {
189 + headers: {
190 + Authorization: `Bearer ${connectionConfig.access_token}`,
191 + },
192 + });
193 +
194 + return {
195 + data: await result.json(),
196 + error: null,
197 + successful: true,
198 + };
199 + },
200 +});
201 +```
202 + </Tab>
203 +</Tabs>
204 +
205 +### Using Custom Headers and Query Parameters
206 +
207 +You can add custom headers and query parameters to your toolkit-based tools using the `parameters` option in `executeToolRequest`:
208 +
209 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
210 + <Tab value="Python">
211 +```python
212 +@composio.tools.custom_tool(toolkit="github")
213 +def get_issue_info(
214 + request: GetIssueInfoInput,
215 + execute_request: ExecuteRequestFn,
216 + auth_credentials: dict,
217 +) -> dict:
218 + """Get information about a GitHub issue."""
219 + response = execute_request(
220 + endpoint=f"/repos/composiohq/composio/issues/{request.issue_number}",
221 + method="GET",
222 + parameters=[
223 + {
224 + "name": "Accept",
225 + "value": "application/vnd.github.v3+json",
226 + "type": "header",
227 + },
228 + {
229 + "name": "Authorization",
230 + "value": f"Bearer {auth_credentials['access_token']}",
231 + "type": "header",
232 + },
233 + {
234 + "name": 'X-Custom-Header',
235 + "value": 'custom-value',
236 + "type": 'header',
237 + },
238 + ],
239 + )
240 + return {"data": response.data}
241 +```
242 + </Tab>
243 + <Tab value="TypeScript">
244 +```typescript
245 +const tool = await composio.tools.createCustomTool({
246 + slug: 'GITHUB_SEARCH_REPOSITORIES',
247 + name: 'Search GitHub Repositories',
248 + description: 'Search for repositories with custom parameters',
249 + toolkitSlug: 'github',
250 + inputParams: z.object({
251 + query: z.string().describe('Search query'),
252 + perPage: z.number().optional().describe('Results per page'),
253 + acceptType: z.string().optional().describe('Custom accept header'),
254 + }),
255 + execute: async (input, connectionConfig, executeToolRequest) => {
256 + const result = await executeToolRequest({
257 + endpoint: '/search/repositories',
258 + method: 'GET',
259 + parameters: [
260 + // Add query parameters for pagination
261 + {
262 + name: 'q',
263 + value: input.query,
264 + in: 'query',
265 + },
266 + {
267 + name: 'per_page',
268 + value: (input.perPage || 30).toString(),
269 + in: 'query',
270 + },
271 + // Add custom headers
272 + {
273 + name: 'Accept',
274 + value: input.acceptType || 'application/vnd.github.v3+json',
275 + in: 'header',
276 + },
277 + {
278 + name: 'X-Custom-Header',
279 + value: 'custom-value',
280 + in: 'header',
281 + },
282 + ],
283 + });
284 + return result;
285 + },
286 +});
287 +```
288 + </Tab>
289 +</Tabs>
290 +
291 +## Executing Custom Tools
292 +
293 +You can execute custom tools just like any other tool:
294 +
295 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
296 + <Tab value="Python">
297 +```python
298 +response = composio.tools.execute(
299 + user_id="default",
300 + slug="TOOL_SLUG", # For the tool above you can use `get_issue_info.slug`
301 + arguments={"issue_number": 1},
302 +)
303 +```
304 + </Tab>
305 + <Tab value="TypeScript">
306 +```typescript
307 +const result = await composio.tools.execute('TOOL_SLUG', {
308 + arguments: {
309 + // Tool input parameters
310 + },
311 + userId: 'user-id',
312 + connectedAccountId: 'optional-account-id', // Required for toolkit-based tools
313 +});
314 +```
315 + </Tab>
316 +</Tabs>
317 +
318 +## Best Practices
319 +
320 +1. Use descriptive names and slugs for your tools
321 +2. Always provide descriptions for input parameters using `describe()`
322 +3. Handle errors gracefully in your execute function
323 +4. For toolkit-based tools:
324 + - Prefer `executeToolRequest` over direct API calls when possible
325 + - Use relative paths with `executeToolRequest` - Composio will automatically inject the correct baseURL
326 + - Use the `parameters` option to add custom headers or query parameters:
327 + ```typescript
328 + parameters: [
329 + { name: 'page', value: '1', in: 'query' }, // Adds ?page=1 to URL
330 + { name: 'x-custom', value: 'value', in: 'header' }, // Adds header
331 + ];
332 + ```
333 + - Remember that `executeToolRequest` can only call tools from the same toolkit
334 + - Use `executeToolRequest` to leverage Composio's automatic credential handling
335 + - Only use `connectionConfig` when you need to make direct API calls or interact with different services
336 +5. Chain multiple toolkit operations using `executeToolRequest` for better maintainability
337 +
338 +## Limitations
339 +
340 +1. Custom tools are stored in memory and are not persisted
341 +2. They need to be recreated when the application restarts
342 +3. Toolkit-based tools require a valid connected account with the specified toolkit
343 +4. `executeToolRequest` can only execute tools from the same toolkit that the custom tool belongs to
344 +5. Each toolkit-based tool can only use one connected account at a time
fumadocs/content/docs/executing-tools.mdx new
+384
@@ -0,0 +1,384 @@
1 +---
2 +title: Executing Tools
3 +description: Learn how to execute Composio tools with different providers and frameworks
4 +---
5 +
6 +LLMs on their own can only do generation. Tool calling changes that by letting them interact with external services. Instead of just drafting an email, the model can call `GMAIL_SEND_EMAIL` to actually send it. The tool's results feed back to the LLM, closing the loop so it can decide, act, observe, and adapt.
7 +
8 +In Composio, every **tool** is a single API action—fully described with schema, parameters, and return type. Tools live inside **toolkits** like Gmail, Slack, or GitHub, and Composio handles authentication and user scoping.
9 +
10 +<Callout type="info">
11 +**User Scoping**: All tools are scoped to a specific user - that's why every example includes a `user_id`. Learn how to structure User IDs in [User Management](/docs/user-management). Each user must authenticate with their respective services (Gmail, Calendar, etc.) - see [Authentication](/docs/authenticating-tools).
12 +</Callout>
13 +
14 +## Using Chat Completions
15 +
16 +Use the Composio SDK with providers like OpenAI, Anthropic, and Google AI. To learn how to set up these providers, see [Providers](/providers/openai).
17 +
18 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
19 + <Tab value="Python">
20 +```python
21 +from composio import Composio
22 +from composio_openai import OpenAIProvider
23 +from openai import OpenAI
24 +from datetime import datetime
25 +
26 +# Use a unique identifier for each user in your application
27 +user_id = "user-k7334"
28 +
29 +# Create composio client
30 +composio = Composio(provider=OpenAIProvider(), api_key="your_composio_api_key")
31 +
32 +# Create openai client
33 +openai = OpenAI()
34 +
35 +# Get calendar tools for this user
36 +tools = composio.tools.get(
37 + user_id=user_id,
38 + tools=["GOOGLECALENDAR_EVENTS_LIST"]
39 +)
40 +
41 +# Ask the LLM to check calendar
42 +result = openai.chat.completions.create(
43 + model="gpt-4o-mini",
44 + tools=tools,
45 + messages=[
46 + {"role": "system", "content": "You are a helpful assistant."},
47 + {"role": "user", "content": f"What's on my calendar for the next 7 days?"}
48 + ]
49 +)
50 +
51 +# Handle tool calls
52 +result = composio.provider.handle_tool_calls(user_id=user_id, response=result)
53 +print(result)
54 +```
55 + </Tab>
56 + <Tab value="TypeScript">
57 +```typescript
58 +import { Composio } from '@composio/core';
59 +import { AnthropicProvider } from '@composio/anthropic';
60 +import { Anthropic } from '@anthropic-ai/sdk';
61 +
62 +// Use a unique identifier for each user in your application
63 +const userId = 'user-k7334';
64 +
65 +// Create anthropic client
66 +const anthropic = new Anthropic();
67 +
68 +// Create Composio client
69 +const composio = new Composio({
70 + apiKey: "your-composio-api-key",
71 + provider: new AnthropicProvider(),
72 +});
73 +
74 +// Get calendar tools for this user
75 +const tools = await composio.tools.get(userId, {
76 + tools: ['GOOGLECALENDAR_EVENTS_LIST'],
77 +});
78 +
79 +// Ask the LLM to check calendar
80 +const msg = await anthropic.messages.create({
81 + model: 'claude-sonnet-4-20250514',
82 + tools: tools,
83 + messages: [
84 + {
85 + role: 'user',
86 + content: `What's on my calendar for the next 7 days?`,
87 + },
88 + ],
89 + max_tokens: 1024,
90 +});
91 +
92 +// Handle tool calls
93 +const result = await composio.provider.handleToolCalls(userId, msg);
94 +console.log('Results:', JSON.stringify(result, null, 2));
95 +```
96 + </Tab>
97 +</Tabs>
98 +
99 +## Using Agentic Frameworks
100 +
101 +Agentic frameworks automatically handle the tool execution loop. Composio provides support for frameworks like this by making sure the tools are formatted into the correct objects for the agentic framework to execute.
102 +
103 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
104 + <Tab value="Python">
105 +```python
106 +import asyncio
107 +from agents import Agent, Runner
108 +from composio import Composio
109 +from composio_openai_agents import OpenAIAgentsProvider
110 +
111 +# Use a unique identifier for each user in your application
112 +user_id = "user-k7334"
113 +
114 +# Initialize Composio toolset
115 +composio = Composio(provider=OpenAIAgentsProvider(), api_key="your_composio_api_key")
116 +
117 +# Get all tools for the user
118 +tools = composio.tools.get(
119 + user_id=user_id,
120 + toolkits=["COMPOSIO_SEARCH"],
121 +)
122 +
123 +# Create an agent with the tools
124 +agent = Agent(
125 + name="Deep Researcher",
126 + instructions="You are an investigative journalist.",
127 + tools=tools,
128 +)
129 +
130 +async def main():
131 + result = await Runner.run(
132 + starting_agent=agent,
133 + input=("Do a thorough DEEP research on Golden Gate Bridge"),
134 + )
135 + print(result.final_output)
136 +
137 +# Run the agent
138 +asyncio.run(main())
139 +```
140 + </Tab>
141 + <Tab value="TypeScript">
142 +```typescript
143 +import { Composio } from '@composio/core';
144 +import { generateText } from 'ai';
145 +import { anthropic } from '@ai-sdk/anthropic';
146 +import { VercelProvider } from '@composio/vercel';
147 +
148 +// Use a unique identifier for each user in your application
149 +const userId = 'user-k7334';
150 +
151 +// Initialize Composio toolset
152 +const composio = new Composio({
153 + apiKey: process.env.COMPOSIO_API_KEY,
154 + provider: new VercelProvider(),
155 +});
156 +
157 +// Get all tools for the user
158 +const tools = await composio.tools.get(userId, {
159 + toolkits: ['HACKERNEWS_GET_LATEST_POSTS'],
160 + limit: 10,
161 +});
162 +
163 +// Generate text with tool use
164 +const { text } = await generateText({
165 + model: anthropic('claude-sonnet-4-20250514'),
166 + messages: [
167 + {
168 + role: 'user',
169 + content: 'Do a thorough DEEP research on the top articles on Hacker News about Composio',
170 + },
171 + ],
172 + tools,
173 +});
174 +
175 +console.log(text);
176 +```
177 + </Tab>
178 +</Tabs>
179 +
180 +## Direct Tool Execution
181 +
182 +If you just want to call a tool without using any framework or LLM provider, you can use the `execute` method directly.
183 +
184 +<Callout type="info">
185 +**Finding tool parameters and types:**
186 +
187 +**Platform UI**: [Auth Configs](https://platform.composio.dev?next_page=/auth-configs) → Select your toolkit → Tools & Triggers → Select the tool to see its required and optional parameters
188 +
189 +**CLI**: For Python and TypeScript projects, run `composio generate` to generate types. [Learn more →](/docs/cli#generate-type-definitions)
190 +</Callout>
191 +
192 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
193 + <Tab value="Python">
194 +```python
195 +from composio import Composio
196 +
197 +user_id = "user-k7334"
198 +# Configure toolkit versions at SDK level
199 +composio = Composio(
200 + api_key="your_composio_key",
201 + toolkit_versions={"github": "20251027_00"}
202 +)
203 +
204 +# Find available arguments for any tool in the Composio dashboard
205 +result = composio.tools.execute(
206 + "GITHUB_LIST_STARGAZERS",
207 + user_id=user_id,
208 + arguments={"owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5}
209 +)
210 +print(result)
211 +```
212 + </Tab>
213 + <Tab value="TypeScript">
214 +```typescript
215 +import { Composio } from "@composio/core";
216 +
217 +const userId = "user-k7334";
218 +// Configure toolkit versions at SDK level
219 +const composio = new Composio({
220 + apiKey: "your_composio_key",
221 + toolkitVersions: { github: "20251027_00" }
222 +});
223 +
224 +// Find available arguments for any tool in the Composio dashboard
225 +const result = await composio.tools.execute("GITHUB_LIST_STARGAZERS", {
226 + userId,
227 + arguments: {
228 + "owner": "ComposioHQ",
229 + "repo": "composio",
230 + "page": 1,
231 + "per_page": 5
232 + },
233 +});
234 +console.log('GitHub stargazers:', JSON.stringify(result, null, 2));
235 +```
236 + </Tab>
237 +</Tabs>
238 +
239 +<Callout>
240 +The examples above configure toolkit versions at SDK initialization. You can also pass versions per-execution or use environment variables. See [toolkit versioning](/docs/toolkit-versioning) for all configuration options.
241 +</Callout>
242 +
243 +### Proxy Execute
244 +
245 +You can proxy requests to any supported toolkit API and let Composio inject the authentication state. This is useful when you need an API endpoint that isn't available as a predefined tool.
246 +
247 +The `endpoint` can be a relative path or absolute URL. Composio uses the `connected_account_id` to determine the toolkit and resolve relative paths against the appropriate base URL.
248 +
249 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
250 + <Tab value="Python">
251 +```python
252 +# Send a proxy request to the endpoint
253 +response = composio.tools.proxy(
254 + endpoint="/repos/composiohq/composio/issues/1",
255 + method="GET",
256 + connected_account_id="ca_jI6********", # use connected account for github
257 + parameters=[
258 + {
259 + "name": "Accept",
260 + "value": "application/vnd.github.v3+json",
261 + "type": "header",
262 + },
263 + ],
264 +)
265 +
266 +print(response)
267 +```
268 + </Tab>
269 + <Tab value="TypeScript">
270 +```typescript
271 +// Send a proxy request to the endpoint
272 +const { data } = await composio.tools.proxyExecute({
273 + endpoint:'/repos/composiohq/composio/issues/1',
274 + method: 'GET',
275 + connectedAccountId: 'ca_jI*****', // use connected account for github
276 + parameters:[
277 + {
278 + "name": "Accept",
279 + "value": "application/vnd.github.v3+json",
280 + "in": "header",
281 + },
282 + ],
283 +});
284 +
285 +console.log(data);
286 +```
287 + </Tab>
288 +</Tabs>
289 +
290 +<Callout type="info">
291 +Need an API that isn't supported by any Composio toolkit, or want to extend an existing one? Learn how to [create custom tools](/docs/custom-tools).
292 +</Callout>
293 +
294 +## Automatic File Handling
295 +
296 +Composio handles file operations automatically. Pass file paths to tools that need them, and get local file paths back from tools that return files.
297 +
298 +### File Upload
299 +
300 +Pass local file paths, URLs, or File objects to tools that accept files:
301 +
302 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
303 + <Tab value="Python">
304 +```python
305 +# Upload a local file to Google Drive
306 +result = composio.tools.execute(
307 + slug="GOOGLEDRIVE_UPLOAD_FILE",
308 + user_id="user-1235***",
309 + arguments={"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},
310 +)
311 +
312 +print(result) # Print Google Drive file details
313 +```
314 + </Tab>
315 + <Tab value="TypeScript">
316 +```typescript
317 +// Upload a local file to Google Drive
318 +const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
319 + userId: 'user-4235***',
320 + arguments: {
321 + file_to_upload: path.join(__dirname, 'document.pdf')
322 + }
323 +});
324 +
325 +console.log(result.data); // Contains Google Drive file details
326 +```
327 + </Tab>
328 +</Tabs>
329 +
330 +### File Download
331 +
332 +When tools return files, Composio downloads them to the local directory and provides the file path in the response:
333 +
334 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
335 + <Tab value="Python">
336 +```python
337 +composio = Composio(
338 + api_key="your_composio_key",
339 + file_download_dir="./downloads" # Optional: Specify download directory
340 +)
341 +
342 +result = composio.tools.execute(
343 + "GOOGLEDRIVE_DOWNLOAD_FILE",
344 + user_id="user-1235***",
345 + arguments={"file_id": "your_file_id"},
346 +)
347 +
348 +# Result includes local file path
349 +print(result)
350 +```
351 + </Tab>
352 + <Tab value="TypeScript">
353 +```typescript
354 +// Download a file from Google Drive
355 +const result = await composio.tools.execute('GOOGLEDRIVE_DOWNLOAD_FILE', {
356 + userId: 'user-1235***',
357 + arguments: {
358 + file_id: 'your-file-id'
359 + }
360 + });
361 +
362 +// Result includes local file path
363 +console.log(result);
364 +```
365 + </Tab>
366 +</Tabs>
367 +
368 +### Disabling Auto File Handling
369 +
370 +You can disable automatic file handling when initializing the TypeScript SDK. When disabled, handle file uploads and downloads manually using `files.upload` and `files.download`:
371 +
372 +```typescript
373 +const composio = new Composio({
374 + apiKey: process.env.COMPOSIO_API_KEY,
375 + autoUploadDownloadFiles: false
376 +});
377 +
378 +// Now you need to handle files manually using composio.files API
379 +const fileData = await composio.files.upload({
380 + filePath: path.join(__dirname, 'document.pdf'),
381 + toolSlug: 'GOOGLEDRIVE_UPLOAD_FILE',
382 + toolkitSlug: 'googledrive'
383 +});
384 +```
fumadocs/content/docs/meta.json
+7 -1
@@ -5,6 +5,12 @@
5 "quickstart",
6 "capabilities",
7 "---Tools and Triggers---",
8 - "fetching-tools"
8 + "fetching-tools",
9 + "authenticating-tools",
10 + "executing-tools",
11 + "using-triggers",
12 + "modify-tool-behavior",
13 + "custom-tools",
14 + "toolkit-versioning"
15 ]
16 }
fumadocs/content/docs/modify-tool-behavior/after-execution-modifiers.mdx new
+177
@@ -0,0 +1,177 @@
1 +---
2 +title: After Execution Modifiers
3 +description: Transform tool results after execution
4 +---
5 +
6 +After execution modifiers are part of Composio SDK's powerful middleware capabilities that allow you to customize and extend the behavior of tools.
7 +
8 +These modifiers are called after the tool is executed. This allows you to modify the result of the tool before it is returned to the agent.
9 +
10 +**Useful for:**
11 +- Modifying or truncating the output of the tool
12 +- Converting the output to a different format before returning it to the agent
13 +
14 +<Figure src="/images/after-execute.png" alt="After Execution Modifier" />
15 +
16 +<Callout>
17 +Below we use the `afterExecute` modifier to truncate the output of `HACKERNEWS_GET_USER` and only return the karma of the user.
18 +</Callout>
19 +
20 +## With Chat Completions
21 +
22 +Since completion providers don't have a function execution step, Composio executes the tool call directly. The modifier is configured on the `tools.execute` method.
23 +
24 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
25 + <Tab value="Python">
26 +```python
27 +from composio import Composio, after_execute
28 +from composio.types import ToolExecutionResponse
29 +
30 +@after_execute(tools=["HACKERNEWS_GET_USER"])
31 +def after_execute_modifier(
32 + tool: str,
33 + toolkit: str,
34 + response: ToolExecutionResponse,
35 +) -> ToolExecutionResponse:
36 + return {
37 + **response,
38 + "data": {
39 + "karma": response["data"]["karma"],
40 + },
41 + }
42 +
43 +tools = composio.tools.get(user_id=user_id, slug="HACKERNEWS_GET_USER")
44 +
45 +# Get response from the LLM
46 +response = openai_client.chat.completions.create(
47 + model="gpt-4o-mini",
48 + tools=tools,
49 + messages=messages,
50 +)
51 +print(response)
52 +
53 +# Execute the function calls
54 +result = composio.provider.handle_tool_calls(
55 + response=response,
56 + user_id="default",
57 + modifiers=[
58 + after_execute_modifier,
59 + ]
60 +)
61 +print(result)
62 +```
63 + </Tab>
64 + <Tab value="TypeScript">
65 +```typescript
66 +const response = await openai.chat.completions.create({
67 + model: "gpt-4o-mini",
68 + messages,
69 + tools,
70 + tool_choice: "auto",
71 +});
72 +
73 +const { tool_calls } = response.choices[0].message;
74 +console.log(tool_calls);
75 +
76 +if (tool_calls) {
77 + const {
78 + function: { arguments: toolArgs },
79 + } = tool_calls[0];
80 +
81 + const result = await composio.tools.execute(
82 + "HACKERNEWS_GET_USER",
83 + {
84 + userId,
85 + arguments: JSON.parse(toolArgs),
86 + },
87 + {
88 + afterExecute: ({ toolSlug, toolkitSlug, result }) => {
89 + if (toolSlug === "HACKERNEWS_GET_USER") {
90 + const { data } = result;
91 + const { karma } = data.response_data as { karma: number };
92 + return {
93 + ...result,
94 + data: { karma },
95 + };
96 + }
97 + return result;
98 + },
99 + }
100 + );
101 + console.log(JSON.stringify(result, null, 2));
102 +}
103 +```
104 + </Tab>
105 +</Tabs>
106 +
107 +## With Agentic Frameworks
108 +
109 +Agentic providers have a function execution step. The modifier is configured on the `tools.get` method which modifies the execution logic within the framework.
110 +
111 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
112 + <Tab value="Python">
113 +```python
114 +from composio import Composio, after_execute
115 +from composio.types import ToolExecutionResponse
116 +from composio_crewai import CrewAIProvider
117 +
118 +composio = Composio(provider=CrewAIProvider())
119 +
120 +@after_execute(tools=["HACKERNEWS_GET_USER"])
121 +def after_execute_modifier(
122 + tool: str,
123 + toolkit: str,
124 + response: ToolExecutionResponse,
125 +) -> ToolExecutionResponse:
126 + return {
127 + **response,
128 + "data": {
129 + "karma": response["data"]["karma"],
130 + },
131 + }
132 +
133 +tools = composio.tools.get(
134 + user_id="default",
135 + slug="HACKERNEWS_GET_USER",
136 + modifiers=[
137 + after_execute_modifier,
138 + ]
139 +)
140 +```
141 + </Tab>
142 + <Tab value="TypeScript">
143 +```typescript
144 +import { Composio } from "@composio/core";
145 +import { VercelProvider } from "@composio/vercel";
146 +import { v4 as uuidv4 } from "uuid";
147 +
148 +const composio = new Composio({
149 + apiKey: process.env.COMPOSIO_API_KEY,
150 + provider: new VercelProvider(),
151 +});
152 +
153 +const userId = uuidv4();
154 +
155 +const agenticTools = await composio.tools.get(
156 + userId,
157 + {
158 + tools: ["HACKERNEWS_GET_USER"],
159 + },
160 + {
161 + afterExecute: ({ toolSlug, toolkitSlug, result }) => {
162 + if (toolSlug === "HACKERNEWS_GET_USER") {
163 + const {
164 + data: { response_data: { karma } = {} } = {},
165 + } = result;
166 + return {
167 + ...result,
168 + data: { karma },
169 + };
170 + }
171 + return result;
172 + },
173 + }
174 +);
175 +```
176 + </Tab>
177 +</Tabs>
fumadocs/content/docs/modify-tool-behavior/before-execution-modifiers.mdx new
+172
@@ -0,0 +1,172 @@
1 +---
2 +title: Before Execution Modifiers
3 +description: Modify tool arguments before execution
4 +---
5 +
6 +Before execution modifiers are part of Composio SDK's powerful middleware capabilities that allow you to customize and extend the behavior of tools.
7 +
8 +These modifiers are called before the tool is executed by the LLM. This allows you to modify the arguments called by the LLM before they are executed by Composio.
9 +
10 +**Useful for:**
11 +- Injecting an argument into the tool execution
12 +- Overriding the arguments emitted by the LLM
13 +
14 +<Figure src="/images/before-execute.png" alt="Before Execution Modifier" />
15 +
16 +<Callout>
17 +Below we use the `beforeExecute` modifier to modify the number of posts returned by `HACKERNEWS_GET_LATEST_POSTS`.
18 +</Callout>
19 +
20 +## With Chat Completions
21 +
22 +Since completion providers don't have a function execution step, Composio executes the tool call directly. The modifier is configured on the `tools.execute` method.
23 +
24 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
25 + <Tab value="Python">
26 +```python
27 +from openai import OpenAI
28 +from composio import Composio, before_execute
29 +from composio.types import ToolExecuteParams
30 +
31 +composio = Composio()
32 +openai_client = OpenAI()
33 +user_id = "user@email.com"
34 +
35 +@before_execute(tools=["HACKERNEWS_GET_LATEST_POSTS"])
36 +def before_execute_modifier(
37 + tool: str,
38 + toolkit: str,
39 + params: ToolExecuteParams,
40 +) -> ToolExecuteParams:
41 + params["arguments"]["size"] = 1
42 + return params
43 +
44 +# Get tools
45 +tools = composio.tools.get(user_id=user_id, slug="HACKERNEWS_GET_LATEST_POSTS")
46 +
47 +# Get response from the LLM
48 +response = openai_client.chat.completions.create(
49 + model="gpt-4o-mini",
50 + tools=tools,
51 + messages=[{"role": "user", "content": "Fetch latest posts from hackernews"}],
52 +)
53 +print(response)
54 +
55 +# Execute the function calls
56 +result = composio.provider.handle_tool_calls(
57 + response=response,
58 + user_id="default",
59 + modifiers=[
60 + before_execute_modifier,
61 + ],
62 +)
63 +print(result)
64 +```
65 + </Tab>
66 + <Tab value="TypeScript">
67 +```typescript
68 +const response = await openai.chat.completions.create({
69 + model: "gpt-4o-mini",
70 + messages,
71 + tools,
72 + tool_choice: "auto",
73 +});
74 +
75 +const { tool_calls } = response.choices[0].message;
76 +console.log(tool_calls);
77 +
78 +if (tool_calls) {
79 + const {
80 + function: { arguments: toolArgs },
81 + } = tool_calls[0];
82 +
83 + const result = await composio.tools.execute(
84 + "HACKERNEWS_GET_LATEST_POSTS",
85 + {
86 + userId,
87 + arguments: JSON.parse(toolArgs),
88 + },
89 + {
90 + beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
91 + if (toolSlug === "HACKERNEWS_GET_LATEST_POSTS") {
92 + params.arguments.size = 1;
93 + }
94 + console.log(params);
95 + return params;
96 + },
97 + }
98 + );
99 + console.log(JSON.stringify(result, null, 2));
100 +}
101 +```
102 + </Tab>
103 +</Tabs>
104 +
105 +## With Agentic Frameworks
106 +
107 +Agentic providers have a function execution step. The modifier is configured on the `tools.get` method which modifies the execution logic within the framework.
108 +
109 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
110 + <Tab value="Python">
111 +```python
112 +from composio import Composio, before_execute
113 +from composio.types import ToolExecuteParams
114 +from composio_crewai import CrewAIProvider
115 +
116 +composio = Composio(provider=CrewAIProvider())
117 +
118 +@before_execute(tools=["LINEAR_CREATE_LINEAR_ISSUE"])
119 +def modify_linear_project_id(
120 + tool: str,
121 + toolkit: str,
122 + params: ToolExecuteParams,
123 +) -> ToolExecuteParams:
124 + params["arguments"]["project_id"] = "1234567890"
125 + return params
126 +
127 +tools = composio.tools.get(
128 + user_id="default",
129 + tools=[
130 + "HACKERNEWS_GET_LATEST_POSTS",
131 + "HACKERNEWS_GET_USER",
132 + "LINEAR_CREATE_LINEAR_ISSUE",
133 + ],
134 + modifiers=[
135 + modify_linear_project_id,
136 + ]
137 +)
138 +```
139 + </Tab>
140 + <Tab value="TypeScript">
141 +```typescript
142 +import { Composio } from "@composio/core";
143 +import { MastraProvider } from "@composio/mastra";
144 +
145 +const composio = new Composio({
146 + apiKey: process.env.COMPOSIO_API_KEY,
147 + provider: new MastraProvider(),
148 +});
149 +
150 +const userId = "user@acme.com";
151 +
152 +const agenticTools = await composio.tools.get(
153 + userId,
154 + {
155 + tools: [
156 + "HACKERNEWS_GET_LATEST_POSTS",
157 + "HACKERNEWS_GET_USER",
158 + "LINEAR_CREATE_LINEAR_ISSUE",
159 + ],
160 + },
161 + {
162 + beforeExecute: ({toolSlug, toolkitSlug, params}) => {
163 + if (toolSlug === "LINEAR_CREATE_LINEAR_ISSUE") {
164 + params.arguments.project_id = "1234567890";
165 + }
166 + return params;
167 + },
168 + }
169 +);
170 +```
171 + </Tab>
172 +</Tabs>
fumadocs/content/docs/modify-tool-behavior/meta.json new
+8
@@ -0,0 +1,8 @@
1 +{
2 + "title": "Modify tool behavior",
3 + "pages": [
4 + "schema-modifiers",
5 + "before-execution-modifiers",
6 + "after-execution-modifiers"
7 + ]
8 +}
fumadocs/content/docs/modify-tool-behavior/schema-modifiers.mdx new
+261
@@ -0,0 +1,261 @@
1 +---
2 +title: Schema Modifiers
3 +description: Customize how tools appear to agents
4 +---
5 +
6 +Schema modifiers are part of Composio SDK's powerful middleware capabilities that allow you to customize and extend the behavior of tools.
7 +
8 +Schema modifiers transform a tool's schema before the tool is seen by an agent.
9 +
10 +<Figure src="/images/schema-modifier.png" alt="Schema Modifier" />
11 +
12 +**Useful for:**
13 +- Modifying or rewriting the tool description to better fit your use case
14 +- Adding arguments to the tool (e.g., adding a `thought` argument to prompt the agent to explain reasoning)
15 +- Hiding arguments from the tool when they're irrelevant
16 +- Adding extra arguments for custom use cases
17 +- Adding default values to tool arguments
18 +
19 +<Callout>
20 +Below we modify the schema of `HACKERNEWS_GET_LATEST_POSTS` to make the `size` argument required and remove the `page` argument.
21 +</Callout>
22 +
23 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
24 + <Tab value="Python">
25 +```python
26 +from composio import Composio, schema_modifier
27 +from composio.types import Tool
28 +
29 +user_id = "your@email.com"
30 +
31 +@schema_modifier(tools=["HACKERNEWS_GET_LATEST_POSTS"])
32 +def modify_schema(
33 + tool: str,
34 + toolkit: str,
35 + schema: Tool,
36 +) -> Tool:
37 + _ = schema.input_parameters["properties"].pop("page", None)
38 + schema.input_parameters["required"] = ["size"]
39 + return schema
40 +
41 +tools = composio.tools.get(
42 + user_id=user_id,
43 + tools=["HACKERNEWS_GET_LATEST_POSTS", "HACKERNEWS_GET_USER"],
44 + modifiers=[
45 + modify_schema,
46 + ]
47 +)
48 +```
49 + </Tab>
50 + <Tab value="TypeScript">
51 +```typescript
52 +const userId = "your@email.com";
53 +
54 +const tools = await composio.tools.get(
55 + userId,
56 + {
57 + tools: ["HACKERNEWS_GET_LATEST_POSTS", "HACKERNEWS_GET_USER"],
58 + },
59 + {
60 + modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
61 + if (toolSlug === "HACKERNEWS_GET_LATEST_POSTS") {
62 + const { inputParameters } = schema;
63 + if (inputParameters?.properties) {
64 + delete inputParameters.properties["page"];
65 + }
66 + inputParameters.required = ["size"];
67 + }
68 + return schema;
69 + },
70 + }
71 +);
72 +
73 +console.log(JSON.stringify(tools, null, 2));
74 +```
75 + </Tab>
76 +</Tabs>
77 +
78 +With the modified tool schema, the `page` argument is removed and `size` is required.
79 +
80 +<Accordions>
81 + <Accordion title="Full example with LLM">
82 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
83 + <Tab value="Python">
84 +```python
85 +from openai import OpenAI
86 +from composio import Composio, schema_modifier
87 +from composio.types import Tool
88 +from composio_openai import OpenAIProvider
89 +
90 +@schema_modifier(tools=["HACKERNEWS_GET_LATEST_POSTS"])
91 +def modify_schema(
92 + tool: str,
93 + toolkit: str,
94 + schema: Tool,
95 +) -> Tool:
96 + _ = schema.input_parameters["properties"].pop("page", None)
97 + schema.input_parameters["required"] = ["size"]
98 + return schema
99 +
100 +# Initialize tools
101 +openai_client = OpenAI()
102 +composio = Composio(provider=OpenAIProvider())
103 +
104 +# Define task
105 +task = "Get the latest posts from Hacker News"
106 +
107 +# Get tools with modifier
108 +tools = composio.tools.get(
109 + user_id="default",
110 + tools=['HACKERNEWS_GET_LATEST_POSTS', 'HACKERNEWS_GET_USER'],
111 + modifiers=[
112 + modify_schema,
113 + ],
114 +)
115 +
116 +# Get response from the LLM
117 +response = openai_client.chat.completions.create(
118 + model="gpt-4o-mini",
119 + tools=tools,
120 + messages=[
121 + {"role": "system", "content": "You are a helpful assistant."},
122 + {"role": "user", "content": task},
123 + ],
124 +)
125 +print(response)
126 +
127 +# Execute the function calls
128 +result = composio.provider.handle_tool_calls(response=response, user_id="default")
129 +print(result)
130 +```
131 + </Tab>
132 + <Tab value="TypeScript">
133 +```typescript
134 +import { Composio } from '@composio/core';
135 +import { OpenAI } from 'openai';
136 +
137 +const composio = new Composio({
138 + apiKey: process.env.COMPOSIO_API_KEY,
139 +});
140 +const openai = new OpenAI();
141 +
142 +const userId = 'your@email.com';
143 +
144 +const tools = await composio.tools.get(
145 + userId,
146 + {
147 + tools: ['HACKERNEWS_GET_LATEST_POSTS', 'HACKERNEWS_GET_USER'],
148 + },
149 + {
150 + modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
151 + if (toolSlug === 'HACKERNEWS_GET_LATEST_POSTS') {
152 + const { inputParameters } = schema;
153 + if (inputParameters?.properties) {
154 + delete inputParameters.properties['page'];
155 + }
156 + inputParameters.required = ['size'];
157 + }
158 + return schema;
159 + },
160 + }
161 +);
162 +
163 +console.log(JSON.stringify(tools, null, 2));
164 +
165 +const response = await openai.chat.completions.create({
166 + model: 'gpt-4o-mini',
167 + messages: [
168 + {
169 + role: 'system',
170 + content: 'You are a helpful assistant that can help with tasks.',
171 + },
172 + { role: 'user', content: 'Get the latest posts from Hacker News' },
173 + ],
174 + tools: tools,
175 + tool_choice: 'auto',
176 +});
177 +
178 +console.log(response.choices[0].message.tool_calls);
179 +```
180 + </Tab>
181 +</Tabs>
182 + </Accordion>
183 +</Accordions>
184 +
185 +## Example: Modifying the tool description
186 +
187 +Sometimes you need to provide additional context to help the agent understand how to use a tool correctly. This example demonstrates modifying the description of `GITHUB_LIST_REPOSITORY_ISSUES` to specify a default repository.
188 +
189 +<Callout>
190 +This approach is useful when you want to guide the agent's behavior without changing the tool's underlying functionality.
191 +</Callout>
192 +
193 +In this example:
194 +- We append additional instructions to the tool's description
195 +- The modified description tells the agent to use `composiohq/composio` as the default repository
196 +- This helps prevent errors when the agent forgets to specify a repository parameter
197 +
198 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
199 + <Tab value="Python">
200 +```python
201 +from composio import Composio, schema_modifier
202 +from composio.types import Tool
203 +from composio_google import GoogleProvider
204 +from google import genai
205 +from uuid import uuid4
206 +
207 +composio = Composio(provider=GoogleProvider())
208 +client = genai.Client()
209 +user_id = uuid4()
210 +
211 +@schema_modifier(tools=["GITHUB_LIST_REPOSITORY_ISSUES"])
212 +def append_repository(
213 + tool: str,
214 + toolkit: str,
215 + schema: Tool,
216 +) -> Tool:
217 + schema.description += " When not specified, use the `composiohq/composio` repository"
218 + return schema
219 +
220 +tools = composio.tools.get(
221 + user_id=user_id,
222 + tools=["GITHUB_LIST_REPOSITORY_ISSUES"],
223 + modifiers=[append_repository]
224 +)
225 +
226 +print(tools)
227 +```
228 + </Tab>
229 + <Tab value="TypeScript">
230 +```typescript
231 +import { Composio } from '@composio/core';
232 +import { VercelProvider } from '@composio/vercel';
233 +import { v4 as uuidv4 } from 'uuid';
234 +
235 +const userId = uuidv4();
236 +const composio = new Composio({
237 + apiKey: process.env.COMPOSIO_API_KEY,
238 + provider: new VercelProvider(),
239 +});
240 +
241 +const addDescription = ({ toolSlug, toolkitSlug, schema }) => {
242 + if (toolSlug === 'GITHUB_LIST_REPOSITORY_ISSUES') {
243 + schema.description += 'If not specified, use the `composiohq/composio` repository';
244 + }
245 + return schema;
246 +};
247 +
248 +const tools = await composio.tools.get(
249 + userId,
250 + {
251 + tools: ['GITHUB_LIST_REPOSITORY_ISSUES'],
252 + },
253 + {
254 + modifySchema: addDescription,
255 + }
256 +);
257 +
258 +console.log(tools);
259 +```
260 + </Tab>
261 +</Tabs>
fumadocs/content/docs/toolkit-versioning.mdx new
+154
@@ -0,0 +1,154 @@
1 +---
2 +title: Toolkit Versioning
3 +description: Pin specific tool versions for consistent behavior in production
4 +---
5 +
6 +Toolkit versioning ensures your tools behave consistently across deployments. You can pin specific versions in production, test new releases in development, and roll back when needed.
7 +
8 +<Callout type="info">
9 +Starting from Python SDK v0.9.0 and TypeScript SDK v0.2.0, specifying versions is required for manual tool execution.
10 +</Callout>
11 +
12 +## Configuration methods
13 +
14 +Configure toolkit versions using one of three methods:
15 +
16 +### SDK initialization
17 +
18 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
19 + <Tab value="Python">
20 +```python
21 +from composio import Composio
22 +
23 +# Pin specific versions for each toolkit
24 +composio = Composio(
25 + api_key="YOUR_API_KEY",
26 + toolkit_versions={
27 + "github": "20251027_00",
28 + "slack": "20251027_00",
29 + "gmail": "20251027_00"
30 + }
31 +)
32 +```
33 + </Tab>
34 + <Tab value="TypeScript">
35 +```typescript
36 +import { Composio } from "@composio/core";
37 +
38 +// Pin specific versions for each toolkit
39 +const composio = new Composio({
40 + apiKey: "YOUR_API_KEY",
41 + toolkitVersions: {
42 + github: "20251027_00",
43 + slack: "20251027_00",
44 + gmail: "20251027_00"
45 + }
46 +});
47 +```
48 + </Tab>
49 +</Tabs>
50 +
51 +### Environment variables
52 +
53 +```bash
54 +# Set versions for specific toolkits
55 +export COMPOSIO_TOOLKIT_VERSION_GITHUB="20251027_00"
56 +export COMPOSIO_TOOLKIT_VERSION_SLACK="20251027_00"
57 +export COMPOSIO_TOOLKIT_VERSION_GMAIL="20251027_00"
58 +```
59 +
60 +### Per-execution override
61 +
62 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
63 + <Tab value="Python">
64 +```python
65 +from composio import Composio
66 +
67 +composio = Composio(api_key="YOUR_API_KEY")
68 +
69 +# Specify version directly in execute call
70 +result = composio.tools.execute(
71 + "GITHUB_LIST_STARGAZERS",
72 + arguments={
73 + "owner": "ComposioHQ",
74 + "repo": "composio"
75 + },
76 + user_id="user-k7334",
77 + version="20251027_00" # Override version for this execution
78 +)
79 +print(result)
80 +```
81 + </Tab>
82 + <Tab value="TypeScript">
83 +```typescript
84 +import { Composio } from "@composio/core";
85 +
86 +const composio = new Composio({ apiKey: "YOUR_API_KEY" });
87 +
88 +// Specify version directly in execute call
89 +const result = await composio.tools.execute("GITHUB_LIST_STARGAZERS", {
90 + userId: "user-k7334",
91 + arguments: {
92 + owner: "ComposioHQ",
93 + repo: "composio"
94 + },
95 + version: "20251027_00" // Override version for this execution
96 +});
97 +console.log(result);
98 +```
99 + </Tab>
100 +</Tabs>
101 +
102 +## Version format
103 +
104 +Versions follow the format `YYYYMMDD_NN`:
105 +- `YYYYMMDD`: Release date
106 +- `NN`: Sequential release number
107 +
108 +```python
109 +# Production
110 +toolkit_versions = {"github": "20251027_00"}
111 +
112 +# Development
113 +toolkit_versions = {"github": "latest"}
114 +```
115 +
116 +<Callout type="warn">
117 +Never use `latest` in production. It can introduce breaking changes.
118 +</Callout>
119 +
120 +## Version resolution order
121 +
122 +1. Per-execution version (highest priority)
123 +2. SDK initialization version
124 +3. Environment variable (toolkit-specific)
125 +
126 +## Managing versions
127 +
128 +Check available versions using:
129 +
130 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
131 + <Tab value="Python">
132 +```python
133 +# Get toolkit information including available versions
134 +toolkit = composio.toolkits.get(slug="github")
135 +
136 +# Extract and print version information
137 +print(f"Toolkit: {toolkit.name}")
138 +print(f"Current Version: {toolkit.meta.version}")
139 +print(f"Available Versions: {toolkit.meta.available_versions}")
140 +```
141 + </Tab>
142 + <Tab value="TypeScript">
143 +```typescript
144 +// Get toolkit information including available versions
145 +const toolkit = await composio.toolkits.get("github");
146 +
147 +// Extract and print version information
148 +console.log("Toolkit:", toolkit.name);
149 +console.log("Current Version:", toolkit.meta.version);
150 +console.log("Available Versions:", toolkit.meta.availableVersions);
151 +console.log("Latest Version:", toolkit.meta.availableVersions[0]); // First one is usually the latest
152 +```
153 + </Tab>
154 +</Tabs>
fumadocs/content/docs/using-triggers.mdx new
+384
@@ -0,0 +1,384 @@
1 +---
2 +title: Using Triggers
3 +description: Send payloads to your AI agents or systems based on events in apps
4 +---
5 +
6 +When events occur in connected apps (like new Slack messages or GitHub commits), triggers automatically send the event data to your application.
7 +
8 +Each event is delivered as a structured payload to your webhook endpoint (via webhooks or WebSockets), enabling your applications or AI agents to respond proactively.
9 +
10 +<Figure src="/images/triggers.png" alt="Triggers Overview" caption="Triggers through Composio" />
11 +
12 +<Callout type="info" title="Prerequisites">
13 +Before proceeding, ensure you've created an [auth config](/docs/authenticating-tools#creating-an-auth-config) and [established a connection](/docs/authenticating-tools#hosted-authentication-connect-link) to an app (e.g., Slack, GitHub). Triggers are scoped to specific users - learn about [User Management](/docs/user-management) for guidance on structuring User IDs.
14 +</Callout>
15 +
16 +## Creating a trigger
17 +
18 +You can create triggers using either the Composio dashboard or programmatically via the SDK.
19 +
20 +### Using Dashboard
21 +
22 +To create triggers through the dashboard:
23 +
24 +1. Navigate to the [Auth Configs](https://platform.composio.dev?next_page=%2Fauth-configs) page
25 +2. Select the auth config
26 +3. Click "Add Trigger" and navigate to "Active Triggers" tab to fetch the trigger ID
27 +
28 +<Video src="/videos/enabling-triggers.mp4" caption="Creating a trigger from the dashboard" />
29 +
30 +Some triggers require additional configuration. The dashboard will prompt you for any required fields during setup.
31 +
32 +<Figure
33 + src="/images/trigger-config.png"
34 + alt="Trigger configuration example"
35 + caption="Example: Gmail trigger configuration"
36 + size="sm"
37 +/>
38 +
39 +### Using SDK
40 +
41 +Create triggers programmatically by providing the trigger type and any required configuration. The trigger instance will be created using the toolkit version configured during Composio initialization (defaults to `'latest'`).
42 +
43 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
44 + <Tab value="Python">
45 +```python
46 +from composio import Composio
47 +
48 +composio = Composio(api_key="your-api-key")
49 +user_id = "user-id-123435"
50 +
51 +# Check what configuration is required
52 +trigger_type = composio.triggers.get_type("GITHUB_COMMIT_EVENT")
53 +print(trigger_type.config)
54 +# Returns: {"properties": {...}, "required": ["owner", "repo"], ...}
55 +
56 +# Create trigger with the required config
57 +trigger = composio.triggers.create(
58 + slug="GITHUB_COMMIT_EVENT",
59 + user_id=user_id,
60 + trigger_config={"owner": "your-repo-owner", "repo": "your-repo-name"},
61 +)
62 +print(f"Trigger created: {trigger.trigger_id}")
63 +```
64 + </Tab>
65 + <Tab value="TypeScript">
66 +```typescript
67 +import { Composio } from '@composio/core';
68 +
69 +const composio = new Composio({apiKey: "your-api-key"});
70 +const userId = 'user-id-123435';
71 +
72 +// Check what configuration is required
73 +const triggerType = await composio.triggers.getType("GITHUB_COMMIT_EVENT");
74 +console.log(triggerType.config);
75 +// Returns: {"properties": {...}, "required": ["owner", "repo"], ...}
76 +
77 +// Create trigger with the required config
78 +const trigger = await composio.triggers.create(
79 + userId,
80 + 'GITHUB_COMMIT_EVENT',
81 + {
82 + triggerConfig: {
83 + owner: 'your-repo-owner',
84 + repo: 'your-repo-name'
85 + }
86 + }
87 +);
88 +console.log(`Trigger created: ${trigger.triggerId}`);
89 +```
90 + </Tab>
91 +</Tabs>
92 +
93 +<Callout>
94 +To use a specific toolkit version when creating triggers, configure `toolkitVersions` during initialization. See [Toolkit Versioning](/docs/toolkit-versioning) for more details.
95 +</Callout>
96 +
97 +## Subscribing to triggers
98 +
99 +### Webhooks
100 +
101 +The recommended way to subscribe to triggers is through webhooks. Configure your webhook URL in the [Event & Trigger settings](https://platform.composio.dev?next_page=/settings/events).
102 +
103 +Use a publicly accessible URL where Composio can send event payloads. This endpoint should be able to process incoming POST requests containing the trigger data.
104 +
105 +<Callout type="info">
106 +**Local development:** Use [ngrok](https://ngrok.com) or [webhook.site](https://webhook.site) to expose your local server to the internet for testing.
107 +</Callout>
108 +
109 +Webhook payloads contain:
110 +- `type`: The trigger type identifier
111 +- `data`: The actual event data
112 +- `timestamp`: When the event occurred
113 +- `log_id`: Unique identifier for this event
114 +
115 +Below are examples of webhook handlers for FastAPI and Next.js applications:
116 +
117 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
118 + <Tab value="Python">
119 +```python
120 +@app.post("/webhook")
121 +async def webhook_handler(request: Request):
122 + payload = await request.json()
123 +
124 + trigger_type = payload.get("type")
125 + event_data = payload.get("data", {})
126 +
127 + if trigger_type == "github_star_added_event":
128 + repo_name = event_data.get("repository_name")
129 + starred_by = event_data.get("starred_by")
130 + print(f"Repository {repo_name} starred by {starred_by}")
131 + # Add your business logic here
132 +
133 + return {"status": "success", "message": "Webhook processed"}
134 +```
135 + </Tab>
136 + <Tab value="TypeScript">
137 +```typescript
138 +export default async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
139 + const payload = req.body;
140 +
141 + if (payload.type === 'github_star_added_event') {
142 + const event: TriggerEvent<GitHubStarEventData> = {
143 + type: payload.type,
144 + timestamp: payload.timestamp,
145 + data: payload.data
146 + };
147 +
148 + console.log(`Repository ${event.data.repository_name} starred by ${event.data.starred_by}`);
149 + // Add your business logic here
150 + }
151 +
152 + res.status(200).json({
153 + status: 'success',
154 + message: 'Webhook processed'
155 + });
156 +}
157 +```
158 + </Tab>
159 +</Tabs>
160 +
161 +### Verifying webhook signatures
162 +
163 +Composio signs all webhook requests so you can verify they're authentic. Each webhook includes these headers:
164 +
165 +- `webhook-signature`: HMAC signature in format `v1,<base64_signature>`
166 +- `webhook-id`: Unique message identifier
167 +- `webhook-timestamp`: Unix timestamp when the webhook was sent
168 +
169 +To enable verification:
170 +
171 +1. Obtain your webhook secret from the [Composio dashboard](https://platform.composio.dev?next_page=/settings/webhook) under Project Settings → Webhook
172 +2. Set it as the `COMPOSIO_WEBHOOK_SECRET` environment variable
173 +3. Use the verification function in your webhook handler:
174 +
175 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
176 + <Tab value="Python">
177 +```python
178 +def verify_webhook_signature(request: Request, body: bytes) -> bool:
179 + """Verify Composio webhook signature"""
180 + webhook_signature = request.headers.get("webhook-signature")
181 + webhook_id = request.headers.get("webhook-id")
182 + webhook_timestamp = request.headers.get("webhook-timestamp")
183 + webhook_secret = os.getenv("COMPOSIO_WEBHOOK_SECRET")
184 +
185 + if not all([webhook_signature, webhook_id, webhook_timestamp, webhook_secret]):
186 + raise HTTPException(status_code=400, detail="Missing required webhook headers or secret")
187 +
188 + if not webhook_signature.startswith("v1,"):
189 + raise HTTPException(status_code=401, detail="Invalid signature format")
190 +
191 + received = webhook_signature[3:]
192 + signing_string = f"{webhook_id}.{webhook_timestamp}.{body.decode()}"
193 + expected = base64.b64encode(
194 + hmac.new(webhook_secret.encode(), signing_string.encode(), hashlib.sha256).digest()
195 + ).decode()
196 +
197 + if not hmac.compare_digest(received, expected):
198 + raise HTTPException(status_code=401, detail="Invalid webhook signature")
199 +
200 + return True
201 +```
202 + </Tab>
203 + <Tab value="TypeScript">
204 +```typescript
205 +function verifyWebhookSignature(
206 + req: NextApiRequest,
207 + body: string
208 +): boolean {
209 + const signature = req.headers['webhook-signature'] as string | undefined;
210 + const msgId = req.headers['webhook-id'] as string | undefined;
211 + const timestamp = req.headers['webhook-timestamp'] as string | undefined;
212 + const secret = process.env.COMPOSIO_WEBHOOK_SECRET;
213 +
214 + if (!signature || !msgId || !timestamp || !secret) {
215 + throw new Error('Missing required webhook headers or secret');
216 + }
217 +
218 + if (!signature.startsWith('v1,')) {
219 + throw new Error('Invalid signature format');
220 + }
221 +
222 + const received = signature.slice(3);
223 + const signingString = `${msgId}.${timestamp}.${body}`;
224 + const expected = crypto
225 + .createHmac('sha256', secret)
226 + .update(signingString)
227 + .digest('base64');
228 +
229 + return crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
230 +}
231 +```
232 + </Tab>
233 +</Tabs>
234 +
235 +The signature is calculated as:
236 +```
237 +signing_string = "{webhook-id}.{webhook-timestamp}.{raw_body}"
238 +signature = HMAC-SHA256(signing_string, secret)
239 +```
240 +
241 +### Prototyping with trigger subscriptions
242 +
243 +During development, you can subscribe to triggers directly through the SDK without setting up webhooks.
244 +
245 +You can subscribe to multiple trigger events by configuring the filters. When you specify multiple filters, ALL of them must match for the trigger to be subscribed to.
246 +
247 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
248 + <Tab value="Python">
249 +```python
250 +from composio import Composio
251 +
252 +# Initialize Composio client
253 +composio = Composio(api_key="your_api_key_here")
254 +
255 +# Subscribe to trigger events
256 +subscription = composio.triggers.subscribe()
257 +
258 +# Define event handler
259 +@subscription.handle(trigger_id="your_trigger_id")
260 +def handle_github_commit(data):
261 + print(f"New commit detected: {data}")
262 + # Add your custom logic here
263 +
264 +# listen for events on the trigger
265 +subscription.wait_forever()
266 +# Note: For production use, set up webhooks instead
267 +```
268 + </Tab>
269 + <Tab value="TypeScript">
270 +```typescript
271 +import { Composio } from '@composio/core';
272 +
273 +// Initialize Composio client
274 +const composio = new Composio({ apiKey: "your_api_key_here" });
275 +
276 +// Subscribe to trigger events
277 +composio.triggers.subscribe(
278 + (data) => {
279 + console.log(`New commit detected:`, data);
280 + // Add your custom logic here
281 + },
282 + { triggerId: 'your_trigger_id' }
283 +);
284 +
285 +// Note: For production use, set up webhooks instead
286 +```
287 + </Tab>
288 +</Tabs>
289 +
290 +## Trigger payload types
291 +
292 +To see what data you'll receive in your webhook handler, inspect the trigger's payload:
293 +
294 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
295 + <Tab value="Python">
296 +```python
297 +# Get trigger type to inspect payload structure
298 +trigger = composio.triggers.get_type(slug="GITHUB_COMMIT_EVENT")
299 +print(trigger.payload)
300 +```
301 + </Tab>
302 + <Tab value="TypeScript">
303 +```typescript
304 +// Get trigger type to inspect payload structure
305 +const triggerType = await composio.triggers.getType('GITHUB_COMMIT_EVENT');
306 +console.log(triggerType.payload);
307 +```
308 + </Tab>
309 +</Tabs>
310 +
311 +### Type-safe trigger handling (TypeScript)
312 +
313 +For better type safety and developer experience in TypeScript, you can define specific payload types and use the `TriggerEvent<T>` interface:
314 +
315 +```typescript
316 +import { Composio, TriggerEvent } from '@composio/core';
317 +
318 +// Define type-safe payload for GitHub Star Added event
319 +export type GitHubStarAddedEventPayload = {
320 + action: "created";
321 + repository_id: number;
322 + repository_name: string;
323 + repository_url: string;
324 + starred_at: string;
325 + starred_by: string;
326 +};
327 +
328 +// Type-safe trigger event handler
329 +function handleGitHubStarEvent(event: TriggerEvent<GitHubStarAddedEventPayload>) {
330 + console.log(`⭐ ${event.data.repository_name} starred by ${event.data.starred_by}`);
331 +}
332 +```
333 +
334 +This approach provides:
335 +
336 +- **IntelliSense support** for trigger payload fields
337 +- **Compile-time error checking** for typos and invalid field access
338 +- **Better documentation** through TypeScript types
339 +- **Improved maintainability** of trigger handling code
340 +
341 +## Managing triggers
342 +
343 +### Enable/disable triggers
344 +
345 +You can pause triggers temporarily without deleting them.
346 +
347 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
348 + <Tab value="Python">
349 +```python
350 +# Disable a trigger
351 +composio.triggers.disable(trigger_id="ti_abcd123")
352 +
353 +# Re-enable when needed
354 +composio.triggers.enable(trigger_id="ti_abcd123")
355 +```
356 + </Tab>
357 + <Tab value="TypeScript">
358 +```typescript
359 +// Disable a trigger
360 +await composio.triggers.disable('ti_abcd123');
361 +
362 +// Re-enable when needed
363 +await composio.triggers.enable('ti_abcd123');
364 +```
365 + </Tab>
366 +</Tabs>
367 +
368 +You can also manage triggers from the dashboard:
369 +
370 +1. Go to the [Auth Config](https://platform.composio.dev?next_page=/auth-configs) page
371 +2. Select your auth config
372 +3. Navigate to "Active Triggers"
373 +4. Disable/Enable the trigger
374 +
375 +<Figure
376 + src="/images/trigger-enable-disable.png"
377 + alt="Enable/disable triggers"
378 + caption="Enable/disable triggers in dashboard"
379 + size="sm"
380 +/>
381 +
382 +## Troubleshooting
383 +
384 +View detailed trigger logs and debug issues on the [Composio dashboard](https://platform.composio.dev?next_page=/logs/triggers).
fumadocs/mdx-components.tsx
+12
@@ -4,7 +4,12 @@ import { YouTube } from '@/components/youtube';
4 import { Tabs, Tab, TabsList, TabsTrigger, TabsContent } from 'fumadocs-ui/components/tabs';
5 import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
6 import { Callout } from 'fumadocs-ui/components/callout';
7 +import { Step, Steps } from 'fumadocs-ui/components/steps';
8 +import { Card, Cards } from 'fumadocs-ui/components/card';
9 +import { ImageZoom } from 'fumadocs-ui/components/image-zoom';
10 import { ProviderCard, ProviderGrid } from '@/components/provider-card';
11 +import { Figure } from '@/components/figure';
12 +import { Video } from '@/components/video';
13 import { CapabilityCard, CapabilityList } from '@/components/capability-card';
14 import { ShieldCheck, Route as RouteIcon } from 'lucide-react';
15 import {
@@ -21,6 +26,7 @@ import {
26 export function getMDXComponents(components?: MDXComponents): MDXComponents {
27 return {
28 ...defaultMdxComponents,
29 + img: (props) => <ImageZoom {...(props as any)} />,
30 YouTube,
31 Tabs,
32 Tab,
@@ -30,8 +36,14 @@ export function getMDXComponents(components?: MDXComponents): MDXComponents {
36 Accordion,
37 Accordions,
38 Callout,
39 + Step,
40 + Steps,
41 + Card,
42 + Cards,
43 ProviderCard,
44 ProviderGrid,
45 + Figure,
46 + Video,
47 CapabilityCard,
48 CapabilityList,
49 // Lucide icons - available globally in MDX without imports
fumadocs/public/images/after-execute.png
Binary files /dev/null and b/fumadocs/public/images/after-execute.png differ
fumadocs/public/images/auth-screen-example.png
Binary files /dev/null and b/fumadocs/public/images/auth-screen-example.png differ
fumadocs/public/images/before-execute.png
Binary files /dev/null and b/fumadocs/public/images/before-execute.png differ
fumadocs/public/images/schema-modifier.png
Binary files /dev/null and b/fumadocs/public/images/schema-modifier.png differ
fumadocs/public/images/trigger-config.png
Binary files /dev/null and b/fumadocs/public/images/trigger-config.png differ
fumadocs/public/images/trigger-enable-disable.png
Binary files /dev/null and b/fumadocs/public/images/trigger-enable-disable.png differ
fumadocs/public/images/triggers.png
Binary files /dev/null and b/fumadocs/public/images/triggers.png differ
fumadocs/public/videos/enabling-triggers.mp4
Binary files /dev/null and b/fumadocs/public/videos/enabling-triggers.mp4 differ