@devries-cameron20 / composio-1 / commits / 44e5458c3
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.

feat(core): remove legacy TypeScript custom tools (#3509)

This PR is **part 2 of 3** splitting https://github.com/ComposioHQ/composio/pull/3505 to make the removal of the old 2025 custom tools easier to review. It carries the **TypeScript** slice. - builds on top of https://github.com/ComposioHQ/composio/pull/3508 (stacked — review/merge the Python slice first; this PR's base is `remove-py-custom-tools`) - removes the legacy `composio.tools.createCustomTool(...)` in-memory registry: the plural `CustomTools` model, registry wiring, legacy-only tests/examples/`ts/docs` pages, and stale error/type exports - preserves the 2026 tool-router APIs: `experimental_createTool`, `experimental_createToolkit`, `ToolRouter`, `ToolRouterSession`, and inline custom-tool execution - regenerates the TypeScript SDK reference so raw tool listing no longer describes the removed local registry and points to session-scoped custom tools - adds a `@composio/core` minor changeset ## Notes - The committed SDK reference is **verified self-consistent**: `pnpm --filter @composio/core generate:docs` reproduces it with zero diff. - This slice is a byte-identical subset of #3505 — the three split branches recombine to that PR's exact tree. See #3505 for the original verification logs (`typecheck`, `test`, `lint`, `cf-workers` e2e); CI re-runs per PR.

Alberto Schiabel committed Jun 5, 2026 at 10:53 UTC 44e5458c35eec6b172474b3e20e4d40cae6817e8
37 files changed +338 -1908
.changeset/remove-legacy-custom-tools.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/core": minor
3 +---
4 +
5 +Remove the legacy `composio.tools.createCustomTool(...)` in-memory registry API. Use Tool Router custom tools via `experimental_createTool`, `experimental_createToolkit`, and `composio.create(..., { experimental: { customTools, customToolkits } })` instead.
docs/content/reference/sdk-reference/typescript/composio.mdx
+19 -44
@@ -53,7 +53,13 @@ const composio = new Composio({
53 |------|------|-------------|
54 | `authConfigs` | `AuthConfigs` | Manage authentication configurations for toolkits |
55 | `connectedAccounts` | `ConnectedAccounts` | Manage authenticated connections |
56 -| `create` | `object` | Creates a new tool router session for a user. |
56 +| `create` | `object` | Creates a new tool router session for a user.
57 +Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools
58 +should be exposed directly; see `ToolRouterCreateSessionConfig`. |
59 +| `experimental` | `Experimental` | Experimental SDK methods whose shape may change in future releases.
60 +Houses stateful operations like Experimental.updateAcl that
61 +take a client and perform I/O. Stateless experimental factories
62 +(e.g. `experimental_createTool`) stay at the top level. |
63 | `files` | `Files` | Upload and download files |
64 | `mcp` | `MCP` | Model Context Protocol server management |
65 | `provider` | `TProvider` | The tool provider instance used for wrapping tools in framework-specific formats |
@@ -61,7 +67,7 @@ const composio = new Composio({
67 | `toolRouter` | `ToolRouter` | Experimental feature, use with caution |
68 | `tools` | `Tools` | List, retrieve, and execute tools |
69 | `triggers` | `Triggers` | Manage webhook triggers and event subscriptions |
64 -| `use` | `(id: string) => Promise<Session>` | Use an existing tool router session |
70 +| `use` | `object` | Use an existing tool router session |
71
72 ## Methods
73
@@ -166,53 +172,22 @@ getClient(): Composio
172
173 ### getConfig()
174
169 -Get the configuration SDK is initialized with
175 +Get the configuration SDK is initialized with.
176 +
177 +Returns a frozen shallow clone — the SDK has already snapshotted
178 +configuration values such as `dangerouslyAllowAutoUploadDownloadFiles`,
179 +`fileUploadDirs`, and `fileDownloadDir` into its internal models, so
180 +mutating the live config object would silently no-op. Freezing makes
181 +that contract visible at the call site instead of letting the mutation
182 +appear successful.
183
184 ```typescript
172 -getConfig(): ComposioConfig
185 +getConfig(): Readonly<ComposioConfig>
186 ```
187
188 **Returns**
189
177 -`ComposioConfig` — The configuration SDK is initialized with
178 -
179 ----
180 -
181 -## File upload security
182 -
183 -When `dangerouslyAllowAutoUploadDownloadFiles` is true, the SDK can read local file paths and upload them before tool execution (this behavior is **off** by default). The constructor accepts options that work together with the optional `beforeFileUpload` modifier on `tools.execute` (see [Executing tools: security](/docs/tools-direct/executing-tools#security-for-local-file-paths)).
184 -
185 -| Option | Type | Default | Description |
186 -|--------|------|---------|-------------|
187 -| `sensitiveFileUploadProtection` | `boolean` | `true` | When true, local path strings for auto-upload and `files.upload` are checked against a built-in denylist of path segments (for example `.ssh`, `.aws`) and credential-like file names. Set to `false` only if you accept the security tradeoff. |
188 -| `fileUploadPathDenySegments` | `string[]` | `undefined` | Additional single path *components* (directory or file names) merged with the built-in list; matched anywhere in the resolved path. |
189 -| `fileUploadDirs` | `string[] \| false` | `[~/.composio/temp]` | Allowlist of directories the SDK may read during **automatic** upload (when `dangerouslyAllowAutoUploadDownloadFiles: true`). Pass `false` (or `[]`) to reject every local path; URLs and `File`/`Blob` objects still work. Providing a list **replaces** the default — include `~/.composio/temp` explicitly if you want the default staging dir to keep working. Does **not** affect manual `composio.files.upload()` calls. |
190 -| `fileDownloadDir` | `string` | `~/.composio/files` | Directory where files from tool responses marked `file_downloadable` are streamed. |
191 -
192 -Pass **`beforeFileUpload`** on the **third argument** to `composio.tools.execute` (with `beforeExecute` / `afterExecute`), not on the constructor. The hook runs for each `file_uploadable` value before read/upload: return a path string, `false` to abort, or throw. The hook's context includes a `source` field (`'path' | 'url' | 'file'`) so it can scope its logic to local paths vs URLs vs `File` objects.
193 -
194 -**Related errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError`, `ComposioFileUploadPathNotAllowedError`, `ComposioFileNotFoundError` (from `@composio/core`).
195 -
196 -### Restricting automatic uploads to specific directories
197 -
198 -When `dangerouslyAllowAutoUploadDownloadFiles: true`, the SDK only reads local
199 -files from directories in `fileUploadDirs`. This stacks with (it does NOT
200 -replace) the sensitive-path denylist.
201 -
202 -```typescript
203 -// @noErrors
204 -import { Composio } from '@composio/core';
205 -
206 -const composio = new Composio({
207 - apiKey: process.env.COMPOSIO_API_KEY!,
208 - dangerouslyAllowAutoUploadDownloadFiles: true,
209 - // Replaces the default `[~/.composio/temp]`. List every directory you want
210 - // the SDK to read from during tool execution.
211 - fileUploadDirs: ['/srv/agent/uploads', '~/.composio/temp'],
212 -});
213 -```
214 -
215 -Pass `fileUploadDirs: false` (or `[]`) to reject every filesystem path; URLs
216 -and in-memory `File`/`Blob` objects still upload normally.
190 +`Readonly<ComposioConfig>` — The frozen configuration
191 + the SDK is initialized with.
192
193 ---
docs/content/reference/sdk-reference/typescript/connected-accounts.mdx
+22 -3
@@ -19,7 +19,7 @@ const result = await composio.connectedAccounts.list();
19 Deletes a connected account.
20
21 This method permanently removes a connected account from the Composio platform.
22 -This action cannot be undone.
22 +This action cannot be undone and will revoke any access tokens associated with the account.
23
24 ```typescript
25 async delete(nanoid: string): Promise<ConnectedAccountDeleteResponse>
@@ -144,6 +144,22 @@ Compound function to create a new connected account.
144 This function creates a new connected account and returns a connection request.
145 Users can then wait for the connection to be established using the `waitForConnection` method.
146
147 +**Deprecated for Composio-managed OAuth (OAuth1, OAuth2, DCR_OAUTH).**
148 +The legacy `POST endpoint that this method
149 +wraps is being retired for Composio-managed auth configs on redirectable
150 +schemes. The cutover is **2026-05-08** for new organizations and
151 +**2026-07-03** for all remaining organizations. After your org's cutover,
152 +this method will throw ComposioLegacyConnectedAccountsEndpointRetiredError
153 +for that specific combination.
154 +
155 +Use ConnectedAccounts.link for Composio-managed OAuth — it works for
156 +every redirectable scheme regardless of whether the auth config is
157 +Composio-managed or custom, and the return shape is the same.
158 +
159 +Custom auth configs (your own OAuth app) and non-OAuth schemes (API key,
160 +bearer token, basic auth) are unaffected and continue to work on
161 +`initiate()`. See https://docs.composio.dev/docs/changelog/2026/04/24
162 +
163 ```typescript
164 async initiate(userId: string, authConfigId: string, options?: object): Promise<ConnectionRequest>
165 ```
@@ -205,7 +221,7 @@ const connectionRequest = await composio.connectedAccounts.initiate(
221 ### link()
222
223 ```typescript
208 -async link(userId: string, authConfigId: string, options?: { alias?: string; callbackUrl?: string }): Promise<ConnectionRequest>
224 +async link(userId: string, authConfigId: string, options?: object): Promise<ConnectionRequest>
225 ```
226
227 **Parameters**
@@ -318,7 +334,10 @@ const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123')
334
335 ### update()
336
321 -Update a connected account's alias and/or credentials.
337 +Enable or disable a connected account. Accepts `{ enabled: boolean }`.
338 +
339 +For ACL writes on SHARED connections, see
340 +`composio.experimental.updateAcl()`.
341
342 ```typescript
343 async update(nanoid: string, params: ConnectedAccountUpdateStatusParams): Promise<ConnectedAccountUpdateStatusResponse>
docs/content/reference/sdk-reference/typescript/experimental.mdx new
+89
@@ -0,0 +1,89 @@
1 +---
2 +title: Experimental
3 +description: `composio.experimental` namespace. Mirrors the Python SDK's `composio.experimental` mount, with one method per experimental surface. **Shape may change in future releases.**
4 +---
5 +
6 +## Usage
7 +
8 +Access this class through the `composio.experimental` property:
9 +
10 +```typescript
11 +const composio = new Composio({ apiKey: 'your-api-key' });
12 +const result = await composio.experimental.list();
13 +```
14 +
15 +## Methods
16 +
17 +### updateAcl()
18 +
19 +Update the per-user ACL on a SHARED connected account.
20 +**Experimental — shape may change in future releases.**
21 +
22 +Only meaningful for SHARED connections — calling this on a PRIVATE
23 +connection raises `ComposioAclOnlyForSharedError` (400). ACL writes
24 +require the connection's creator or an API key.
25 +
26 +PATCH semantics: omit a field to leave it unchanged; pass an empty
27 +array to clear an allow/deny list. At least one field must be
28 +provided.
29 +
30 +Resolution rule (deny wins):
31 + 1. requesting `userId` in `notAllowedUserIds` → DENY
32 + 2. `allowAllUsers === true` → ALLOW
33 + 3. requesting `userId` in `allowedUserIds` → ALLOW
34 + 4. otherwise → DENY
35 +
36 +```typescript
37 +async updateAcl(nanoid: string, params: { allowAllUsers?: boolean; allowedUserIds?: string[]; notAllowedUserIds?: string[] }): Promise<ConnectedAccountPatchResponse>
38 +```
39 +
40 +**Parameters**
41 +
42 +| Name | Type |
43 +|------|------|
44 +| `nanoid` | `string` |
45 +| `params` | `object` |
46 +
47 +**Returns**
48 +
49 +`Promise<ConnectedAccountPatchResponse>` — The PATCH response (`\{ id, status, success \}`). To read
50 + the updated ACL block, call
51 + `composio.connectedAccounts.get(nanoid)` after the promise
52 + resolves and inspect `account.experimental?.aclConfigForShared`.
53 +
54 +**Example**
55 +
56 +```typescript
57 +import { Composio } from '@composio/core';
58 +
59 +const composio = new Composio({ apiKey: '...' });
60 +
61 +// Allow every userId to use this connection
62 +await composio.experimental.updateAcl('ca_abc', { allowAllUsers: true });
63 +
64 +// Everyone except a specific user
65 +await composio.experimental.updateAcl('ca_abc', {
66 + allowAllUsers: true,
67 + notAllowedUserIds: ['user_bob'],
68 +});
69 +
70 +// Targeted allow
71 +await composio.experimental.updateAcl('ca_abc', {
72 + allowedUserIds: ['user_alice', 'user_bob'],
73 +});
74 +
75 +// Revoke a previously-granted allow list (back to deny-by-default)
76 +await composio.experimental.updateAcl('ca_abc', { allowedUserIds: [] });
77 +```
78 +
79 +**Empty-array semantics — read carefully.** Passing `[]` for either
80 +list **replaces** the list, it does not extend it:
81 +
82 +- `allowedUserIds: []` → revoke all previously-granted user IDs (state
83 + reverts to deny-by-default unless `allowAllUsers` is true).
84 +- `notAllowedUserIds: []` → **clears the deny list**, which silently
85 + re-grants access to users you previously blocked. Always pair an
86 + empty deny list with a deliberate audit of the allow side.
87 +```
88 +
89 +---
docs/content/reference/sdk-reference/typescript/index.mdx
+1
@@ -35,6 +35,7 @@ bun add @composio/core
35 | [`Composio`](/reference/sdk-reference/typescript/composio) | This is the core class for Composio. |
36 | [`AuthConfigs`](/reference/sdk-reference/typescript/auth-configs) | AuthConfigs class |
37 | [`ConnectedAccounts`](/reference/sdk-reference/typescript/connected-accounts) | ConnectedAccounts class |
38 +| [`Experimental`](/reference/sdk-reference/typescript/experimental) | `composio.experimental` namespace. Mirrors the Python SDK's |
39 | [`MCP`](/reference/sdk-reference/typescript/mcp) | MCP (Model Control Protocol) class |
40 | [`RemoteFile`](/reference/sdk-reference/typescript/remote-file) | Represents a file stored in a tool router session's file mount. |
41 | [`SessionContextImpl`](/reference/sdk-reference/typescript/session-context-impl) | Concrete implementation of SessionContext. |
docs/content/reference/sdk-reference/typescript/meta.json
+1
@@ -4,6 +4,7 @@
4 "composio",
5 "auth-configs",
6 "connected-accounts",
7 + "experimental",
8 "mcp",
9 "remote-file",
10 "session-context-impl",
docs/content/reference/sdk-reference/typescript/tool-router-session.mdx
+39 -2
@@ -16,9 +16,12 @@ const result = await composio.toolRouterSession.list();
16
17 | Name | Type |
18 |------|------|
19 +| `configVersion` | `number` |
20 | `experimental` | `SessionExperimental` |
21 | `mcp` | `object` |
22 +| `preload` | `Preload` |
23 | `sessionId` | `string` |
24 +| `warnings` | `Warning[]` |
25
26 ## Methods
27
@@ -27,8 +30,19 @@ const result = await composio.toolRouterSession.list();
30 Initiate an authorization flow for a toolkit.
31 Returns a ConnectionRequest with a redirect URL for the user.
32
33 +Pass `experimental: { accountType: 'SHARED', aclConfigForShared }` to
34 +create a SHARED connection with a per-user ACL in one flow. Default
35 +behaviour (omit the block) creates a PRIVATE connection.
36 +
37 +Experimental — shape may change in future releases.
38 +
39 +`aclConfigForShared` is validated against the same caps as
40 +`composio.connectedAccounts.link()` (≤1000 entries per list, each
41 +`userId` 1..256 characters). Invalid input throws `ValidationError`
42 +at the SDK boundary.
43 +
44 ```typescript
31 -async authorize(toolkit: string, options?: { alias?: string; callbackUrl?: string }): Promise<ConnectionRequest>
45 +async authorize(toolkit: string, options?: object): Promise<ConnectionRequest>
46 ```
47
48 **Parameters**
@@ -89,7 +103,7 @@ full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
103 remote tools are sent to the Composio backend.
104
105 ```typescript
92 -async execute(toolSlug: string, arguments_?: Record<string, unknown>): Promise<{ data: Record<string, unknown>; error: string | null; logId: string }>
106 +async execute(toolSlug: string, arguments_?: Record<string, unknown>, options?: ToolRouterSessionExecuteOptions): Promise<{ data: Record<string, unknown>; error: string | null; logId: string }>
107 ```
108
109 **Parameters**
@@ -98,6 +112,7 @@ async execute(toolSlug: string, arguments_?: Record<string, unknown>): Promise<{
112 |------|------|-------------|
113 | `toolSlug` | `string` | The tool slug to execute |
114 | `arguments_?` | `Record<string, unknown>` | Optional tool arguments |
115 +| `options?` | `ToolRouterSessionExecuteOptions` | Optional execution options |
116
117 **Returns**
118
@@ -191,3 +206,25 @@ async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType>
206 `Promise<ReturnType>`
207
208 ---
209 +
210 +### update()
211 +
212 +Partially update the session configuration.
213 +Only the fields provided will be changed; omitted fields are preserved.
214 +Mutates this session's `configVersion`, `preload`, and `warnings` in-place.
215 +
216 +```typescript
217 +async update(config: object): Promise<void>
218 +```
219 +
220 +**Parameters**
221 +
222 +| Name | Type |
223 +|------|------|
224 +| `config` | `object` |
225 +
226 +**Returns**
227 +
228 +`Promise<void>`
229 +
230 +---
docs/content/reference/sdk-reference/typescript/tools.mdx
+23 -80
@@ -14,72 +14,11 @@ const result = await composio.tools.list();
14
15 ## Methods
16
17 -### createCustomTool()
18 -
19 -Creates a custom tool that can be used within the Composio SDK.
20 -
21 -Custom tools allow you to extend the functionality of Composio with your own implementations
22 -while keeping a consistent interface for both built-in and custom tools.
23 -
24 -```typescript
25 -async createCustomTool(body: CustomToolOptions<T>): Promise<...>
26 -```
27 -
28 -**Parameters**
29 -
30 -| Name | Type | Description |
31 -|------|------|-------------|
32 -| `body` | `CustomToolOptions<T>` | The configuration for the custom tool |
33 -
34 -**Returns**
35 -
36 -`Promise<...>` — The created custom tool
37 -
38 -**Example**
39 -
40 -```typescript
41 -// creating a custom tool with a toolkit
42 -await composio.tools.createCustomTool({
43 - name: 'My Custom Tool',
44 - description: 'A custom tool that does something specific',
45 - slug: 'MY_CUSTOM_TOOL',
46 - userId: 'default',
47 - connectedAccountId: '123',
48 - toolkitSlug: 'github',
49 - inputParameters: z.object({
50 - param1: z.string().describe('First parameter'),
51 - }),
52 - execute: async (input, connectionConfig, executeToolRequest) => {
53 - // Custom logic here
54 - return { data: { result: 'Success!' } };
55 - }
56 -});
57 -```
58 -
59 -```typescript
60 -// creating a custom tool without a toolkit
61 -await composio.tools.createCustomTool({
62 - name: 'My Custom Tool',
63 - description: 'A custom tool that does something specific',
64 - slug: 'MY_CUSTOM_TOOL',
65 - inputParameters: z.object({
66 - param1: z.string().describe('First parameter'),
67 - }),
68 - execute: async (input) => {
69 - // Custom logic here
70 - return { data: { result: 'Success!' } };
71 - }
72 -});
73 -```
74 -
75 ----
76 -
17 ### execute()
18
19 Executes a given tool with the provided parameters.
20
81 -This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
82 -It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
21 +This method calls the Composio API to execute the tool and returns the response.
22
23 **Version Control:**
24 By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest",
@@ -148,12 +87,12 @@ const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
87
88 ---
89
151 -### executeMetaTool()
90 +### executeSessionTool()
91
153 -Executes a composio meta tool based on tool router session
92 +Executes a tool based on a tool router session.
93
94 ```typescript
156 -async executeMetaTool(toolSlug: string, body: { arguments?: Record<string, unknown>; sessionId: string }, modifiers?: SessionExecuteMetaModifiers): Promise<...>
95 +async executeSessionTool(toolSlug: string, body: { arguments?: Record<string, unknown>; sessionId: string }, modifiers?: SessionExecuteMetaModifiers, tool?: object, options?: ToolRouterSessionExecuteOptions): Promise<...>
96 ```
97
98 **Parameters**
@@ -163,6 +102,8 @@ async executeMetaTool(toolSlug: string, body: { arguments?: Record<string, unkno
102 | `toolSlug` | `string` | The slug of the tool to execute |
103 | `body` | `object` | The execution parameters |
104 | `modifiers?` | `SessionExecuteMetaModifiers` | The modifiers to apply to the tool |
105 +| `tool?` | `object` | Optional tool schema used to resolve toolkit metadata for modifiers |
106 +| `options?` | `ToolRouterSessionExecuteOptions` | |
107
108 **Returns**
109
@@ -280,6 +221,9 @@ Retrieves a specific tool by its slug from the Composio API.
221 This method fetches a single tool in raw format without provider-specific wrapping,
222 providing direct access to the tool's schema and metadata. Tool versions are controlled
223 at the Composio SDK initialization level through the `toolkitVersions` configuration.
224 +Local experimental custom tools are session-scoped; attach them when creating or reusing a
225 +Tool Router session, then use `session.tools()`, `session.customTools()`, or
226 +`session.execute()`.
227
228 ```typescript
229 async getRawComposioToolBySlug(slug: string, options?: ToolRetrievalOptions): Promise<...>
@@ -320,9 +264,6 @@ const customizedTool = await composio.tools.getRawComposioToolBySlug(
264 }
265 );
266
323 -// Get a custom tool (will check custom tools first)
324 -const customTool = await composio.tools.getRawComposioToolBySlug('MY_CUSTOM_TOOL');
325 -
267 // Access tool properties
268 const githubTool = await composio.tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
269 console.log({
@@ -339,10 +280,12 @@ console.log({
280
281 ### getRawComposioTools()
282
342 -Lists all tools available in the Composio SDK including custom tools.
283 +Lists Composio API tools available to the SDK.
284
344 -This method fetches tools from the Composio API in raw format and combines them with
345 -any registered custom tools. The response can be filtered and modified as needed.
285 +This method fetches remote Composio tools from the API in raw format. The response can be
286 +filtered and modified as needed. Local experimental custom tools are session-scoped; attach
287 +them when creating or reusing a Tool Router session, then use `session.tools()`,
288 +`session.customTools()`, or `session.execute()`.
289 It provides access to the underlying tool data without provider-specific wrapping.
290
291 ```typescript
@@ -408,32 +351,32 @@ const authSpecificTools = await composio.tools.getRawComposioTools({
351
352 ---
353
411 -### getRawToolRouterMetaTools()
354 +### getRawToolRouterSessionTools()
355
413 -Fetches the meta tools for a tool router session.
414 -This method fetches the meta tools from the Composio API and transforms them to the expected format.
415 -It provides access to the underlying meta tool data without provider-specific wrapping.
356 +Fetches tools exposed by a tool router session.
357 +This includes helper/meta tools plus any tools preloaded into the session.
358 +It provides access to the underlying tool data without provider-specific wrapping.
359
360 ```typescript
418 -async getRawToolRouterMetaTools(sessionId: string, options?: SchemaModifierOptions): Promise<ToolList>
361 +async getRawToolRouterSessionTools(sessionId: string, options?: SchemaModifierOptions): Promise<ToolList>
362 ```
363
364 **Parameters**
365
366 | Name | Type | Description |
367 |------|------|-------------|
425 -| `sessionId` | `string` | \{string\} The session id to get the meta tools for |
368 +| `sessionId` | `string` | \{string\} The session id to get tools for |
369 | `options?` | `SchemaModifierOptions` | \{SchemaModifierOptions\} Optional configuration for tool retrieval |
370
371 **Returns**
372
430 -`Promise<ToolList>` — The list of meta tools
373 +`Promise<ToolList>` — The list of session tools
374
375 **Example**
376
377 ```typescript
435 -const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123');
436 -console.log(metaTools);
378 +const sessionTools = await composio.tools.getRawToolRouterSessionTools('session_123');
379 +console.log(sessionTools);
380 ```
381
382 ---
pnpm-lock.yaml
-22
@@ -529,9 +529,6 @@ importers:
529 dotenv:
530 specifier: ^16.4.1
531 version: 16.6.1
532 - zod:
533 - specifier: 'catalog:'
534 - version: 4.3.6
532 devDependencies:
533 '@types/bun':
534 specifier: ^1.2.9
@@ -581,25 +578,6 @@ importers:
578 specifier: 'catalog:'
579 version: 5.9.3
580
584 - ts/examples/custom-tools:
585 - dependencies:
586 - '@composio/core':
587 - specifier: workspace:*
588 - version: link:../../packages/core
589 - dotenv:
590 - specifier: ^16.4.1
591 - version: 16.6.1
592 - zod:
593 - specifier: 'catalog:'
594 - version: 4.3.6
595 - devDependencies:
596 - '@types/bun':
597 - specifier: ^1.2.9
598 - version: 1.3.9
599 - typescript:
600 - specifier: 'catalog:'
601 - version: 5.9.3
602 -
581 ts/examples/error-handling-demo:
582 dependencies:
583 '@composio/core':
ts/README.md
+19 -29
@@ -6,7 +6,7 @@ The Composio SDK is a powerful toolkit that enables you to integrate third-party
6
7 - Execute tools from various services (GitHub, Gmail, Slack, etc.)
8 - Manage user connections to external services
9 -- Create custom tools with your own logic
9 +- Create session-scoped custom tools with your own logic
10 - Integrate with AI providers like OpenAI
11 - Powerful middleware and modifier support
12 - Extensive error handling
@@ -23,11 +23,11 @@ The SDK is thoroughly documented in the [docs](./docs) directory:
23 ### API Reference
24
25 - [Composio Class](./docs/api/composio.md) - Main SDK class
26 -- [Tools](./docs/api/tools.md) - Using and creating tools
26 +- [Tools](./docs/api/tools.md) - Listing, fetching, and executing tools
27 +- [Tool Router](./docs/api/tool-router.md) - Sessions, search, and custom tools
28 - [Toolkits](./docs/api/toolkits.md) - Working with tool collections
29 - [Connected Accounts](./docs/api/connected-accounts.md) - User authentication
30 - [Auth Configs](./docs/api/auth-configs.md) - Authentication configuration
30 -- [Custom Tools](./docs/api/custom-tools.md) - Creating your own tools
31 - [Providers](./docs/api/providers.md) - AI integration options
32
33 ### Provider Documentation
@@ -142,42 +142,32 @@ if (completion.choices[0].message.tool_calls) {
142 ## Creating Custom Tools
143
144 ```typescript
145 +import { Composio, experimental_createTool } from '@composio/core';
146 import { z } from 'zod';
147
147 -// Create a custom tool
148 -const customTool = await composio.tools.createCustomTool({
148 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
149 +
150 +const weatherForecast = experimental_createTool('WEATHER_FORECAST', {
151 name: 'Weather Forecast',
152 description: 'Get the weather forecast for a location',
151 - slug: 'WEATHER_FORECAST',
153 inputParams: z.object({
154 location: z.string().describe('The location to get the forecast for'),
154 - days: z.number().optional().default(3).describe('Number of days for the forecast')
155 + days: z.number().optional().default(3).describe('Number of days for the forecast'),
156 }),
157 execute: async (input) => {
157 - try {
158 - const { location, days = 3 } = input;
159 -
160 - // Your implementation here
161 - const forecast = [
162 - { date: '2025-05-21', temperature: 72, conditions: 'Sunny' },
163 - { date: '2025-05-22', temperature: 68, conditions: 'Partly Cloudy' },
164 - { date: '2025-05-23', temperature: 65, conditions: 'Rainy' },
165 - ];
166 -
167 - return {
168 - data: { forecast },
169 - successful: true,
170 - error: null,
171 - };
172 - } catch (error) {
173 - return {
174 - data: {},
175 - successful: false,
176 - error: error.message,
177 - };
178 - }
158 + const { location, days = 3 } = input;
159 + const forecast = await getWeatherForecast(location, days);
160 + return { forecast };
161 },
162 });
163 +
164 +const session = await composio.create('default', {
165 + experimental: { customTools: [weatherForecast] },
166 +});
167 +
168 +const result = await session.execute('WEATHER_FORECAST', {
169 + location: 'San Francisco, CA',
170 +});
171 ```
172
173 ## Project Structure
ts/docs/README.md
+2 -3
@@ -20,7 +20,7 @@ Composio SDK allows you to:
20
21 - Execute tools from various services (like GitHub, Gmail, Slack, etc.)
22 - Manage user connections to external services
23 -- Create custom tools
23 +- Create session-scoped custom tools
24 - Implement triggers and event handlers
25 - Integrate with AI providers like OpenAI
26
@@ -42,7 +42,7 @@ The Composio SDK is built around several key concepts:
42 - **Connected Accounts**: User connections to external services
43 - **Auth Configs**: Authentication configurations for external services
44 - **Providers**: Adapters for AI services that can use tools (e.g., OpenAI)
45 -- **Custom Tools**: Tools you can create and define yourself
45 +- **Custom Tools**: Session-scoped local tools created with `experimental_createTool`
46 - **MCP**: Create and manage MCP Servers and clients
47
48 Check out the [Core Concepts](./core-concepts.md) documentation for more detailed information.
@@ -88,7 +88,6 @@ The complete API reference documentation is available here:
88 - [Connected Accounts](./api/connected-accounts.md)
89 - [Auth Configs](./api/auth-configs.md)
90 - [Providers](./api/providers.md)
91 -- [Custom Tools](./api/custom-tools.md)
91 - [MCP](./api/mcp.md)
92 - [ToolRouter](./api/tool-router.md)
93 - [Tool Router Session Files](./api/tool-router-files.md)
ts/docs/advanced/error-handling.md
+11 -35
@@ -172,52 +172,28 @@ try {
172 }
173 ```
174
175 -## Error Handling in Custom Tools
175 +## Error Handling in Session Custom Tools
176
177 -When creating custom tools, implement proper error handling in your handler function:
177 +When creating Tool Router custom tools, throw ordinary errors from the handler when execution cannot continue. The SDK wraps thrown errors into the standard session execution response.
178
179 ```typescript
180 +import { experimental_createTool } from '@composio/core';
181 import { z } from 'zod';
182
182 -const customTool = await composio.tools.createCustomTool({
183 +const customTool = experimental_createTool('MY_CUSTOM_TOOL', {
184 name: 'My Custom Tool',
185 description: 'A custom tool with error handling',
185 - slug: 'MY_CUSTOM_TOOL',
186 inputParams: z.object({
187 - param1: z.string().describe('Required parameter')
187 + param1: z.string().describe('Required parameter'),
188 }),
189 execute: async (input) => {
190 - try {
191 - // Input is already validated by zod
192 - const { param1 } = input;
193 - if (!param1 || param1.trim() === '') {
194 - return {
195 - data: {},
196 - successful: false,
197 - error: 'param1 cannot be empty',
198 - };
199 - }
200 -
201 - // Process the request
202 - // This could throw various errors
203 - const result = await someExternalService(param1);
204 -
205 - return {
206 - data: { result },
207 - successful: true,
208 - error: null,
209 - };
210 - } catch (error) {
211 - // Log the error for debugging
212 - console.error('Error in custom tool:', error);
213 -
214 - // Return a user-friendly error message
215 - return {
216 - data: {},
217 - successful: false,
218 - error: error.message || 'An unexpected error occurred',
219 - };
190 + const { param1 } = input;
191 + if (param1.trim() === '') {
192 + throw new Error('param1 cannot be empty');
193 }
194 +
195 + const result = await someExternalService(param1);
196 + return { result };
197 },
198 });
199 ```
ts/docs/api/custom-tools.md deleted
-204
@@ -1,204 +0,0 @@
1 -# Custom Tools
2 -
3 -Custom tools allow you to create your own tools that can be used with Composio. There are two types of custom tools:
4 -
5 -1. Standalone Tools - Simple tools that don't require any authentication
6 -2. Toolkit-based Tools - Tools that require authentication and can use toolkit credentials
7 -
8 -## Creating a Custom Tool
9 -
10 -### Standalone Tool
11 -
12 -A standalone tool is the simplest form of custom tool. It only requires input parameters and an execute function:
13 -
14 -```typescript
15 -const tool = await composio.tools.createCustomTool({
16 - slug: 'CALCULATE_SQUARE',
17 - name: 'Calculate Square',
18 - description: 'Calculates the square of a number',
19 - inputParams: z.object({
20 - number: z.number().describe('The number to calculate the square of'),
21 - }),
22 - execute: async input => {
23 - const { number } = input;
24 - return {
25 - data: { result: number * number },
26 - error: null,
27 - successful: true,
28 - };
29 - },
30 -});
31 -```
32 -
33 -### Toolkit-based Tool
34 -
35 -A toolkit-based tool has access to two ways of making authenticated requests:
36 -
37 -1. Using `executeToolRequest` - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection and baseURL resolution:
38 -
39 -```typescript
40 -const tool = await composio.tools.createCustomTool({
41 - slug: 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY',
42 - name: 'Github star composio repositories',
43 - toolkitSlug: 'github',
44 - description: 'For any given repository of the user composiohq, star the repository',
45 - inputParams: z.object({
46 - repository: z.string().describe('The repository to star'),
47 - page: z.number().optional().describe('Page number for pagination'),
48 - customHeader: z.string().optional().describe('Custom header value'),
49 - }),
50 - execute: async (input, connectionConfig, executeToolRequest) => {
51 - // executeToolRequest makes authenticated requests to the toolkit's API
52 - // You can use relative paths - Composio will automatically inject the baseURL
53 - const result = await executeToolRequest({
54 - endpoint: `/user/starred/composiohq/${input.repository}`,
55 - method: 'PUT',
56 - body: {},
57 - // Add custom headers or query parameters
58 - parameters: [
59 - // Add query parameters
60 - {
61 - name: 'page',
62 - value: input.page?.toString() || '1',
63 - in: 'query',
64 - },
65 - // Add custom headers
66 - {
67 - name: 'x-custom-header',
68 - value: input.customHeader || 'default-value',
69 - in: 'header',
70 - },
71 - ],
72 - });
73 - return result;
74 - },
75 -});
76 -```
77 -
78 -2. Using `connectionConfig` - For making direct API calls when needed:
79 -
80 -```typescript
81 -const tool = await composio.tools.createCustomTool({
82 - slug: 'GITHUB_DIRECT_API',
83 - name: 'Direct GitHub API Call',
84 - description: 'Makes direct calls to GitHub API',
85 - toolkitSlug: 'github',
86 - inputParams: z.object({
87 - repo: z.string().describe('Repository name'),
88 - }),
89 - execute: async (input, connectionConfig, executeToolRequest) => {
90 - // Use connectionConfig for direct API calls
91 - const result = await fetch(`https://api.github.com/repos/${input.repo}`, {
92 - headers: {
93 - Authorization: `Bearer ${connectionConfig.val?.access_token}`,
94 - },
95 - });
96 -
97 - return {
98 - data: await result.json(),
99 - error: null,
100 - successful: true,
101 - };
102 - },
103 -});
104 -```
105 -
106 -### Using Custom Headers and Query Parameters
107 -
108 -You can add custom headers and query parameters to your toolkit-based tools using the `parameters` option in `executeToolRequest`:
109 -
110 -```typescript
111 -const tool = await composio.tools.createCustomTool({
112 - slug: 'GITHUB_SEARCH_REPOSITORIES',
113 - name: 'Search GitHub Repositories',
114 - description: 'Search for repositories with custom parameters',
115 - toolkitSlug: 'github',
116 - inputParams: z.object({
117 - query: z.string().describe('Search query'),
118 - perPage: z.number().optional().describe('Results per page'),
119 - acceptType: z.string().optional().describe('Custom accept header'),
120 - }),
121 - execute: async (input, connectionConfig, executeToolRequest) => {
122 - const result = await executeToolRequest({
123 - endpoint: '/search/repositories',
124 - method: 'GET',
125 - parameters: [
126 - // Add query parameters for pagination
127 - {
128 - name: 'q',
129 - value: input.query,
130 - in: 'query',
131 - },
132 - {
133 - name: 'per_page',
134 - value: (input.perPage || 30).toString(),
135 - in: 'query',
136 - },
137 - // Add custom headers
138 - {
139 - name: 'Accept',
140 - value: input.acceptType || 'application/vnd.github.v3+json',
141 - in: 'header',
142 - },
143 - {
144 - name: 'X-Custom-Header',
145 - value: 'custom-value',
146 - in: 'header',
147 - },
148 - ],
149 - });
150 - return result;
151 - },
152 -});
153 -```
154 -
155 -## Executing Custom Tools
156 -
157 -You can execute custom tools just like any other tool:
158 -
159 -```typescript
160 -const result = await composio.tools.execute('TOOL_SLUG', {
161 - arguments: {
162 - // Tool input parameters
163 - },
164 - userId: 'user-id',
165 - connectedAccountId: 'optional-account-id', // Required for toolkit-based tools
166 -});
167 -```
168 -
169 -## Type Safety
170 -
171 -The custom tools implementation provides full type safety:
172 -
173 -1. Input parameters are validated using Zod schemas
174 -2. The execute function's parameters are inferred based on whether toolkitSlug is provided:
175 - - Without toolkitSlug: `(input) => Promise<ToolExecuteResponse>`
176 - - With toolkitSlug: `(input, connectionConfig, executeToolRequest) => Promise<ToolExecuteResponse>`
177 -
178 -## Best Practices
179 -
180 -1. Use descriptive names and slugs for your tools
181 -2. Always provide descriptions for input parameters using `describe()`
182 -3. Handle errors gracefully in your execute function
183 -4. For toolkit-based tools:
184 - - Prefer `executeToolRequest` over direct API calls when possible
185 - - Use relative paths with `executeToolRequest` - Composio will automatically inject the correct baseURL
186 - - Use the `parameters` option to add custom headers or query parameters:
187 - ```typescript
188 - parameters: [
189 - { name: 'page', value: '1', in: 'query' }, // Adds ?page=1 to URL
190 - { name: 'x-custom', value: 'value', in: 'header' }, // Adds header
191 - ];
192 - ```
193 - - Remember that `executeToolRequest` can only call tools from the same toolkit
194 - - Use `executeToolRequest` to leverage Composio's automatic credential handling
195 - - Only use `connectionConfig` when you need to make direct API calls or interact with different services
196 -5. Chain multiple toolkit operations using `executeToolRequest` for better maintainability
197 -
198 -## Limitations
199 -
200 -1. Custom tools are stored in memory and are not persisted
201 -2. They need to be recreated when the application restarts
202 -3. Toolkit-based tools require a valid connected account with the specified toolkit
203 -4. `executeToolRequest` can only execute tools from the same toolkit that the custom tool belongs to
204 -5. Each toolkit-based tool can only use one connected account at a time
ts/docs/api/tools.md
+1 -49
@@ -178,46 +178,12 @@ const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
178
179 **Throws:**
180
181 -- `ComposioCustomToolsNotInitializedError`: If the CustomTools instance is not initialized
181 - `ComposioToolNotFoundError`: If the tool with the given slug is not found
182 - `ComposioToolExecutionError`: If there is an error during tool execution
183
185 -### createCustomTool(body)
186 -
187 -Creates a custom tool that can be used within the Composio SDK.
188 -
189 -```typescript
190 -import { z } from 'zod';
191 -
192 -const customTool = await composio.tools.createCustomTool({
193 - name: 'My Custom Tool',
194 - description: 'A custom tool that does something specific',
195 - slug: 'MY_CUSTOM_TOOL',
196 - inputParams: z.object({
197 - param1: z.string().describe('Description of param1'),
198 - param2: z.number().optional().describe('Optional numeric parameter')
199 - }),
200 - execute: async (input) => {
201 - // Custom logic here
202 - console.log('Input:', input.param1, input.param2);
203 - return {
204 - data: { result: 'Success!' },
205 - error: null,
206 - successful: true
207 - };
208 - },
209 -});
210 -```
211 -
212 -**Parameters:**
213 -
214 -- `body` (CustomToolOptions): The configuration for the custom tool
215 -
216 -**Returns:** Promise<Tool> - The created custom tool
217 -
184 ### getRawComposioTools(query, options?)
185
220 -Lists all tools available in the Composio SDK including custom tools. This method provides direct access to tool data without provider-specific wrapping.
186 +Lists all tools available from the Composio API. This method provides direct access to tool data without provider-specific wrapping.
187
188 ```typescript
189 // Get important tools from a toolkit (auto-applies important filter)
@@ -497,17 +463,3 @@ interface ToolExecuteResponse {
463 sessionInfo?: unknown; // Session information
464 }
465 ```
500 -
501 -### CustomToolOptions
502 -
503 -```typescript
504 -interface CustomToolOptions {
505 - name: string; // Name of the custom tool
506 - description: string; // Description of the custom tool
507 - slug: string; // Unique slug for the custom tool
508 - inputParameters: Record<string, unknown>; // Input parameters schema
509 - outputParameters?: Record<string, unknown>; // Output parameters schema
510 - handler: (params: ToolExecuteParams, context: ExecuteMetadata) => Promise<ToolExecuteResponse>; // Handler function
511 -}
512 -```
513 -
ts/docs/core-concepts.md
+15 -12
@@ -402,30 +402,33 @@ Use direct execution when:
402
403 ## Custom Tools
404
405 -Custom Tools allow you to extend Composio's functionality by creating your own tools. You define the input and output parameters and provide a handler function that implements the tool's behavior.
405 +Custom Tools allow you to attach your own local tools to Tool Router sessions. Define them with `experimental_createTool`, then pass them to `composio.create()` under `experimental.customTools`.
406
407 ```typescript
408 +import { Composio, experimental_createTool } from '@composio/core';
409 import { z } from 'zod';
410
410 -// Example: Create a custom tool
411 -const customTool = await composio.tools.createCustomTool({
411 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
412 +
413 +const customTool = experimental_createTool('MY_CUSTOM_TOOL', {
414 name: 'My Custom Tool',
415 description: 'A custom tool that does something specific',
414 - slug: 'MY_CUSTOM_TOOL',
416 inputParams: z.object({
417 param1: z.string().describe('First parameter'),
417 - param2: z.number().optional().describe('Optional parameter')
418 + param2: z.number().optional().describe('Optional parameter'),
419 }),
420 execute: async (input) => {
420 - // Custom logic here
421 - console.log('Received input:', input.param1, input.param2);
422 - return {
423 - data: { result: 'Success!' },
424 - error: null,
425 - successful: true
426 - };
421 + return { result: `Received ${input.param1}` };
422 },
423 });
424 +
425 +const session = await composio.create('default', {
426 + experimental: { customTools: [customTool] },
427 +});
428 +
429 +const result = await session.execute('MY_CUSTOM_TOOL', {
430 + param1: 'hello',
431 +});
432 ```
433
434 ## Triggers
ts/docs/getting-started.md
+17 -31
@@ -283,52 +283,38 @@ For a more complete integration, check out the [OpenAI Provider example](../exam
283
284 ## Creating Custom Tools
285
286 -You can extend Composio by creating your own custom tools:
286 +You can extend Tool Router sessions with your own local custom tools:
287
288 ```typescript
289 +import { Composio, experimental_createTool } from '@composio/core';
290 import { z } from 'zod';
291
291 -// Create a custom tool
292 -const customTool = await composio.tools.createCustomTool({
292 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
293 +
294 +const customTool = experimental_createTool('WEATHER_FORECAST', {
295 name: 'Weather Forecast',
296 description: 'Get the weather forecast for a location',
295 - slug: 'WEATHER_FORECAST',
297 inputParams: z.object({
298 location: z.string().describe('The location to get the forecast for'),
298 - days: z.number().optional().default(3).describe('Number of days for the forecast')
299 + days: z.number().optional().default(3).describe('Number of days for the forecast'),
300 }),
301 execute: async (input) => {
301 - try {
302 - const { location, days = 3 } = input;
303 -
304 - // Here you would call your weather API
305 - const forecast = await getWeatherForecast(location, days);
306 -
307 - return {
308 - data: { forecast },
309 - error: null,
310 - successful: true,
311 - };
312 - } catch (error) {
313 - return {
314 - data: {},
315 - successful: false,
316 - error: error.message,
317 - };
318 - }
302 + const { location, days = 3 } = input;
303 + const forecast = await getWeatherForecast(location, days);
304 + return { forecast };
305 },
306 });
307
322 -// Now you can use your custom tool
323 -const result = await composio.tools.execute('WEATHER_FORECAST', {
324 - userId: 'default',
325 - arguments: {
326 - location: 'San Francisco, CA',
327 - days: 5,
328 - },
308 +const session = await composio.create('default', {
309 + experimental: { customTools: [customTool] },
310 +});
311 +
312 +const result = await session.execute('WEATHER_FORECAST', {
313 + location: 'San Francisco, CA',
314 + days: 5,
315 });
316
331 -console.log(result.data.forecast);
317 +console.log(result.data?.forecast);
318 ```
319
320 For more advanced session management features, check out the [Session Management Guide](./advanced/session-management.md).
ts/e2e-tests/runtimes/cloudflare/cf-workers-files/README.md
+1 -2
@@ -7,7 +7,7 @@ This package tests `@composio/core` file operations in Cloudflare Workers enviro
7 Verifies that:
8 1. `composio.files.upload()` throws the expected "not supported in Cloudflare Workers" error
9 2. `composio.files.download()` throws the expected "not supported in Cloudflare Workers" error
10 -3. The `FileToolModifier.workerd.ts` is correctly loaded and provides the expected error message when `dangerouslyAllowAutoUploadDownloadFiles` is explicitly enabled
10 +3. The `FileToolModifier.workerd.ts` is correctly loaded and surfaces the expected error from `composio.tools.execute()` when `dangerouslyAllowAutoUploadDownloadFiles` is explicitly enabled (covered directly in `test/files.spec.ts`, not via an endpoint)
11 4. Composio initializes correctly with the default configuration (`dangerouslyAllowAutoUploadDownloadFiles: false` in workerd runtime)
12 5. Composio can be explicitly initialized with `dangerouslyAllowAutoUploadDownloadFiles: false`
13
@@ -18,7 +18,6 @@ Verifies that:
18 | `GET /` | Lists all available test endpoints |
19 | `GET /test/files/upload` | Tests that `files.upload()` throws the expected error |
20 | `GET /test/files/download` | Tests that `files.download()` throws the expected error |
21 -| `GET /test/file-modifier/error-message` | Tests the error when `dangerouslyAllowAutoUploadDownloadFiles: true` is explicitly set |
21 | `GET /test/auto-upload-disabled` | Tests Composio initialization with explicit `dangerouslyAllowAutoUploadDownloadFiles: false` |
22 | `GET /test/default-config` | Tests Composio initialization with default configuration (no explicit setting) |
23
ts/e2e-tests/runtimes/cloudflare/cf-workers-files/src/index.ts
-57
@@ -4,7 +4,6 @@
4 * and that the FileToolModifier.workerd.ts is properly loaded.
5 */
6 import { Composio } from '@composio/core';
7 -import { z } from 'zod/v3';
7 import { Hono } from 'hono';
8
9 type Bindings = {
@@ -22,7 +21,6 @@ app.get('/', c => {
21 endpoints: [
22 '/test/files/upload',
23 '/test/files/download',
25 - '/test/file-modifier/error-message',
24 '/test/auto-upload-disabled',
25 '/test/default-config',
26 ],
@@ -93,61 +91,6 @@ app.get('/test/files/download', async c => {
91 }
92 });
93
96 -/**
97 - * Test: FileToolModifier behavior (triggers the auto-upload/download error)
98 - *
99 - * The FileToolModifier.workerd.ts throws an error when automatic file upload/download is enabled.
100 - * In workerd runtime, the default is off, so we explicitly opt in here to test the error.
101 - *
102 - * This endpoint actually executes a tool to trigger the real error from FileToolModifier.workerd.ts.
103 - */
104 -app.get('/test/file-modifier/error-message', async c => {
105 - try {
106 - const composio = new Composio({
107 - apiKey: c.env.COMPOSIO_API_KEY,
108 - dangerouslyAllowAutoUploadDownloadFiles: true,
109 - });
110 -
111 - // Use a local custom tool to avoid depending on remote Composio tool registry.
112 - // Any execute() with automatic file handling enabled will trigger FileToolModifier
113 - // in the workerd runtime.
114 - await composio.tools.createCustomTool({
115 - slug: 'CUSTOM_FILE_TOOL',
116 - name: 'Custom File Tool',
117 - inputParams: z.object({
118 - file: z.string(),
119 - }),
120 - execute: async () => ({
121 - data: {},
122 - error: null,
123 - successful: true,
124 - logId: undefined,
125 - sessionInfo: undefined,
126 - }),
127 - });
128 -
129 - await composio.tools.execute('CUSTOM_FILE_TOOL', {
130 - arguments: {
131 - file: 'https://example.com/test.pdf',
132 - },
133 - dangerouslySkipVersionCheck: true,
134 - });
135 -
136 - // If we get here, the test failed - execution should have thrown
137 - return c.json(
138 - {
139 - error: 'Expected tool execution to throw FileToolModifier error, but it did not',
140 - },
141 - { status: 500 }
142 - );
143 - } catch (error) {
144 - const errorMessage = error instanceof Error ? error.message : String(error);
145 - return c.json({
146 - error: errorMessage,
147 - });
148 - }
149 -});
150 -
94 /**
95 * Test: Composio initialization with automatic file upload/download disabled
96 *
ts/e2e-tests/runtimes/cloudflare/cf-workers-files/test/files.spec.ts
+41 -13
@@ -1,10 +1,15 @@
1 import { env, createExecutionContext, waitOnExecutionContext } from 'cloudflare:test';
2 -import { describe, it, expect } from 'vitest';
2 +import { describe, it, expect, vi, afterEach } from 'vitest';
3 +import { Composio, type Tool } from '@composio/core';
4 import app from '../src/index';
5
6 const IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
7
8 describe('@composio/core Files - Cloudflare Workers compatibility', () => {
9 + afterEach(() => {
10 + vi.restoreAllMocks();
11 + });
12 +
13 it('should list the available endpoints', async () => {
14 const request = new IncomingRequest('http://localhost/');
15 const ctx = createExecutionContext();
@@ -23,7 +28,6 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
28 [
29 "/test/files/upload",
30 "/test/files/download",
26 - "/test/file-modifier/error-message",
31 "/test/auto-upload-disabled",
32 "/test/default-config",
33 ]
@@ -60,19 +64,43 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
64 expect(body.error).toContain('not supported in Cloudflare Workers');
65 });
66
63 - it('should throw FileToolModifier error when executing a tool in Cloudflare Workers', async () => {
64 - const request = new IncomingRequest('http://localhost/test/file-modifier/error-message');
65 - const ctx = createExecutionContext();
66 - const response = await app.fetch(request, env, ctx);
67 - await waitOnExecutionContext(ctx);
68 -
69 - expect(response.status).toBe(200);
70 -
71 - const body = (await response.json()) as {
72 - error?: string;
67 + it('should surface the edge-runtime FileToolModifier error from execute() when auto-upload is enabled', async () => {
68 + // Runs inside workerd (vitest-pool-workers), so `#file_tool_modifier` resolves to the
69 + // .workerd variant — the exact module under test. We drive the real public execute()
70 + // pipeline and stub only the network tool lookup, so the before-execute file modifier
71 + // is reached without depending on a remote tool registry or network access.
72 + const composio = new Composio({
73 + apiKey: env.COMPOSIO_API_KEY,
74 + dangerouslyAllowAutoUploadDownloadFiles: true,
75 + });
76 +
77 + const fileTool: Tool = {
78 + slug: 'CUSTOM_FILE_TOOL',
79 + name: 'Custom File Tool',
80 + description: 'Fixture tool with a file-uploadable input',
81 + inputParameters: {
82 + type: 'object',
83 + properties: {
84 + file: {
85 + type: 'string',
86 + file_uploadable: true,
87 + },
88 + },
89 + required: ['file'],
90 + },
91 + toolkit: { slug: 'custom', name: 'custom' },
92 };
93
75 - expect(body.error).toContain('not available on edge runtimes');
94 + vi.spyOn(composio.tools, 'getRawComposioToolBySlug').mockResolvedValue(fileTool);
95 +
96 + await expect(
97 + composio.tools.execute('CUSTOM_FILE_TOOL', {
98 + arguments: {
99 + file: 'https://example.com/test.pdf',
100 + },
101 + dangerouslySkipVersionCheck: true,
102 + })
103 + ).rejects.toThrow('not available on edge runtimes');
104 });
105
106 it('should successfully initialize Composio with automatic file handling disabled', async () => {
ts/examples/cjs/package.json
+1 -2
@@ -14,8 +14,7 @@
14 "packageManager": "pnpm@10.28.0",
15 "dependencies": {
16 "@composio/core": "workspace:*",
17 - "dotenv": "^16.4.1",
18 - "zod": "catalog:"
17 + "dotenv": "^16.4.1"
18 },
19 "devDependencies": {
20 "@types/bun": "^1.2.9",
ts/examples/cjs/src/index.cjs
+6 -21
@@ -1,31 +1,16 @@
1 const { Composio } = require('@composio/core');
2 -const { z } = require('zod/v3');
2 require('dotenv/config');
3
5 -const composio = new Composio()
4 +const composio = new Composio({
5 + apiKey: process.env.COMPOSIO_API_KEY,
6 +});
7
8 async function main() {
8 - console.log('Creating custom tool...');
9 + console.log('Fetching tools enum...');
10
10 - const tool = await composio.tools.createCustomTool({
11 - name: 'My Custom Tool',
12 - description: 'A custom tool that does something specific',
13 - slug: 'MY_CUSTOM_TOOL',
14 - inputParams: z.object({
15 - param1: z.string().describe('First parameter'),
16 - }),
17 - execute: async (_input) => {
18 - return {
19 - data: {
20 - result: 'Success!',
21 - },
22 - error: null,
23 - successful: true,
24 - };
25 - },
26 - });
11 + const tools = await composio.tools.getToolsEnum();
12
28 - console.log('Custom tool created:', tool);
13 + console.log('Tools enum fetched:', tools.items.length);
14 }
15
16 main()
ts/examples/custom-tools/.env.example deleted
-6
@@ -1,6 +0,0 @@
1 -# Composio API Key - Get it from https://app.composio.dev
2 -COMPOSIO_API_KEY=your_composio_api_key_here
3 -
4 -# Add other environment variables as needed for your example
5 -# OPENAI_API_KEY=your_openai_api_key_here
6 -# ANTHROPIC_API_KEY=your_anthropic_api_key_here
ts/examples/custom-tools/README.md deleted
-165
@@ -1,165 +0,0 @@
1 -# Custom Tools Examples
2 -
3 -This directory contains examples demonstrating how to create and use custom tools with Composio SDK.
4 -
5 -## Examples
6 -
7 -### 1. Simple Custom Tool (`simple.ts`)
8 -
9 -Shows how to create a basic standalone tool that doesn't require authentication. The example creates a tool that calculates the square of a number:
10 -
11 -```typescript
12 -const tool = await composio.tools.createCustomTool({
13 - slug: 'CALCULATE_SQUARE',
14 - name: 'Calculate Square',
15 - description: 'Calculates the square of a number',
16 - inputParams: z.object({
17 - number: z.number().describe('The number to calculate the square of'),
18 - }),
19 - execute: async input => {
20 - const { number } = input;
21 - return {
22 - data: { result: number * number },
23 - error: null,
24 - successful: true,
25 - };
26 - },
27 -});
28 -```
29 -
30 -### 2. Toolkit-based Tools (`auth-credentials.ts`)
31 -
32 -Demonstrates two approaches to making authenticated requests in toolkit-based tools:
33 -
34 -#### Using executeToolRequest (Recommended)
35 -
36 -```typescript
37 -const tool = await composio.tools.createCustomTool({
38 - slug: 'GITHUB_LIST_AND_STAR',
39 - name: 'List and Star Repository',
40 - description: 'Lists repositories and stars them',
41 - toolkitSlug: 'github',
42 - inputParams: z.object({
43 - owner: z.string().describe('Repository owner'),
44 - }),
45 - execute: async (input, connectionConfig, executeToolRequest) => {
46 - // executeToolRequest can only call tools from the 'github' toolkit
47 - // Uses the same connected account credentials automatically
48 - const listResult = await executeToolRequest({
49 - slug: 'LIST_REPOSITORIES', // must be a github toolkit tool
50 - arguments: { owner: input.owner },
51 - });
52 -
53 - const starResult = await executeToolRequest({
54 - slug: 'STAR_REPOSITORY', // must be a github toolkit tool
55 - arguments: {
56 - owner: input.owner,
57 - repo: listResult.data.repositories[0].name,
58 - },
59 - });
60 -
61 - return {
62 - data: { listed: listResult.data, starred: starResult.data },
63 - error: null,
64 - successful: true,
65 - };
66 - },
67 -});
68 -```
69 -
70 -#### Using Direct API Calls
71 -
72 -```typescript
73 -const tool = await composio.tools.createCustomTool({
74 - slug: 'GITHUB_STAR_REPO',
75 - name: 'Star GitHub Repository',
76 - toolkitSlug: 'github',
77 - description: 'Stars a GitHub repository using direct API call',
78 - inputParams: z.object({
79 - repository: z.string().describe('The repository to star'),
80 - }),
81 - execute: async (input, connectionConfig) => {
82 - // Use connectionConfig for direct API calls or when interacting with different services
83 - const result = await fetch(
84 - `https://api.github.com/user/starred/composiohq/${input.repository}`,
85 - {
86 - method: 'PUT',
87 - headers: {
88 - Authorization: `Bearer ${connectionConfig.val?.access_token}`,
89 - },
90 - }
91 - );
92 - return {
93 - data: await result.json(),
94 - error: null,
95 - successful: true,
96 - };
97 - },
98 -});
99 -```
100 -
101 -## Running the Examples
102 -
103 -1. Set up your environment:
104 -
105 - ```bash
106 - cp .env.example .env
107 - ```
108 -
109 -2. Add your Composio API key to `.env`:
110 -
111 - ```
112 - COMPOSIO_API_KEY=your_api_key_here
113 - ```
114 -
115 -3. Run an example:
116 -
117 - ```bash
118 - # Run the simple example
119 - pnpm start:simple
120 -
121 - # Run the auth credentials example
122 - pnpm start:auth
123 - ```
124 -
125 -## Key Concepts
126 -
127 -1. **Standalone vs Toolkit-based Tools**
128 -
129 - - Standalone tools only receive input parameters
130 - - Toolkit-based tools have access to both `executeToolRequest` and `connectionConfig`
131 -
132 -2. **Authentication Methods**
133 -
134 - - `executeToolRequest`: Recommended way to use toolkit tools
135 - - Can only execute tools from the same toolkit
136 - - Uses the connected account credentials automatically
137 - - No need to manage auth tokens
138 - - Better maintainability and security
139 - - `connectionConfig`: For direct API calls
140 - - Use when you need to make direct API calls
141 - - Use when you need to interact with different services
142 - - Requires manual token management
143 - - More flexible but requires more maintenance
144 -
145 -3. **Type Safety**
146 -
147 - - Input parameters are validated using Zod schemas
148 - - TypeScript infers the correct execute function signature based on toolkitSlug
149 -
150 -4. **Error Handling**
151 -
152 - - Tools should always return a ToolExecuteResponse
153 - - Handle errors gracefully and provide meaningful error messages
154 -
155 -## Related Examples
156 -
157 -- [OpenAI Example](../openai) - Shows integration with OpenAI
158 -- [LangChain Example](../langchain) - Shows integration with LangChain
159 -- [More Examples](../) - Browse all available examples
160 -
161 -## Support
162 -
163 -- [Documentation](https://docs.composio.dev)
164 -- [Discord Community](https://discord.gg/composio)
165 -- [GitHub Issues](https://github.com/composio/composio/issues)
ts/examples/custom-tools/package.json deleted
-30
@@ -1,30 +0,0 @@
1 -{
2 - "name": "custom-tools-example",
3 - "private": true,
4 - "version": "0.1.0",
5 - "description": "Example project for Custom-tools",
6 - "main": "src/index.ts",
7 - "scripts": {
8 - "clean": "git clean -xdf node_modules",
9 - "start": "bun src/index.ts",
10 - "dev": "bun --watch src/index.ts",
11 - "test": "echo \"Error: no test specified\" && exit 1"
12 - },
13 - "keywords": [
14 - "composio",
15 - "example",
16 - "custom-tools"
17 - ],
18 - "author": "",
19 - "license": "ISC",
20 - "packageManager": "pnpm@10.28.0",
21 - "dependencies": {
22 - "@composio/core": "workspace:*",
23 - "dotenv": "^16.4.1",
24 - "zod": "catalog:"
25 - },
26 - "devDependencies": {
27 - "@types/bun": "^1.2.9",
28 - "typescript": "catalog:"
29 - }
30 -}
ts/examples/custom-tools/src/connection-config.ts deleted
-88
@@ -1,88 +0,0 @@
1 -/**
2 - * Custom-tools Example
3 - *
4 - * This example demonstrates how to use Composio SDK for custom-tools with auth credentials.
5 - *
6 - * Prerequisites:
7 - * 1. Set up your COMPOSIO_API_KEY in the .env file
8 - * 3. Run the example: pnpm start
9 - */
10 -
11 -import { Composio } from '@composio/core';
12 -import 'dotenv/config';
13 -import { z } from 'zod';
14 -
15 -/**
16 - * Initialize Composio
17 - */
18 -const composio = new Composio({
19 - apiKey: process.env.COMPOSIO_API_KEY,
20 -});
21 -
22 -/**
23 - * Create a custom hackernews tool
24 - * This tool will be registerd in the composio instance and store in memory temporarily.
25 - */
26 -const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';
27 -const tool = await composio.tools.createCustomTool({
28 - slug: customToolSlug,
29 - name: 'Github star composio repositories',
30 - toolkitSlug: 'github',
31 - description: 'For any given repository of the user composiohq, star the repository',
32 - inputParams: z.object({
33 - repository: z.string().describe('The repository to star'),
34 - }),
35 - execute: async (input, connectionConfig) => {
36 - console.log('🚀 ~ execute: ~ params:', input);
37 - console.log('🚀 ~ execute: ~ connectionConfig:', connectionConfig);
38 - /**
39 - * The auth credentials are the auth credentials for the connected account.
40 - * You can use them to make requests to the API.
41 - */
42 - const result = await fetch(
43 - `https://api.github.com/user/starred/composiohq/${input.repository}`,
44 - {
45 - method: 'PUT',
46 - headers: {
47 - Authorization: `Bearer ${connectionConfig?.val?.access_token}`,
48 - },
49 - }
50 - );
51 - const data = await result.json();
52 - return {
53 - data: data,
54 - error: null,
55 - successful: true,
56 - };
57 - },
58 -});
59 -
60 -console.log('🚀 created tool:', tool);
61 -
62 -/**
63 - * Main function to run the example
64 - */
65 -async function main() {
66 - try {
67 - console.log('🚀 Starting Custom-tools Example...');
68 -
69 - // Get available tools
70 - const tools = await composio.tools.get('default', customToolSlug);
71 -
72 - console.log('tools:', tools);
73 -
74 - const result = await composio.tools.execute(customToolSlug, {
75 - arguments: {
76 - repository: 'composio',
77 - },
78 - userId: 'default',
79 - });
80 -
81 - console.log('🚀 Result:', result);
82 - } catch (error) {
83 - console.error('❌ Error running example:', error);
84 - }
85 -}
86 -
87 -// Run the example
88 -main().catch(console.error);
ts/examples/custom-tools/src/index.ts deleted
-75
@@ -1,75 +0,0 @@
1 -/**
2 - * Custom-tools Example
3 - *
4 - * This example demonstrates how to use Composio SDK for custom-tools.
5 - *
6 - * Prerequisites:
7 - * 1. Set up your COMPOSIO_API_KEY in the .env file
8 - * 3. Run the example: pnpm start
9 - */
10 -
11 -import { Composio } from '@composio/core';
12 -import 'dotenv/config';
13 -import { z } from 'zod';
14 -
15 -/**
16 - * Initialize Composio
17 - */
18 -const composio = new Composio({
19 - apiKey: process.env.COMPOSIO_API_KEY,
20 -});
21 -
22 -/**
23 - * Create a custom hackernews tool
24 - * This tool will be registerd in the composio instance and store in memory temporarily.
25 - */
26 -const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';
27 -const tool = await composio.tools.createCustomTool({
28 - slug: customToolSlug,
29 - name: 'Github star composio repositories',
30 - toolkitSlug: 'github',
31 - description: 'For any given repository of the user composiohq, star the repository',
32 - inputParams: z.object({
33 - repository: z.string().describe('The repository to star'),
34 - }),
35 - execute: async (input, connectionConfig, executeToolRequest) => {
36 - console.log('🚀 ~ execute: ~ params:', input);
37 - console.log('🚀 ~ execute: ~ connectionConfig:', connectionConfig);
38 -
39 - const result = await executeToolRequest({
40 - endpoint: `/user/starred/composiohq/${input.repository}`,
41 - method: 'PUT',
42 - });
43 - return result;
44 - },
45 -});
46 -
47 -console.log('🚀 created tool:', tool);
48 -
49 -/**
50 - * Main function to run the example
51 - */
52 -async function main() {
53 - try {
54 - console.log('🚀 Starting Custom-tools Example...');
55 -
56 - // Get available tools
57 - const tools = await composio.tools.get('default', customToolSlug);
58 -
59 - console.log('tools:', tools);
60 -
61 - const result = await composio.tools.execute(customToolSlug, {
62 - arguments: {
63 - repository: 'composio',
64 - },
65 - userId: 'default',
66 - });
67 -
68 - console.log('🚀 Result:', result);
69 - } catch (error) {
70 - console.error('❌ Error running example:', error);
71 - }
72 -}
73 -
74 -// Run the example
75 -main().catch(console.error);
ts/examples/custom-tools/src/simple.ts deleted
-76
@@ -1,76 +0,0 @@
1 -/**
2 - * Custom-tools Example
3 - *
4 - * This example demonstrates how to use Composio SDK for simple custom-tools.
5 - *
6 - * Prerequisites:
7 - * 1. Set up your COMPOSIO_API_KEY in the .env file
8 - * 3. Run the example: pnpm start
9 - */
10 -
11 -import { Composio } from '@composio/core';
12 -import 'dotenv/config';
13 -import { z } from 'zod';
14 -
15 -/**
16 - * Initialize Composio
17 - */
18 -const composio = new Composio({
19 - apiKey: process.env.COMPOSIO_API_KEY,
20 -});
21 -
22 -/**
23 - * Create a custom calculate square of a number tool
24 - * This tool will be registerd in the composio instance and store in memory temporarily.
25 - */
26 -const customToolSlug = 'CALCULATE_SQUARE_OF_A_NUMBER';
27 -const tool = await composio.tools.createCustomTool({
28 - slug: customToolSlug,
29 - name: 'Calculate square of a number',
30 - description: 'For any given number the tool calculates the square of the number',
31 - inputParams: z.object({
32 - number: z.number().describe('The number to calculate the square of'),
33 - }),
34 - execute: async input => {
35 - const { number } = input;
36 - const result = Number(number) * Number(number);
37 -
38 - return {
39 - data: {
40 - result,
41 - },
42 - error: null,
43 - successful: true,
44 - };
45 - },
46 -});
47 -
48 -console.log('🚀 created tool:', tool);
49 -
50 -/**
51 - * Main function to run the example
52 - */
53 -async function main() {
54 - try {
55 - console.log('🚀 Starting Custom-tools Example...');
56 -
57 - // Get available tools
58 - const tools = await composio.tools.get('default', customToolSlug);
59 -
60 - console.log('tools:', tools);
61 -
62 - const result = await composio.tools.execute(customToolSlug, {
63 - arguments: {
64 - number: 2,
65 - },
66 - userId: 'default',
67 - });
68 -
69 - console.log('🚀 Result:', result);
70 - } catch (error) {
71 - console.error('❌ Error running example:', error);
72 - }
73 -}
74 -
75 -// Run the example
76 -main().catch(console.error);
ts/examples/custom-tools/tsconfig.json deleted
-16
@@ -1,16 +0,0 @@
1 -{
2 - "compilerOptions": {
3 - "target": "es2022",
4 - "module": "esnext",
5 - "declaration": true,
6 - "declarationDir": "./dist",
7 - "outDir": "./dist",
8 - "rootDir": "./src",
9 - "strict": true,
10 - "esModuleInterop": true,
11 - "moduleResolution": "bundler",
12 - "skipLibCheck": true,
13 - "resolveJsonModule": true
14 - },
15 - "include": ["src"]
16 -}
ts/packages/core/scripts/generate-docs.ts
-1
@@ -21,7 +21,6 @@ const TEMP_JSON = join(PACKAGE_DIR, '.typedoc-output.json');
21
22 // Internal classes that should NOT be documented (accessed via other APIs)
23 const INTERNAL_CLASSES = new Set([
24 - 'CustomTools', // Internal - accessed via composio.tools.createCustomTool()
24 'AuthScheme', // Utility class
25 'ConnectionRequest', // Utility
26 'Files', // Not yet stable API
ts/packages/core/src/errors/ToolErrors.ts
-17
@@ -6,7 +6,6 @@ export const ToolErrorCodes = {
6 TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
7 TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
8 INVALID_MODIFIER: 'INVALID_MODIFIER',
9 - CUSTOM_TOOLS_NOT_INITIALIZED: 'CUSTOM_TOOLS_NOT_INITIALIZED',
9 TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
10 INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
11 GLOBAL_EXECUTE_TOOL_FN_NOT_SET: 'GLOBAL_EXECUTE_TOOL_FN_NOT_SET',
@@ -61,22 +60,6 @@ export class ComposioInvalidModifierError extends ComposioError {
60 }
61 }
62
64 -export class ComposioCustomToolsNotInitializedError extends ComposioError {
65 - constructor(
66 - message: string = 'Custom tools not initialized',
67 - options: Omit<ComposioErrorOptions, 'code'> = {}
68 - ) {
69 - super(message, {
70 - ...options,
71 - code: ToolErrorCodes.CUSTOM_TOOLS_NOT_INITIALIZED,
72 - possibleFixes: options.possibleFixes || [
73 - 'Ensure the custom tools class is initialized in the Tools instance',
74 - ],
75 - });
76 - this.name = 'ComposioCustomToolsNotInitializedError';
77 - }
78 -}
79 -
63 export class ComposioToolExecutionError extends ComposioError {
64 constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {
65 super(message, {
ts/packages/core/src/models/CustomTool.ts
+10 -1
@@ -34,7 +34,6 @@ import {
34 type CustomToolsMapEntry,
35 type CustomToolWireDefinition,
36 type CustomToolkitWireDefinition,
37 - type InputParamsSchema,
37 } from '../types/customTool.types';
38 import type {
39 SessionCreateResponse,
@@ -49,6 +48,16 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
48 /** Maximum allowed length for the final prefixed slug. */
49 const MAX_SLUG_LENGTH = 60;
50
51 +type InputParamsSchema = {
52 + definitions: {
53 + input: {
54 + type: string;
55 + properties: Record<string, unknown>;
56 + required?: string[];
57 + };
58 + };
59 +};
60 +
61 /**
62 * Compute the final slug length for a tool given its context.
63 * Returns the expected length of LOCAL_[TOOLKIT_]SLUG.
ts/packages/core/src/models/CustomTools.ts deleted
-342
@@ -1,342 +0,0 @@
1 -/**
2 - * @fileoverview Custom tools class for Composio SDK, used to manage custom tools created by users.
3 - *
4 - * @author Musthaq Ahamad <musthaq@composio.dev>
5 - * @date 2025-05-05
6 - * @module CustomTools
7 - */
8 -import ComposioClient from '@composio/client';
9 -import {
10 - CustomToolInputParameter,
11 - CustomToolOptions,
12 - CustomToolRegistry,
13 - InputParamsSchema,
14 -} from '../types/customTool.types';
15 -import * as zodToJsonSchema from 'zod-to-json-schema';
16 -import {
17 - Tool,
18 - ToolExecuteParams,
19 - ToolExecuteResponse,
20 - ToolList,
21 - ToolProxyParams,
22 -} from '../types/tool.types';
23 -import logger from '../utils/logger';
24 -import {
25 - ComposioInvalidExecuteFunctionError,
26 - ComposioToolNotFoundError,
27 -} from '../errors/ToolErrors';
28 -import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsErrors';
29 -import { ComposioError } from '../errors/ComposioError';
30 -import { telemetry } from '../telemetry/Telemetry';
31 -import { ConnectedAccountRetrieveResponse } from '../types/connectedAccounts.types';
32 -import { ValidationError } from '../errors';
33 -import { transformConnectedAccountResponse } from '../utils/transformers/connectedAccounts';
34 -import { ConnectionData } from '../types/connectedAccountAuthStates.types';
35 -import { AuthSchemeTypes } from '../types/authConfigs.types';
36 -
37 -export class CustomTools {
38 - private readonly client: ComposioClient;
39 - private readonly customToolsRegistry: CustomToolRegistry;
40 -
41 - constructor(client: ComposioClient) {
42 - if (!client) {
43 - throw new ComposioError('ComposioClient is required');
44 - }
45 - this.client = client;
46 - this.customToolsRegistry = new Map();
47 - telemetry.instrument(this, 'CustomTools');
48 - }
49 -
50 - /**
51 - * Create a custom tool and registers it in the registry.
52 - * This is just an in memory registry and is not persisted.
53 - * @param {CustomToolOptions} toolOptions CustomToolOptions
54 - * @returns {Tool} The tool created
55 - *
56 - * @example
57 - * ```typescript
58 - * // Create a custom tool with input parameters
59 - * const customTool = await composio.customTools.createTool({
60 - * name: 'My Custom Tool',
61 - * description: 'A tool that performs a custom operation',
62 - * slug: 'MY_CUSTOM_TOOL',
63 - * inputParams: z.object({
64 - * query: z.string().describe('The search query'),
65 - * limit: z.number().optional().describe('Maximum number of results')
66 - * }),
67 - * execute: async (input, connectionConfig, executeToolRequest) => {
68 - * // Custom implementation logic
69 - * return {
70 - * data: { results: ['result1', 'result2'] }
71 - * };
72 - * }
73 - * });
74 - * ```
75 - */
76 - async createTool<T extends CustomToolInputParameter>(
77 - toolOptions: CustomToolOptions<T>
78 - ): Promise<Tool> {
79 - const { slug, execute, inputParams, name, description } = toolOptions;
80 - if (!slug || !execute || !inputParams || !name) {
81 - throw new Error('Invalid tool options');
82 - }
83 - // generate the input parameters schema
84 - const paramsSchema: InputParamsSchema = zodToJsonSchema.default(inputParams, {
85 - name: 'input',
86 - }) as InputParamsSchema;
87 - const paramsSchemaJson = paramsSchema.definitions.input;
88 - const toolSchema: Tool = {
89 - name: name,
90 - slug: slug,
91 - description: description,
92 - inputParameters: {
93 - title: name,
94 - type: 'object',
95 - description: description,
96 - properties: paramsSchemaJson.properties,
97 - required: paramsSchemaJson.required,
98 - },
99 - // the output parameters are not used yet
100 - outputParameters: {
101 - type: 'object',
102 - title: `Response for ${name}`,
103 - properties: {},
104 - },
105 - tags: [],
106 - // this is never set to the user provided toolkitslug so that we can differentiate
107 - // the toolkitslug is used via the execute function.
108 - toolkit: { name: 'custom', slug: 'custom' },
109 - };
110 -
111 - this.customToolsRegistry.set(slug.toLowerCase(), {
112 - options: toolOptions as unknown as CustomToolOptions<CustomToolInputParameter>,
113 - schema: toolSchema,
114 - });
115 - return toolSchema;
116 - }
117 -
118 - /**
119 - * Get all the custom tools from the registry.
120 - * @param {string[]} param0.toolSlugs The slugs of the tools to get
121 - * @returns {ToolList} The list of tools
122 - *
123 - * @example
124 - * ```typescript
125 - * // Get all custom tools
126 - * const allTools = await composio.customTools.getCustomTools({});
127 - *
128 - * // Get specific custom tools by slug
129 - * const specificTools = await composio.customTools.getCustomTools({
130 - * toolSlugs: ['MY_CUSTOM_TOOL', 'ANOTHER_CUSTOM_TOOL']
131 - * });
132 - * ```
133 - */
134 - async getCustomTools({ toolSlugs }: { toolSlugs?: string[] }): Promise<ToolList> {
135 - const tools: Tool[] = [];
136 -
137 - if (toolSlugs) {
138 - // If specific slugs are provided, only return those tools
139 - for (const slug of toolSlugs) {
140 - const tool = this.customToolsRegistry.get(slug.toLowerCase());
141 - if (tool) {
142 - tools.push(tool.schema);
143 - }
144 - }
145 - } else {
146 - // If no slugs provided, return all tools
147 - return Array.from(this.customToolsRegistry.values()).map(tool => tool.schema);
148 - }
149 -
150 - return tools;
151 - }
152 -
153 - /**
154 - * Get a custom tool by slug from the registry.
155 - * @param {string} slug The slug of the tool to get
156 - * @returns {Tool} The tool
157 - *
158 - * @example
159 - * ```typescript
160 - * // Get a specific custom tool by its slug
161 - * const myTool = await composio.customTools.getCustomToolBySlug('MY_CUSTOM_TOOL');
162 - * if (myTool) {
163 - * console.log(`Found tool: ${myTool.name}`);
164 - * } else {
165 - * console.log('Tool not found');
166 - * }
167 - * ```
168 - */
169 - async getCustomToolBySlug(slug: string): Promise<Tool | undefined> {
170 - try {
171 - const tool = this.customToolsRegistry.get(slug.toLowerCase());
172 - return tool?.schema;
173 - } catch (error) {
174 - logger.error(`Error getting custom tool: ${error}`);
175 - return undefined;
176 - }
177 - }
178 -
179 - /**
180 - * Get the connected account for the user and toolkit.
181 - * @param {string} toolkitSlug The slug of the toolkit
182 - * @param {ExecuteMetadata} metadata The metadata of the execution
183 - * @returns {ConnectedAccount} The connected account
184 - */
185 - private async getConnectedAccountForToolkit(
186 - toolkitSlug: string,
187 - userId: string,
188 - connectedAccountId?: string
189 - ): Promise<ConnectedAccountRetrieveResponse | null> {
190 - try {
191 - await this.client.toolkits.retrieve(toolkitSlug);
192 - // check if the toolkit is a no auth toolkit
193 - const toolkit = await this.client.toolkits.retrieve(toolkitSlug);
194 - const isNoAuthToolkit = toolkit.auth_config_details?.some(
195 - details => details.mode === AuthSchemeTypes.NO_AUTH
196 - );
197 - if (isNoAuthToolkit) {
198 - return null;
199 - }
200 - } catch (error) {
201 - throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
202 - cause: error,
203 - });
204 - }
205 - const connectedAccounts = await this.client.connectedAccounts.list({
206 - toolkit_slugs: [toolkitSlug],
207 - user_ids: [userId],
208 - });
209 -
210 - if (!connectedAccounts.items.length) {
211 - throw new ComposioConnectedAccountNotFoundError(
212 - `No connected accounts found for toolkit ${toolkitSlug}`
213 - );
214 - }
215 - // if a connected account id is provided, use it, otherwise use the first connected account
216 - const connectedAccount = connectedAccountId
217 - ? connectedAccounts.items.find(item => item.id === connectedAccountId)
218 - : connectedAccounts.items[0];
219 -
220 - if (!connectedAccount) {
221 - throw new ComposioConnectedAccountNotFoundError(
222 - `Connected account not found for toolkit ${toolkitSlug} for user ${userId}`
223 - );
224 - }
225 -
226 - return transformConnectedAccountResponse(connectedAccount);
227 - }
228 -
229 - /**
230 - * Execute a custom tool
231 - *
232 - * @description If a toolkit is used, the connected account id is used to execute the tool.
233 - * If a connected account id is provided, it is used to execute the tool.
234 - * If a connected account id is not provided, the first connected account for the toolkit is used.
235 - *
236 - * @param {slug} slug The slug of the tool to execute
237 - * @param {Record<string, unknown>} inputParams The input parameters for the tool
238 - * @param {ExecuteMetadata} metadata The metadata of the execution
239 - * @returns {Promise<ToolExecuteResponse>} The response from the tool
240 - */
241 - async executeCustomTool(slug: string, body: ToolExecuteParams): Promise<ToolExecuteResponse> {
242 - const tool = this.customToolsRegistry.get(slug.toLowerCase());
243 - if (!tool) {
244 - throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
245 - }
246 -
247 - let connectionConfig: ConnectionData | null = null;
248 - const { toolkitSlug, execute, inputParams } = tool.options;
249 - // if a toolkit is used, get the connected account, and auth credentials
250 - let connectedAccountId: string | undefined = body.connectedAccountId;
251 - // if a toolkit is used, and a userId is provided, get the connected account
252 - if (toolkitSlug && toolkitSlug !== 'custom' && body.userId) {
253 - const connectedAccount = await this.getConnectedAccountForToolkit(
254 - toolkitSlug,
255 - body.userId,
256 - body.connectedAccountId
257 - );
258 - logger.debug(
259 - `[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`,
260 - JSON.stringify(connectedAccount, null, 2)
261 - );
262 - if (!connectedAccount) {
263 - throw new ComposioConnectedAccountNotFoundError(
264 - `Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`,
265 - {
266 - meta: {
267 - toolkitSlug,
268 - userId: body.userId,
269 - },
270 - }
271 - );
272 - }
273 - connectionConfig = connectedAccount.state ?? null;
274 - connectedAccountId = connectedAccount.id;
275 - }
276 -
277 - if (typeof execute !== 'function') {
278 - throw new ComposioInvalidExecuteFunctionError('Invalid execute function', {
279 - meta: {
280 - toolSlug: slug,
281 - },
282 - });
283 - }
284 - // create a tool proxy request for users to execute in case of a toolkit being used
285 - const executeToolRequest = async (data: ToolProxyParams): Promise<ToolExecuteResponse> => {
286 - // if the toolkit is custom, throw an error while trying to execute the tool by user
287 - if (toolkitSlug && toolkitSlug === 'custom') {
288 - throw new ComposioInvalidExecuteFunctionError(
289 - 'Custom tools without a toolkit cannot be executed using the executeToolRequest function',
290 - {
291 - possibleFixes: [
292 - 'Please manually execute the tool using your logic.',
293 - 'Pass a toolkit slug to execute the tool on behalf of a toolkit credentials',
294 - ],
295 - }
296 - );
297 - }
298 - // map the parameters to the composio format
299 - const parameters = data.parameters?.map(param => ({
300 - name: param.name,
301 - type: param.in,
302 - value: param.value.toString(),
303 - }));
304 -
305 - // execute the tool
306 - const response = await this.client.tools.proxy({
307 - endpoint: data.endpoint,
308 - method: data.method,
309 - parameters: parameters,
310 - body: data.body,
311 - connected_account_id: connectedAccountId,
312 - /**
313 - * @deprecated
314 - * @description
315 - * This parameter is deprecated and will be removed in the future.
316 - * Please use custom_auth_params instead.
317 - *
318 - */
319 - // @ts-ignore
320 - custom_connection_data: data.customConnectionData,
321 - });
322 -
323 - return {
324 - data: response.data as Record<string, unknown>,
325 - error: null,
326 - successful: true,
327 - logId: undefined,
328 - sessionInfo: undefined,
329 - };
330 - };
331 -
332 - // Parse and validate the input using the tool's schema
333 - const parsedInput = inputParams.safeParse(body.arguments);
334 - if (!parsedInput.success) {
335 - throw new ValidationError('Invalid input parameters', {
336 - cause: parsedInput.error,
337 - });
338 - }
339 -
340 - return execute(parsedInput.data, connectionConfig, executeToolRequest);
341 - }
342 -}
ts/packages/core/src/models/Tools.ts
+14 -100
@@ -30,8 +30,6 @@ import {
30 ToolListParams as ComposioToolListParams,
31 ToolExecuteParams as ComposioToolExecuteParams,
32 } from '@composio/client/resources/tools';
33 -import { CustomTools } from './CustomTools';
34 -import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';
33 import {
34 afterExecuteModifier,
35 ExecuteToolModifiers,
@@ -43,7 +41,6 @@ import { BaseComposioProvider } from '../provider/BaseProvider';
41 import logger from '../utils/logger';
42 import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types';
43 import {
46 - ComposioCustomToolsNotInitializedError,
44 ComposioInvalidModifierError,
45 ComposioToolNotFoundError,
46 ComposioProviderNotDefinedError,
@@ -98,7 +95,6 @@ export class Tools<
95 TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
96 > {
97 private client: ComposioClient;
101 - private readonly customTools: CustomTools;
98 private provider: TProvider;
99 private autoUploadDownloadFiles: boolean;
100 private toolkitVersions: ToolkitVersionParam;
@@ -124,7 +120,6 @@ export class Tools<
120 }
121
122 this.client = client;
127 - this.customTools = new CustomTools(client);
123 this.provider = config.provider;
124 this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true;
125 this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
@@ -142,7 +137,6 @@ export class Tools<
137 this.execute = this.execute.bind(this);
138 // Set the execute method for the provider.
139 this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
145 - // Bind methods that use customTools to ensure correct 'this' context
140 this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
141 this.getRawComposioTools = this.getRawComposioTools.bind(this);
142
@@ -337,10 +331,12 @@ export class Tools<
331 }
332
333 /**
340 - * Lists all tools available in the Composio SDK including custom tools.
334 + * Lists Composio API tools available to the SDK.
335 *
342 - * This method fetches tools from the Composio API in raw format and combines them with
343 - * any registered custom tools. The response can be filtered and modified as needed.
336 + * This method fetches remote Composio tools from the API in raw format. The response can be
337 + * filtered and modified as needed. Local experimental custom tools are session-scoped; attach
338 + * them when creating or reusing a Tool Router session, then use `session.tools()`,
339 + * `session.customTools()`, or `session.execute()`.
340 * It provides access to the underlying tool data without provider-specific wrapping.
341 *
342 * @param {ToolListParams} query - Query parameters to filter the tools (required)
@@ -467,14 +463,7 @@ export class Tools<
463 }
464 const caseTransformedTools = tools.items.map(tool => this.transformToolCases(tool));
465
470 - const customTools = await this.customTools.getCustomTools({
471 - toolSlugs: 'tools' in queryParams.data ? queryParams.data.tools : undefined,
472 - });
473 -
474 - let modifiedTools = await this.applyDefaultSchemaModifiers([
475 - ...caseTransformedTools,
476 - ...customTools,
477 - ]);
466 + let modifiedTools = await this.applyDefaultSchemaModifiers(caseTransformedTools);
467
468 // apply local modifiers if they are provided
469 if (options?.modifySchema) {
@@ -555,6 +544,9 @@ export class Tools<
544 * This method fetches a single tool in raw format without provider-specific wrapping,
545 * providing direct access to the tool's schema and metadata. Tool versions are controlled
546 * at the Composio SDK initialization level through the `toolkitVersions` configuration.
547 + * Local experimental custom tools are session-scoped; attach them when creating or reusing a
548 + * Tool Router session, then use `session.tools()`, `session.customTools()`, or
549 + * `session.execute()`.
550 *
551 * @param {string} slug - The unique identifier of the tool (e.g., 'GITHUB_GET_REPOS')
552 * @param {GetRawComposioToolBySlugOptions} [options] - Optional configuration for tool retrieval
@@ -584,9 +576,6 @@ export class Tools<
576 * }
577 * );
578 *
587 - * // Get a custom tool (will check custom tools first)
588 - * const customTool = await composio.tools.getRawComposioToolBySlug('MY_CUSTOM_TOOL');
589 - *
579 * // Access tool properties
580 * const githubTool = await composio.tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
581 * console.log({
@@ -600,15 +589,6 @@ export class Tools<
589 * ```
590 */
591 async getRawComposioToolBySlug(slug: string, options?: ToolRetrievalOptions): Promise<Tool> {
603 - // check if the tool is a custom tool
604 - const customTool = await this.customTools.getCustomToolBySlug(slug);
605 - if (customTool) {
606 - logger.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
607 - return customTool;
608 - } else {
609 - logger.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
610 - }
611 - // if not, fetch the tool from the Composio API
592 let tool: ToolRetrieveResponse;
593 try {
594 // Build API call parameters based on version source
@@ -915,8 +895,7 @@ export class Tools<
895 /**
896 * Executes a given tool with the provided parameters.
897 *
918 - * This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
919 - * It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
898 + * This method calls the Composio API to execute the tool and returns the response.
899 *
900 * **Version Control:**
901 * By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest",
@@ -933,7 +912,6 @@ export class Tools<
912 * @param {ExecuteToolModifiers} [modifiers] - Optional modifiers to transform the request or response
913 * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
914 *
936 - * @throws {ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized
915 * @throws {ComposioConnectedAccountNotFoundError} If the connected account is not found
916 * @throws {ComposioToolNotFoundError} If the tool with the given slug is not found
917 * @throws {ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true
@@ -990,24 +968,14 @@ export class Tools<
968 body: ToolExecuteParams,
969 modifiers?: ExecuteToolModifiers
970 ): Promise<ToolExecuteResponse> {
993 - if (!this.customTools) {
994 - throw new ComposioCustomToolsNotInitializedError(
995 - 'CustomTools not initialized. Make sure Tools class is properly constructed.'
996 - );
997 - }
998 -
971 const executeParams = ToolExecuteParamsSchema.safeParse(body);
972 if (!executeParams.success) {
973 throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
974 }
975
1004 - // Determine if it's a custom tool or composio tool
1005 - const customTool = await this.customTools.getCustomToolBySlug(slug);
1006 - const tool =
1007 - customTool ??
1008 - (await this.getRawComposioToolBySlug(slug, {
1009 - version: body.version,
1010 - }));
976 + const tool = await this.getRawComposioToolBySlug(slug, {
977 + version: body.version,
978 + });
979 const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
980
981 // Apply before execute modifiers
@@ -1021,10 +989,7 @@ export class Tools<
989 modifiers
990 );
991
1024 - // Execute the tool (custom or composio)
1025 - let result = customTool
1026 - ? await this.customTools.executeCustomTool(customTool.slug, params)
1027 - : await this.executeComposioTool(tool, params);
992 + let result = await this.executeComposioTool(tool, params);
993
994 // Apply after execute modifiers
995 result = await this.applyAfterExecuteModifiers(
@@ -1214,55 +1179,4 @@ export class Tools<
1179 custom_connection_data: toolProxyParams.data.customConnectionData,
1180 });
1181 }
1217 -
1218 - /**
1219 - * Creates a custom tool that can be used within the Composio SDK.
1220 - *
1221 - * Custom tools allow you to extend the functionality of Composio with your own implementations
1222 - * while keeping a consistent interface for both built-in and custom tools.
1223 - *
1224 - * @param {CustomToolOptions} body - The configuration for the custom tool
1225 - * @returns {Promise<Tool>} The created custom tool
1226 - *
1227 - * @example
1228 - * ```typescript
1229 - * // creating a custom tool with a toolkit
1230 - * await composio.tools.createCustomTool({
1231 - * name: 'My Custom Tool',
1232 - * description: 'A custom tool that does something specific',
1233 - * slug: 'MY_CUSTOM_TOOL',
1234 - * userId: 'default',
1235 - * connectedAccountId: '123',
1236 - * toolkitSlug: 'github',
1237 - * inputParameters: z.object({
1238 - * param1: z.string().describe('First parameter'),
1239 - * }),
1240 - * execute: async (input, connectionConfig, executeToolRequest) => {
1241 - * // Custom logic here
1242 - * return { data: { result: 'Success!' } };
1243 - * }
1244 - * });
1245 - * ```
1246 - *
1247 - * @example
1248 - * ```typescript
1249 - * // creating a custom tool without a toolkit
1250 - * await composio.tools.createCustomTool({
1251 - * name: 'My Custom Tool',
1252 - * description: 'A custom tool that does something specific',
1253 - * slug: 'MY_CUSTOM_TOOL',
1254 - * inputParameters: z.object({
1255 - * param1: z.string().describe('First parameter'),
1256 - * }),
1257 - * execute: async (input) => {
1258 - * // Custom logic here
1259 - * return { data: { result: 'Success!' } };
1260 - * }
1261 - * });
1262 - */
1263 - async createCustomTool<T extends CustomToolInputParameter>(
1264 - body: CustomToolOptions<T>
1265 - ): Promise<Tool> {
1266 - return this.customTools.createTool(body);
1267 - }
1182 }
ts/packages/core/src/types/customTool.types.ts
-58
@@ -1,72 +1,14 @@
1 import { z } from 'zod/v3';
2 -import { Tool, ToolProxyParams } from './tool.types';
2 import type {
3 SessionProxyExecuteParams,
4 ToolRouterSessionExecuteResponse,
5 ToolRouterSessionProxyExecuteResponse,
6 } from './toolRouter.types';
8 -import { ToolExecuteResponse } from '@composio/client/resources/tools';
9 -import { ConnectionData } from './connectedAccountAuthStates.types';
7 import type {
8 SessionCreateParams,
9 SessionCreateResponse,
10 } from '@composio/client/resources/tool-router/session/session.mjs';
11
15 -// ────────────────────────────────────────────────────────────────
16 -// Legacy custom tool types (used by composio.tools.createCustomTool)
17 -// ────────────────────────────────────────────────────────────────
18 -
19 -type BaseCustomToolOptions<T extends z.ZodType> = {
20 - name: string;
21 - description?: string;
22 - slug: string;
23 - inputParams: T;
24 -};
25 -
26 -type ToolkitBasedExecute<T extends z.ZodType> = {
27 - execute: (
28 - input: z.infer<T>,
29 - connectionConfig: ConnectionData | null,
30 - executeToolRequest: (data: ToolProxyParams) => Promise<ToolExecuteResponse>
31 - ) => Promise<ToolExecuteResponse>;
32 - toolkitSlug: string;
33 -};
34 -
35 -type StandaloneExecute<T extends z.ZodType> = {
36 - execute: (input: z.infer<T>) => Promise<ToolExecuteResponse>;
37 - toolkitSlug?: never;
38 -};
39 -
40 -export type CustomToolOptions<T extends z.ZodType> = BaseCustomToolOptions<T> &
41 - (ToolkitBasedExecute<T> | StandaloneExecute<T>);
42 -
43 -export type CustomToolRegistry = Map<
44 - string,
45 - { options: CustomToolOptions<CustomToolInputParameter>; schema: Tool }
46 ->;
47 -
48 -export type InputParamsSchema = {
49 - definitions: {
50 - input: {
51 - type: string;
52 - properties: Record<string, unknown>;
53 - required?: string[];
54 - };
55 - };
56 -};
57 -
58 -export type CustomToolInputParameter = z.ZodType;
59 -
60 -export interface CustomToolRegistryItem {
61 - options: CustomToolOptions<CustomToolInputParameter>;
62 - schema: Tool;
63 -}
64 -
65 -export interface ExecuteMetadata {
66 - userId: string;
67 - connectedAccountId?: string;
68 -}
69 -
12 // ────────────────────────────────────────────────────────────────
13 // New custom tool types (for tool router integration via createCustomTool())
14 // ────────────────────────────────────────────────────────────────
ts/packages/core/test/tools/customTools.test.ts deleted
-265
@@ -1,265 +0,0 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
2 -import { CustomTools } from '../../src/models/CustomTools';
3 -import { mockClient } from '../utils/mocks/client.mock';
4 -import { toolMocks } from '../utils/mocks/data.mock';
5 -import ComposioClient from '@composio/client';
6 -import { z } from 'zod/v3';
7 -import { ComposioToolNotFoundError } from '../../src/errors/ToolErrors';
8 -import { ComposioConnectedAccountNotFoundError } from '../../src/errors/ConnectedAccountsErrors';
9 -import { ValidationError } from '../../src/errors';
10 -
11 -describe('CustomTools', () => {
12 - let customTools: CustomTools;
13 -
14 - const toolOptions = {
15 - slug: 'CUSTOM_TOOL',
16 - name: 'Custom Tool',
17 - description: 'A custom tool for testing',
18 - inputParams: z.object({
19 - query: z.string().describe('The search query'),
20 - }),
21 - execute: vi.fn().mockResolvedValue(toolMocks.toolExecuteResponse),
22 - };
23 -
24 - beforeEach(() => {
25 - vi.clearAllMocks();
26 - customTools = new CustomTools(mockClient as unknown as ComposioClient);
27 - });
28 -
29 - it('should throw an error if client is not provided', () => {
30 - expect(() => new CustomTools(null as any)).toThrow('ComposioClient is required');
31 - });
32 -
33 - describe('createTool', () => {
34 - it('should create a custom tool and add it to the registry', async () => {
35 - const result = await customTools.createTool(toolOptions);
36 -
37 - expect(result).toMatchObject({
38 - slug: toolOptions.slug,
39 - name: toolOptions.name,
40 - description: toolOptions.description,
41 - inputParameters: expect.any(Object),
42 - outputParameters: expect.any(Object),
43 - });
44 -
45 - // Verify it's in the registry
46 - const registryTool = await customTools.getCustomToolBySlug(toolOptions.slug);
47 - expect(registryTool).toBeDefined();
48 - expect(registryTool?.slug).toEqual(toolOptions.slug);
49 - });
50 -
51 - it('should throw an error for invalid tool options', async () => {
52 - const invalidOptions = {
53 - slug: 'INVALID_TOOL',
54 - // Missing required properties
55 - };
56 -
57 - await expect(customTools.createTool(invalidOptions as any)).rejects.toThrow(Error);
58 - });
59 - });
60 -
61 - describe('getCustomTools', () => {
62 - it('should return all tools from the registry when no slugs provided', async () => {
63 - // Add tools to the registry
64 - await customTools.createTool(toolOptions);
65 - await customTools.createTool({
66 - ...toolOptions,
67 - slug: 'ANOTHER_TOOL',
68 - });
69 -
70 - const result = await customTools.getCustomTools({});
71 -
72 - expect(result).toHaveLength(2);
73 - expect(result[0].slug).toEqual('CUSTOM_TOOL');
74 - expect(result[1].slug).toEqual('ANOTHER_TOOL');
75 - });
76 -
77 - it('should filter tools by slug when provided', async () => {
78 - // Add tools to the registry
79 - await customTools.createTool(toolOptions);
80 - await customTools.createTool({
81 - ...toolOptions,
82 - slug: 'ANOTHER_TOOL',
83 - });
84 -
85 - const result = await customTools.getCustomTools({
86 - toolSlugs: ['CUSTOM_TOOL'],
87 - });
88 -
89 - expect(result).toHaveLength(1);
90 - expect(result[0].slug).toEqual('CUSTOM_TOOL');
91 - });
92 - });
93 -
94 - describe('executeCustomTool', () => {
95 - const executeParams = {
96 - arguments: { query: 'test query' },
97 - userId: 'test-user',
98 - };
99 -
100 - it('should execute a custom tool with provided parameters', async () => {
101 - // Add a tool to the registry
102 - await customTools.createTool(toolOptions);
103 -
104 - const result = await customTools.executeCustomTool(toolOptions.slug, executeParams);
105 -
106 - expect(toolOptions.execute).toHaveBeenCalledWith(
107 - executeParams.arguments,
108 - null,
109 - expect.any(Function)
110 - );
111 - expect(result).toEqual(toolMocks.toolExecuteResponse);
112 - });
113 -
114 - it('should throw an error if tool does not exist', async () => {
115 - const nonExistentSlug = 'NON_EXISTENT';
116 -
117 - await expect(customTools.executeCustomTool(nonExistentSlug, executeParams)).rejects.toThrow(
118 - ComposioToolNotFoundError
119 - );
120 - });
121 -
122 - it('should throw validation error for invalid input parameters', async () => {
123 - await customTools.createTool(toolOptions);
124 - const invalidParams = {
125 - ...executeParams,
126 - arguments: { invalidField: 'test' },
127 - };
128 -
129 - await expect(customTools.executeCustomTool(toolOptions.slug, invalidParams)).rejects.toThrow(
130 - ValidationError
131 - );
132 - });
133 -
134 - describe('toolkit-based custom tools', () => {
135 - const toolkitTool = {
136 - ...toolOptions,
137 - toolkitSlug: 'TEST_TOOLKIT',
138 - };
139 -
140 - const mockConnectedAccount = {
141 - id: 'conn-123',
142 - auth_config: {
143 - id: 'auth-123',
144 - auth_scheme: 'OAUTH2',
145 - is_composio_managed: true,
146 - is_disabled: false,
147 - },
148 - user_id: 'test-user',
149 - data: {},
150 - state: {
151 - authScheme: 'OAUTH2',
152 - val: {
153 - status: 'ACTIVE',
154 - access_token: 'test-token',
155 - token_type: 'Bearer',
156 - },
157 - },
158 - status: 'ACTIVE',
159 - status_reason: null,
160 - toolkit: {
161 - slug: 'TEST_TOOLKIT',
162 - },
163 - test_request_endpoint: 'https://api.test.com',
164 - is_disabled: false,
165 - created_at: '2024-01-01T00:00:00Z',
166 - updated_at: '2024-01-01T00:00:00Z',
167 - };
168 -
169 - beforeEach(async () => {
170 - await customTools.createTool(toolkitTool);
171 - mockClient.toolkits.retrieve.mockResolvedValue({ slug: 'TEST_TOOLKIT' });
172 - });
173 -
174 - it('should fetch and use auth credentials for toolkit-based custom tools', async () => {
175 - mockClient.connectedAccounts.list.mockResolvedValueOnce({
176 - items: [mockConnectedAccount],
177 - totalPages: 1,
178 - });
179 -
180 - await customTools.executeCustomTool(toolkitTool.slug, executeParams);
181 -
182 - expect(toolkitTool.execute).toHaveBeenCalledWith(
183 - executeParams.arguments,
184 - mockConnectedAccount.state,
185 - expect.any(Function)
186 - );
187 - });
188 -
189 - it('should use specified connected account when connectedAccountId is provided', async () => {
190 - const specificConnectedAccountId = 'conn-456';
191 - const specificConnectedAccount = {
192 - ...mockConnectedAccount,
193 - id: specificConnectedAccountId,
194 - };
195 -
196 - mockClient.connectedAccounts.list.mockResolvedValueOnce({
197 - items: [mockConnectedAccount, specificConnectedAccount],
198 - totalPages: 1,
199 - });
200 -
201 - await customTools.executeCustomTool(toolkitTool.slug, {
202 - ...executeParams,
203 - connectedAccountId: specificConnectedAccountId,
204 - });
205 -
206 - expect(toolkitTool.execute).toHaveBeenCalledWith(
207 - executeParams.arguments,
208 - specificConnectedAccount.state,
209 - expect.any(Function)
210 - );
211 - });
212 -
213 - it('should throw error when toolkit is not found', async () => {
214 - mockClient.toolkits.retrieve.mockRejectedValueOnce(new Error('Toolkit not found'));
215 -
216 - await expect(
217 - customTools.executeCustomTool(toolkitTool.slug, executeParams)
218 - ).rejects.toThrow(ComposioToolNotFoundError);
219 - });
220 -
221 - it('should throw error when no connected accounts are found', async () => {
222 - mockClient.connectedAccounts.list.mockResolvedValueOnce({
223 - items: [],
224 - totalPages: 1,
225 - });
226 -
227 - await expect(
228 - customTools.executeCustomTool(toolkitTool.slug, executeParams)
229 - ).rejects.toThrow(ComposioConnectedAccountNotFoundError);
230 - });
231 -
232 - it('should throw error when specified connected account is not found', async () => {
233 - mockClient.connectedAccounts.list.mockResolvedValueOnce({
234 - items: [mockConnectedAccount],
235 - totalPages: 1,
236 - });
237 -
238 - await expect(
239 - customTools.executeCustomTool(toolkitTool.slug, {
240 - ...executeParams,
241 - connectedAccountId: 'non-existent-id',
242 - })
243 - ).rejects.toThrow(ComposioConnectedAccountNotFoundError);
244 - });
245 -
246 - it('should throw error when trying to use executeToolRequest with custom toolkit', async () => {
247 - const customToolkitTool = {
248 - ...toolOptions,
249 - toolkitSlug: 'custom',
250 - execute: async (input: any, auth: any, executeToolRequest: any) => {
251 - return executeToolRequest({ slug: 'TEST_TOOL', arguments: {} });
252 - },
253 - };
254 -
255 - await customTools.createTool(customToolkitTool);
256 -
257 - await expect(
258 - customTools.executeCustomTool(customToolkitTool.slug, executeParams)
259 - ).rejects.toThrow(
260 - 'Custom tools without a toolkit cannot be executed using the executeToolRequest function'
261 - );
262 - });
263 - });
264 - });
265 -});
ts/packages/core/test/tools/tools.test.ts
-48
@@ -285,21 +285,6 @@ describe('Tools', () => {
285 expect(result[0].outputParameters).toEqual(toolMocks.transformedTool.outputParameters);
286 });
287
288 - it('should include custom tools in the results', async () => {
289 - mockClient.tools.list.mockResolvedValueOnce({
290 - items: [toolMocks.rawTool],
291 - totalPages: 1,
292 - });
293 -
294 - const getCustomToolsSpy = vi.spyOn(context.tools['customTools'], 'getCustomTools');
295 - getCustomToolsSpy.mockResolvedValueOnce([toolMocks.customTool as unknown as Tool]);
296 -
297 - const result = await context.tools.getRawComposioTools({ tools: ['TEST_TOOL'] });
298 -
299 - expect(result).toHaveLength(2);
300 - expect(result[1].slug).toEqual(toolMocks.customTool.slug);
301 - });
302 -
288 it('should apply schema modifiers when provided', async () => {
289 const schemaModifier = createSchemaModifier({
290 description: 'Modified description',
@@ -392,24 +377,9 @@ describe('Tools', () => {
377 expect(result.slug).toEqual(toolMocks.transformedTool.slug);
378 });
379
395 - it('should check for custom tools first', async () => {
396 - const slug = 'CUSTOM_TOOL';
397 -
398 - const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
399 - getCustomToolBySlugSpy.mockResolvedValueOnce(toolMocks.customTool as unknown as Tool);
400 -
401 - const result = await context.tools.getRawComposioToolBySlug(slug);
402 -
403 - expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
404 - expect(mockClient.tools.retrieve).not.toHaveBeenCalled();
405 - expect(result.slug).toEqual(toolMocks.customTool.slug);
406 - });
407 -
380 it('should throw an error if tool is not found', async () => {
381 const slug = 'NONEXISTENT_TOOL';
382
411 - const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
412 - getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
383 mockClient.tools.retrieve.mockRejectedValue(null);
384
385 await expect(context.tools.getRawComposioToolBySlug(slug)).rejects.toThrow(
@@ -664,24 +634,6 @@ describe('Tools', () => {
634 });
635
636 describe('execute', () => {
667 - it('should execute a custom tool', async () => {
668 - const slug = 'CUSTOM_TOOL';
669 - const body = { userId: 'test-user', arguments: { query: 'test' } };
670 -
671 - const { getCustomToolBySlugSpy } = await mockToolExecution(context.tools, {
672 - customToolExists: true,
673 - });
674 -
675 - const executeCustomToolSpy = vi.spyOn(context.tools['customTools'], 'executeCustomTool');
676 - executeCustomToolSpy.mockResolvedValueOnce(toolMocks.toolExecuteResponse);
677 -
678 - const result = await context.tools.execute(slug, body);
679 -
680 - expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
681 - expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body);
682 - expect(result).toEqual(toolMocks.toolExecuteResponse);
683 - });
684 -
637 it('should execute a composio tool', async () => {
638 const slug = 'COMPOSIO_TOOL';
639 const body = {
ts/packages/core/test/utils/toolExecuteUtils.ts
+1 -11
@@ -29,10 +29,7 @@ export const setupTest = (context: TestContext) => {
29 });
30 };
31
32 -export const mockToolExecution = async (
33 - tools: TestTools,
34 - { customToolExists = false, connectedAccountId = 'test-connected-account-id' } = {}
35 -) => {
32 +export const mockToolExecution = async (tools: TestTools) => {
33 // Mock client responses
34 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
35 mockClient.toolkits.retrieve.mockResolvedValueOnce(toolkitMocks.rawToolkit);
@@ -40,12 +37,6 @@ export const mockToolExecution = async (
37 connectedAccountMocks.rawConnectedAccountsResponse
38 );
39
43 - // Mock custom tool check
44 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
45 - getCustomToolBySlugSpy.mockResolvedValueOnce(
46 - customToolExists ? (toolMocks.customTool as unknown as Tool) : undefined
47 - );
48 -
40 // Mock composio tool retrieval
41 const getRawComposioToolBySlugSpy = vi.spyOn(tools, 'getRawComposioToolBySlug');
42 getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
@@ -54,7 +45,6 @@ export const mockToolExecution = async (
45 mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
46
47 return {
57 - getCustomToolBySlugSpy,
48 getRawComposioToolBySlugSpy,
49 };
50 };