1
----
2
-title: Creating Custom Tools
3
-description: Learn how to extend Composio's toolkits with your own tools
4
-keywords: [create tool, custom action, extend, standalone tool]
5
-llmGuardrails: "direct-execution"
6
----
7
-
8
-<Callout type="info">
9
-If you're building an agent, we recommend using [sessions](/docs/configuring-sessions) instead. See [Custom Tools and Toolkits (Experimental)](/docs/toolkits/custom-tools-and-toolkits) for defining local tools that run in-process alongside remote Composio tools within a session.
10
-</Callout>
11
-
12
-Custom tools allow you to create your own tools that can be used with Composio.
13
-
14
-1. **Standalone tools** - Simple tools that don't require any authentication
15
-2. **Toolkit-based tools** - Tools that require authentication and can use toolkit credentials
16
-
17
-## Creating a Custom Tool
18
-
19
-### Standalone Tool
20
-
21
-A standalone tool is the simplest form of custom tool. It only requires input parameters and an execute function:
22
-
23
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
24
- <Tab value="Python">
25
-```python
26
-from pydantic import BaseModel, Field
27
-
28
-from composio import Composio
29
-from composio.types import ExecuteRequestFn
30
-
31
-composio = Composio()
32
-
33
-
34
-class AddTwoNumbersInput(BaseModel):
35
- a: int = Field(
36
- ...,
37
- description="The first number to add",
38
- )
39
- b: int = Field(
40
- ...,
41
- description="The second number to add",
42
- )
43
-
44
-# function name will be used as slug
45
-@composio.tools.custom_tool
46
-def add_two_numbers(request: AddTwoNumbersInput) -> int:
47
- """Add two numbers."""
48
- return request.a + request.b
49
-```
50
- </Tab>
51
- <Tab value="TypeScript">
52
-```typescript
53
-import { Composio } from '@composio/core';
54
-import { z } from 'zod/v3';
55
-const composio = new Composio({ apiKey: 'your_api_key' });
56
-// ---cut---
57
-const tool = await composio.tools.createCustomTool({
58
- slug: 'CALCULATE_SQUARE',
59
- name: 'Calculate Square',
60
- description: 'Calculates the square of a number',
61
- inputParams: z.object({
62
- number: z.number().describe('The number to calculate the square of'),
63
- }),
64
- execute: async input => {
65
- const { number } = input;
66
- return {
67
- data: { result: number * number },
68
- error: null,
69
- successful: true,
70
- };
71
- },
72
-});
73
-```
74
- </Tab>
75
-</Tabs>
76
-
77
-### Toolkit-based Tool
78
-
79
-A toolkit-based tool has access to two ways of making authenticated requests:
80
-
81
-**1. Using `executeToolRequest`** - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection and baseURL resolution:
82
-
83
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
84
- <Tab value="Python">
85
-```python
86
-class GetIssueInfoInput(BaseModel):
87
- issue_number: int = Field(
88
- ...,
89
- description="The number of the issue to get information about",
90
- )
91
-
92
-# function name will be used as slug
93
-@composio.tools.custom_tool(toolkit="github")
94
-def get_issue_info(
95
- request: GetIssueInfoInput,
96
- execute_request: ExecuteRequestFn,
97
- auth_credentials: dict,
98
-) -> dict:
99
- """Get information about a GitHub issue."""
100
- response = execute_request(
101
- endpoint=f"/repos/composiohq/composio/issues/{request.issue_number}",
102
- method="GET",
103
- parameters=[
104
- {
105
- "name": "Accept",
106
- "value": "application/vnd.github.v3+json",
107
- "type": "header",
108
- },
109
- {
110
- "name": "Authorization",
111
- "value": f"Bearer {auth_credentials['access_token']}",
112
- "type": "header",
113
- },
114
- ],
115
- )
116
- return {"data": response.data}
117
-```
118
- </Tab>
119
- <Tab value="TypeScript">
120
-```typescript
121
-import { Composio } from '@composio/core';
122
-import { z } from 'zod/v3';
123
-const composio = new Composio({ apiKey: 'your_api_key' });
124
-// ---cut---
125
-const tool = await composio.tools.createCustomTool({
126
- slug: 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY',
127
- name: 'Github star composio repositories',
128
- toolkitSlug: 'github',
129
- description: 'Star any specified repo of `composiohq` user',
130
- inputParams: z.object({
131
- repository: z.string().describe('The repository to star'),
132
- page: z.number().optional().describe('Pagination page number'),
133
- customHeader: z.string().optional().describe('Custom header'),
134
- }),
135
- execute: async (input, connectionConfig, executeToolRequest) => {
136
- // This method makes authenticated requests to the relevant API
137
- // You can use relative paths!
138
- // Composio will automatically inject the baseURL
139
- const result = await executeToolRequest({
140
- endpoint: `/user/starred/composiohq/${input.repository}`,
141
- method: 'PUT',
142
- body: {},
143
- // Add custom headers or query parameters
144
- parameters: [
145
- // Add query parameters
146
- {
147
- name: 'page',
148
- value: input.page?.toString() || '1',
149
- in: 'query',
150
- },
151
- // Add custom headers
152
- {
153
- name: 'x-custom-header',
154
- value: input.customHeader || 'default-value',
155
- in: 'header',
156
- },
157
- ],
158
- });
159
- return result;
160
- },
161
-});
162
-```
163
- </Tab>
164
-</Tabs>
165
-
166
-**2. Using `connectionConfig`** - For making direct API calls when needed:
167
-
168
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
169
- <Tab value="Python">
170
-```python
171
-import requests
172
-
173
-@composio.tools.custom_tool(toolkit="github")
174
-def get_issue_info_direct(
175
- request: GetIssueInfoInput,
176
- execute_request: ExecuteRequestFn,
177
- auth_credentials: dict,
178
-) -> dict:
179
- """Get information about a GitHub issue."""
180
- response = requests.get(
181
- f"https://api.github.com/repos/composiohq/composio/issues/{request.issue_number}",
182
- headers={
183
- "Accept": "application/vnd.github.v3+json",
184
- "Authorization": f"Bearer {auth_credentials['access_token']}",
185
- },
186
- )
187
- return {"data": response.json()}
188
-```
189
- </Tab>
190
- <Tab value="TypeScript">
191
-```typescript
192
-import { Composio } from '@composio/core';
193
-import { z } from 'zod/v3';
194
-const composio = new Composio({ apiKey: 'your_api_key' });
195
-// ---cut---
196
-const tool = await composio.tools.createCustomTool({
197
- slug: 'GITHUB_DIRECT_API',
198
- name: 'Direct GitHub API Call',
199
- description: 'Makes direct calls to GitHub API',
200
- toolkitSlug: 'github',
201
- inputParams: z.object({
202
- repo: z.string().describe('Repository name'),
203
- }),
204
- execute: async (input, connectionConfig, executeToolRequest) => {
205
- // Use connectionConfig for direct API calls
206
- if (!connectionConfig || connectionConfig.authScheme !== 'OAUTH2') {
207
- throw new Error('OAuth2 connection required');
208
- }
209
- const result = await fetch(`https://api.github.com/repos/${input.repo}`, {
210
- headers: {
211
- Authorization: `Bearer ${connectionConfig.val.access_token}`,
212
- },
213
- });
214
-
215
- return {
216
- data: await result.json(),
217
- error: null,
218
- successful: true,
219
- };
220
- },
221
-});
222
-```
223
- </Tab>
224
-</Tabs>
225
-
226
-### Using Custom Headers and Query Parameters
227
-
228
-You can add custom headers and query parameters to your toolkit-based tools using the `parameters` option in `executeToolRequest`:
229
-
230
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
231
- <Tab value="Python">
232
-```python
233
-@composio.tools.custom_tool(toolkit="github")
234
-def get_issue_info(
235
- request: GetIssueInfoInput,
236
- execute_request: ExecuteRequestFn,
237
- auth_credentials: dict,
238
-) -> dict:
239
- """Get information about a GitHub issue."""
240
- response = execute_request(
241
- endpoint=f"/repos/composiohq/composio/issues/{request.issue_number}",
242
- method="GET",
243
- parameters=[
244
- {
245
- "name": "Accept",
246
- "value": "application/vnd.github.v3+json",
247
- "type": "header",
248
- },
249
- {
250
- "name": "Authorization",
251
- "value": f"Bearer {auth_credentials['access_token']}",
252
- "type": "header",
253
- },
254
- {
255
- "name": 'X-Custom-Header',
256
- "value": 'custom-value',
257
- "type": 'header',
258
- },
259
- ],
260
- )
261
- return {"data": response.data}
262
-```
263
- </Tab>
264
- <Tab value="TypeScript">
265
-```typescript
266
-import { Composio } from '@composio/core';
267
-import { z } from 'zod/v3';
268
-const composio = new Composio({ apiKey: 'your_api_key' });
269
-// ---cut---
270
-const tool = await composio.tools.createCustomTool({
271
- slug: 'GITHUB_SEARCH_REPOSITORIES',
272
- name: 'Search GitHub Repositories',
273
- description: 'Search for repositories with custom parameters',
274
- toolkitSlug: 'github',
275
- inputParams: z.object({
276
- query: z.string().describe('Search query'),
277
- perPage: z.number().optional().describe('Results per page'),
278
- acceptType: z.string().optional().describe('Custom accept header'),
279
- }),
280
- execute: async (input, connectionConfig, executeToolRequest) => {
281
- const result = await executeToolRequest({
282
- endpoint: '/search/repositories',
283
- method: 'GET',
284
- parameters: [
285
- // Add query parameters for pagination
286
- {
287
- name: 'q',
288
- value: input.query,
289
- in: 'query',
290
- },
291
- {
292
- name: 'per_page',
293
- value: (input.perPage || 30).toString(),
294
- in: 'query',
295
- },
296
- // Add custom headers
297
- {
298
- name: 'Accept',
299
- value: input.acceptType || 'application/vnd.github.v3+json',
300
- in: 'header',
301
- },
302
- {
303
- name: 'X-Custom-Header',
304
- value: 'custom-value',
305
- in: 'header',
306
- },
307
- ],
308
- });
309
- return result;
310
- },
311
-});
312
-```
313
- </Tab>
314
-</Tabs>
315
-
316
-## Executing Custom Tools
317
-
318
-You can execute custom tools just like any other tool:
319
-
320
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
321
- <Tab value="Python">
322
-```python
323
-response = composio.tools.execute(
324
- user_id="default",
325
- slug="TOOL_SLUG", # For the tool above you can use `get_issue_info.slug`
326
- arguments={"issue_number": 1},
327
-)
328
-```
329
- </Tab>
330
- <Tab value="TypeScript">
331
-```typescript
332
-import { Composio } from '@composio/core';
333
-const composio = new Composio({ apiKey: 'your_api_key' });
334
-// ---cut---
335
-const result = await composio.tools.execute('TOOL_SLUG', {
336
- arguments: {
337
- // Tool input parameters
338
- },
339
- userId: 'user-id',
340
- connectedAccountId: 'optional-account-id', // Required for toolkit-based tools
341
-});
342
-```
343
- </Tab>
344
-</Tabs>
345
-
346
-## Best Practices
347
-
348
-1. Use descriptive names and slugs for your tools
349
-2. Always provide descriptions for input parameters using `describe()`
350
-3. Handle errors gracefully in your execute function
351
-4. For toolkit-based tools:
352
- - Prefer `executeToolRequest` over direct API calls when possible
353
- - Use relative paths with `executeToolRequest` - Composio will automatically inject the correct baseURL
354
- - Use the `parameters` option to add custom headers or query parameters:
355
- ```typescript
356
- parameters: [
357
- { name: 'page', value: '1', in: 'query' }, // Adds ?page=1 to URL
358
- { name: 'x-custom', value: 'value', in: 'header' }, // Adds header
359
- ];
360
- ```
361
- - Remember that `executeToolRequest` can only call tools from the same toolkit
362
- - Use `executeToolRequest` to leverage Composio's automatic credential handling
363
- - Only use `connectionConfig` when you need to make direct API calls or interact with different services
364
-5. Chain multiple toolkit operations using `executeToolRequest` for better maintainability
365
-
366
-## Limitations
367
-
368
-1. Custom tools are stored in memory and are not persisted
369
-2. They need to be recreated when the application restarts
370
-3. Toolkit-based tools require a valid connected account with the specified toolkit
371
-4. `executeToolRequest` can only execute tools from the same toolkit that the custom tool belongs to
372
-5. Each toolkit-based tool can only use one connected account at a time
373
-
374
-## What to read next
375
-
376
-<Cards>
377
- <Card icon={<Play />} title="Executing tools" href="/docs/tools-direct/executing-tools" description="Run tools with providers, agentic frameworks, or direct execution" />
378
- <Card icon={<Wrench />} title="Fetching tools" href="/docs/tools-direct/fetching-tools" description="Fetch and filter tools, inspect schemas, and search semantically" />
379
- <Card icon={<Key />} title="Authenticating tools" href="/docs/tools-direct/authenticating-tools" description="Create auth configs and connect user accounts" />
380
-</Cards>