Skip to content

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)

Alberto Schiabel44e5458c35ee
diff --git a/.changeset/remove-legacy-custom-tools.md b/.changeset/remove-legacy-custom-tools.md
new file mode 100644
index 000000000..978f24738
--- /dev/null
+++ b/.changeset/remove-legacy-custom-tools.md
@@ -0,0 +1,5 @@
+---
+"@composio/core": minor
+---
+
+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.
diff --git a/docs/content/reference/sdk-reference/typescript/composio.mdx b/docs/content/reference/sdk-reference/typescript/composio.mdx
index 5cef39db5..cad86a49c 100644
--- a/docs/content/reference/sdk-reference/typescript/composio.mdx
+++ b/docs/content/reference/sdk-reference/typescript/composio.mdx
@@ -53,7 +53,13 @@ const composio = new Composio({
|------|------|-------------|
| `authConfigs` | `AuthConfigs` | Manage authentication configurations for toolkits |
| `connectedAccounts` | `ConnectedAccounts` | Manage authenticated connections |
-| `create` | `object` | Creates a new tool router session for a user. |
+| `create` | `object` | Creates a new tool router session for a user.
+Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools
+should be exposed directly; see `ToolRouterCreateSessionConfig`. |
+| `experimental` | `Experimental` | Experimental SDK methods whose shape may change in future releases.
+Houses stateful operations like Experimental.updateAcl that
+take a client and perform I/O. Stateless experimental factories
+(e.g. `experimental_createTool`) stay at the top level. |
| `files` | `Files` | Upload and download files |
| `mcp` | `MCP` | Model Context Protocol server management |
| `provider` | `TProvider` | The tool provider instance used for wrapping tools in framework-specific formats |
@@ -61,7 +67,7 @@ const composio = new Composio({
| `toolRouter` | `ToolRouter` | Experimental feature, use with caution |
| `tools` | `Tools` | List, retrieve, and execute tools |
| `triggers` | `Triggers` | Manage webhook triggers and event subscriptions |
-| `use` | `(id: string) => Promise<Session>` | Use an existing tool router session |
+| `use` | `object` | Use an existing tool router session |
## Methods
@@ -166,53 +172,22 @@ getClient(): Composio
### getConfig()
-Get the configuration SDK is initialized with
+Get the configuration SDK is initialized with.
+
+Returns a frozen shallow clone — the SDK has already snapshotted
+configuration values such as `dangerouslyAllowAutoUploadDownloadFiles`,
+`fileUploadDirs`, and `fileDownloadDir` into its internal models, so
+mutating the live config object would silently no-op. Freezing makes
+that contract visible at the call site instead of letting the mutation
+appear successful.
```typescript
-getConfig(): ComposioConfig
+getConfig(): Readonly<ComposioConfig>
```
**Returns**
-`ComposioConfig` — The configuration SDK is initialized with
-
----
-
-## File upload security
-
-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)).
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `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. |
-| `fileUploadPathDenySegments` | `string[]` | `undefined` | Additional single path *components* (directory or file names) merged with the built-in list; matched anywhere in the resolved path. |
-| `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. |
-| `fileDownloadDir` | `string` | `~/.composio/files` | Directory where files from tool responses marked `file_downloadable` are streamed. |
-
-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.
-
-**Related errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError`, `ComposioFileUploadPathNotAllowedError`, `ComposioFileNotFoundError` (from `@composio/core`).
-
-### Restricting automatic uploads to specific directories
-
-When `dangerouslyAllowAutoUploadDownloadFiles: true`, the SDK only reads local
-files from directories in `fileUploadDirs`. This stacks with (it does NOT
-replace) the sensitive-path denylist.
-
-```typescript
-// @noErrors
-import { Composio } from '@composio/core';
-
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY!,
- dangerouslyAllowAutoUploadDownloadFiles: true,
- // Replaces the default `[~/.composio/temp]`. List every directory you want
- // the SDK to read from during tool execution.
- fileUploadDirs: ['/srv/agent/uploads', '~/.composio/temp'],
-});
-```
-
-Pass `fileUploadDirs: false` (or `[]`) to reject every filesystem path; URLs
-and in-memory `File`/`Blob` objects still upload normally.
+`Readonly<ComposioConfig>` — The frozen configuration
+ the SDK is initialized with.
---
diff --git a/docs/content/reference/sdk-reference/typescript/connected-accounts.mdx b/docs/content/reference/sdk-reference/typescript/connected-accounts.mdx
index 7ea954607..c2df089c0 100644
--- a/docs/content/reference/sdk-reference/typescript/connected-accounts.mdx
+++ b/docs/content/reference/sdk-reference/typescript/connected-accounts.mdx
@@ -19,7 +19,7 @@ const result = await composio.connectedAccounts.list();
Deletes a connected account.
This method permanently removes a connected account from the Composio platform.
-This action cannot be undone.
+This action cannot be undone and will revoke any access tokens associated with the account.
```typescript
async delete(nanoid: string): Promise<ConnectedAccountDeleteResponse>
@@ -144,6 +144,22 @@ Compound function to create a new connected account.
This function creates a new connected account and returns a connection request.
Users can then wait for the connection to be established using the `waitForConnection` method.
+**Deprecated for Composio-managed OAuth (OAuth1, OAuth2, DCR_OAUTH).**
+The legacy `POST endpoint that this method
+wraps is being retired for Composio-managed auth configs on redirectable
+schemes. The cutover is **2026-05-08** for new organizations and
+**2026-07-03** for all remaining organizations. After your org's cutover,
+this method will throw ComposioLegacyConnectedAccountsEndpointRetiredError
+for that specific combination.
+
+Use ConnectedAccounts.link for Composio-managed OAuth — it works for
+every redirectable scheme regardless of whether the auth config is
+Composio-managed or custom, and the return shape is the same.
+
+Custom auth configs (your own OAuth app) and non-OAuth schemes (API key,
+bearer token, basic auth) are unaffected and continue to work on
+`initiate()`. See https://docs.composio.dev/docs/changelog/2026/04/24
+
```typescript
async initiate(userId: string, authConfigId: string, options?: object): Promise<ConnectionRequest>
```
@@ -205,7 +221,7 @@ const connectionRequest = await composio.connectedAccounts.initiate(
### link()
```typescript
-async link(userId: string, authConfigId: string, options?: { alias?: string; callbackUrl?: string }): Promise<ConnectionRequest>
+async link(userId: string, authConfigId: string, options?: object): Promise<ConnectionRequest>
```
**Parameters**
@@ -318,7 +334,10 @@ const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123')
### update()
-Update a connected account's alias and/or credentials.
+Enable or disable a connected account. Accepts `{ enabled: boolean }`.
+
+For ACL writes on SHARED connections, see
+`composio.experimental.updateAcl()`.
```typescript
async update(nanoid: string, params: ConnectedAccountUpdateStatusParams): Promise<ConnectedAccountUpdateStatusResponse>
diff --git a/docs/content/reference/sdk-reference/typescript/experimental.mdx b/docs/content/reference/sdk-reference/typescript/experimental.mdx
new file mode 100644
index 000000000..dcd2a7452
--- /dev/null
+++ b/docs/content/reference/sdk-reference/typescript/experimental.mdx
@@ -0,0 +1,89 @@
+---
+title: Experimental
+description: `composio.experimental` namespace. Mirrors the Python SDK's `composio.experimental` mount, with one method per experimental surface. **Shape may change in future releases.**
+---
+
+## Usage
+
+Access this class through the `composio.experimental` property:
+
+```typescript
+const composio = new Composio({ apiKey: 'your-api-key' });
+const result = await composio.experimental.list();
+```
+
+## Methods
+
+### updateAcl()
+
+Update the per-user ACL on a SHARED connected account.
+**Experimental — shape may change in future releases.**
+
+Only meaningful for SHARED connections — calling this on a PRIVATE
+connection raises `ComposioAclOnlyForSharedError` (400). ACL writes
+require the connection's creator or an API key.
+
+PATCH semantics: omit a field to leave it unchanged; pass an empty
+array to clear an allow/deny list. At least one field must be
+provided.
+
+Resolution rule (deny wins):
+ 1. requesting `userId` in `notAllowedUserIds` → DENY
+ 2. `allowAllUsers === true` → ALLOW
+ 3. requesting `userId` in `allowedUserIds` → ALLOW
+ 4. otherwise → DENY
+
+```typescript
+async updateAcl(nanoid: string, params: { allowAllUsers?: boolean; allowedUserIds?: string[]; notAllowedUserIds?: string[] }): Promise<ConnectedAccountPatchResponse>
+```
+
+**Parameters**
+
+| Name | Type |
+|------|------|
+| `nanoid` | `string` |
+| `params` | `object` |
+
+**Returns**
+
+`Promise<ConnectedAccountPatchResponse>` — The PATCH response (`\{ id, status, success \}`). To read
+ the updated ACL block, call
+ `composio.connectedAccounts.get(nanoid)` after the promise
+ resolves and inspect `account.experimental?.aclConfigForShared`.
+
+**Example**
+
+```typescript
+import { Composio } from '@composio/core';
+
+const composio = new Composio({ apiKey: '...' });
+
+// Allow every userId to use this connection
+await composio.experimental.updateAcl('ca_abc', { allowAllUsers: true });
+
+// Everyone except a specific user
+await composio.experimental.updateAcl('ca_abc', {
+ allowAllUsers: true,
+ notAllowedUserIds: ['user_bob'],
+});
+
+// Targeted allow
+await composio.experimental.updateAcl('ca_abc', {
+ allowedUserIds: ['user_alice', 'user_bob'],
+});
+
+// Revoke a previously-granted allow list (back to deny-by-default)
+await composio.experimental.updateAcl('ca_abc', { allowedUserIds: [] });
+```
+
+**Empty-array semantics — read carefully.** Passing `[]` for either
+list **replaces** the list, it does not extend it:
+
+- `allowedUserIds: []` → revoke all previously-granted user IDs (state
+ reverts to deny-by-default unless `allowAllUsers` is true).
+- `notAllowedUserIds: []` → **clears the deny list**, which silently
+ re-grants access to users you previously blocked. Always pair an
+ empty deny list with a deliberate audit of the allow side.
+```
+
+---
diff --git a/docs/content/reference/sdk-reference/typescript/index.mdx b/docs/content/reference/sdk-reference/typescript/index.mdx
index 52679c5c7..6e0c13d3b 100644
--- a/docs/content/reference/sdk-reference/typescript/index.mdx
+++ b/docs/content/reference/sdk-reference/typescript/index.mdx
@@ -35,6 +35,7 @@ bun add @composio/core
| [`Composio`](/reference/sdk-reference/typescript/composio) | This is the core class for Composio. |
| [`AuthConfigs`](/reference/sdk-reference/typescript/auth-configs) | AuthConfigs class |
| [`ConnectedAccounts`](/reference/sdk-reference/typescript/connected-accounts) | ConnectedAccounts class |
+| [`Experimental`](/reference/sdk-reference/typescript/experimental) | `composio.experimental` namespace. Mirrors the Python SDK's |
| [`MCP`](/reference/sdk-reference/typescript/mcp) | MCP (Model Control Protocol) class |
| [`RemoteFile`](/reference/sdk-reference/typescript/remote-file) | Represents a file stored in a tool router session's file mount. |
| [`SessionContextImpl`](/reference/sdk-reference/typescript/session-context-impl) | Concrete implementation of SessionContext. |
diff --git a/docs/content/reference/sdk-reference/typescript/meta.json b/docs/content/reference/sdk-reference/typescript/meta.json
index 57ad070ac..012e3510d 100644
--- a/docs/content/reference/sdk-reference/typescript/meta.json
+++ b/docs/content/reference/sdk-reference/typescript/meta.json
@@ -4,6 +4,7 @@
"composio",
"auth-configs",
"connected-accounts",
+ "experimental",
"mcp",
"remote-file",
"session-context-impl",
diff --git a/docs/content/reference/sdk-reference/typescript/tool-router-session.mdx b/docs/content/reference/sdk-reference/typescript/tool-router-session.mdx
index 34fff700c..ee1495ea1 100644
--- a/docs/content/reference/sdk-reference/typescript/tool-router-session.mdx
+++ b/docs/content/reference/sdk-reference/typescript/tool-router-session.mdx
@@ -16,9 +16,12 @@ const result = await composio.toolRouterSession.list();
| Name | Type |
|------|------|
+| `configVersion` | `number` |
| `experimental` | `SessionExperimental` |
| `mcp` | `object` |
+| `preload` | `Preload` |
| `sessionId` | `string` |
+| `warnings` | `Warning[]` |
## Methods
@@ -27,8 +30,19 @@ const result = await composio.toolRouterSession.list();
Initiate an authorization flow for a toolkit.
Returns a ConnectionRequest with a redirect URL for the user.
+Pass `experimental: { accountType: 'SHARED', aclConfigForShared }` to
+create a SHARED connection with a per-user ACL in one flow. Default
+behaviour (omit the block) creates a PRIVATE connection.
+
+Experimental — shape may change in future releases.
+
+`aclConfigForShared` is validated against the same caps as
+`composio.connectedAccounts.link()` (≤1000 entries per list, each
+`userId` 1..256 characters). Invalid input throws `ValidationError`
+at the SDK boundary.
+
```typescript
-async authorize(toolkit: string, options?: { alias?: string; callbackUrl?: string }): Promise<ConnectionRequest>
+async authorize(toolkit: string, options?: object): Promise<ConnectionRequest>
```
**Parameters**
@@ -89,7 +103,7 @@ full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
remote tools are sent to the Composio backend.
```typescript
-async execute(toolSlug: string, arguments_?: Record<string, unknown>): Promise<{ data: Record<string, unknown>; error: string | null; logId: string }>
+async execute(toolSlug: string, arguments_?: Record<string, unknown>, options?: ToolRouterSessionExecuteOptions): Promise<{ data: Record<string, unknown>; error: string | null; logId: string }>
```
**Parameters**
@@ -98,6 +112,7 @@ async execute(toolSlug: string, arguments_?: Record<string, unknown>): Promise<{
|------|------|-------------|
| `toolSlug` | `string` | The tool slug to execute |
| `arguments_?` | `Record<string, unknown>` | Optional tool arguments |
+| `options?` | `ToolRouterSessionExecuteOptions` | Optional execution options |
**Returns**
@@ -191,3 +206,25 @@ async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType>
`Promise<ReturnType>`
---
+
+### update()
+
+Partially update the session configuration.
+Only the fields provided will be changed; omitted fields are preserved.
+Mutates this session's `configVersion`, `preload`, and `warnings` in-place.
+
+```typescript
+async update(config: object): Promise<void>
+```
+
+**Parameters**
+
+| Name | Type |
+|------|------|
+| `config` | `object` |
+
+**Returns**
+
+`Promise<void>`
+
+---
diff --git a/docs/content/reference/sdk-reference/typescript/tools.mdx b/docs/content/reference/sdk-reference/typescript/tools.mdx
index 191266000..cf7c3abaa 100644
--- a/docs/content/reference/sdk-reference/typescript/tools.mdx
+++ b/docs/content/reference/sdk-reference/typescript/tools.mdx
@@ -14,72 +14,11 @@ const result = await composio.tools.list();
## Methods
-### createCustomTool()
-
-Creates a custom tool that can be used within the Composio SDK.
-
-Custom tools allow you to extend the functionality of Composio with your own implementations
-while keeping a consistent interface for both built-in and custom tools.
-
-```typescript
-async createCustomTool(body: CustomToolOptions<T>): Promise<...>
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `body` | `CustomToolOptions<T>` | The configuration for the custom tool |
-
-**Returns**
-
-`Promise<...>` — The created custom tool
-
-**Example**
-
-```typescript
-// creating a custom tool with a toolkit
-await composio.tools.createCustomTool({
- name: 'My Custom Tool',
- description: 'A custom tool that does something specific',
- slug: 'MY_CUSTOM_TOOL',
- userId: 'default',
- connectedAccountId: '123',
- toolkitSlug: 'github',
- inputParameters: z.object({
- param1: z.string().describe('First parameter'),
- }),
- execute: async (input, connectionConfig, executeToolRequest) => {
- // Custom logic here
- return { data: { result: 'Success!' } };
- }
-});
-```
-
-```typescript
-// creating a custom tool without a toolkit
-await composio.tools.createCustomTool({
- name: 'My Custom Tool',
- description: 'A custom tool that does something specific',
- slug: 'MY_CUSTOM_TOOL',
- inputParameters: z.object({
- param1: z.string().describe('First parameter'),
- }),
- execute: async (input) => {
- // Custom logic here
- return { data: { result: 'Success!' } };
- }
-});
-```
-
----
-
### execute()
Executes a given tool with the provided parameters.
-This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
-It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
+This method calls the Composio API to execute the tool and returns the response.
**Version Control:**
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', {
---
-### executeMetaTool()
+### executeSessionTool()
-Executes a composio meta tool based on tool router session
+Executes a tool based on a tool router session.
```typescript
-async executeMetaTool(toolSlug: string, body: { arguments?: Record<string, unknown>; sessionId: string }, modifiers?: SessionExecuteMetaModifiers): Promise<...>
+async executeSessionTool(toolSlug: string, body: { arguments?: Record<string, unknown>; sessionId: string }, modifiers?: SessionExecuteMetaModifiers, tool?: object, options?: ToolRouterSessionExecuteOptions): Promise<...>
```
**Parameters**
@@ -163,6 +102,8 @@ async executeMetaTool(toolSlug: string, body: { arguments?: Record<string, unkno
| `toolSlug` | `string` | The slug of the tool to execute |
| `body` | `object` | The execution parameters |
| `modifiers?` | `SessionExecuteMetaModifiers` | The modifiers to apply to the tool |
+| `tool?` | `object` | Optional tool schema used to resolve toolkit metadata for modifiers |
+| `options?` | `ToolRouterSessionExecuteOptions` | |
**Returns**
@@ -280,6 +221,9 @@ Retrieves a specific tool by its slug from the Composio API.
This method fetches a single tool in raw format without provider-specific wrapping,
providing direct access to the tool's schema and metadata. Tool versions are controlled
at the Composio SDK initialization level through the `toolkitVersions` configuration.
+Local experimental custom tools are session-scoped; attach them when creating or reusing a
+Tool Router session, then use `session.tools()`, `session.customTools()`, or
+`session.execute()`.
```typescript
async getRawComposioToolBySlug(slug: string, options?: ToolRetrievalOptions): Promise<...>
@@ -320,9 +264,6 @@ const customizedTool = await composio.tools.getRawComposioToolBySlug(
}
);
-// Get a custom tool (will check custom tools first)
-const customTool = await composio.tools.getRawComposioToolBySlug('MY_CUSTOM_TOOL');
-
// Access tool properties
const githubTool = await composio.tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
console.log({
@@ -339,10 +280,12 @@ console.log({
### getRawComposioTools()
-Lists all tools available in the Composio SDK including custom tools.
+Lists Composio API tools available to the SDK.
-This method fetches tools from the Composio API in raw format and combines them with
-any registered custom tools. The response can be filtered and modified as needed.
+This method fetches remote Composio tools from the API in raw format. The response can be
+filtered and modified as needed. Local experimental custom tools are session-scoped; attach
+them when creating or reusing a Tool Router session, then use `session.tools()`,
+`session.customTools()`, or `session.execute()`.
It provides access to the underlying tool data without provider-specific wrapping.
```typescript
@@ -408,32 +351,32 @@ const authSpecificTools = await composio.tools.getRawComposioTools({
---
-### getRawToolRouterMetaTools()
+### getRawToolRouterSessionTools()
-Fetches the meta tools for a tool router session.
-This method fetches the meta tools from the Composio API and transforms them to the expected format.
-It provides access to the underlying meta tool data without provider-specific wrapping.
+Fetches tools exposed by a tool router session.
+This includes helper/meta tools plus any tools preloaded into the session.
+It provides access to the underlying tool data without provider-specific wrapping.
```typescript
-async getRawToolRouterMetaTools(sessionId: string, options?: SchemaModifierOptions): Promise<ToolList>
+async getRawToolRouterSessionTools(sessionId: string, options?: SchemaModifierOptions): Promise<ToolList>
```
**Parameters**
| Name | Type | Description |
|------|------|-------------|
-| `sessionId` | `string` | \{string\} The session id to get the meta tools for |
+| `sessionId` | `string` | \{string\} The session id to get tools for |
| `options?` | `SchemaModifierOptions` | \{SchemaModifierOptions\} Optional configuration for tool retrieval |
**Returns**
-`Promise<ToolList>` — The list of meta tools
+`Promise<ToolList>` — The list of session tools
**Example**
```typescript
-const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123');
-console.log(metaTools);
+const sessionTools = await composio.tools.getRawToolRouterSessionTools('session_123');
+console.log(sessionTools);
```
---
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 49fe6e694..3aa240c24 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -529,9 +529,6 @@ importers:
dotenv:
specifier: ^16.4.1
version: 16.6.1
- zod:
- specifier: 'catalog:'
- version: 4.3.6
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -581,25 +578,6 @@ importers:
specifier: 'catalog:'
version: 5.9.3
- ts/examples/custom-tools:
- dependencies:
- '@composio/core':
- specifier: workspace:*
- version: link:../../packages/core
- dotenv:
- specifier: ^16.4.1
- version: 16.6.1
- zod:
- specifier: 'catalog:'
- version: 4.3.6
- devDependencies:
- '@types/bun':
- specifier: ^1.2.9
- version: 1.3.9
- typescript:
- specifier: 'catalog:'
- version: 5.9.3
-
ts/examples/error-handling-demo:
dependencies:
'@composio/core':
diff --git a/ts/README.md b/ts/README.md
index b256bc5c3..5dd31f2d7 100644
--- a/ts/README.md
+++ b/ts/README.md
@@ -6,7 +6,7 @@ The Composio SDK is a powerful toolkit that enables you to integrate third-party
- Execute tools from various services (GitHub, Gmail, Slack, etc.)
- Manage user connections to external services
-- Create custom tools with your own logic
+- Create session-scoped custom tools with your own logic
- Integrate with AI providers like OpenAI
- Powerful middleware and modifier support
- Extensive error handling
@@ -23,11 +23,11 @@ The SDK is thoroughly documented in the [docs](./docs) directory:
### API Reference
- [Composio Class](./docs/api/composio.md) - Main SDK class
-- [Tools](./docs/api/tools.md) - Using and creating tools
+- [Tools](./docs/api/tools.md) - Listing, fetching, and executing tools
+- [Tool Router](./docs/api/tool-router.md) - Sessions, search, and custom tools
- [Toolkits](./docs/api/toolkits.md) - Working with tool collections
- [Connected Accounts](./docs/api/connected-accounts.md) - User authentication
- [Auth Configs](./docs/api/auth-configs.md) - Authentication configuration
-- [Custom Tools](./docs/api/custom-tools.md) - Creating your own tools
- [Providers](./docs/api/providers.md) - AI integration options
### Provider Documentation
@@ -142,42 +142,32 @@ if (completion.choices[0].message.tool_calls) {
## Creating Custom Tools
```typescript
+import { Composio, experimental_createTool } from '@composio/core';
import { z } from 'zod';
-// Create a custom tool
-const customTool = await composio.tools.createCustomTool({
+const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
+
+const weatherForecast = experimental_createTool('WEATHER_FORECAST', {
name: 'Weather Forecast',
description: 'Get the weather forecast for a location',
- slug: 'WEATHER_FORECAST',
inputParams: z.object({
location: z.string().describe('The location to get the forecast for'),
- days: z.number().optional().default(3).describe('Number of days for the forecast')
+ days: z.number().optional().default(3).describe('Number of days for the forecast'),
}),
execute: async (input) => {
- try {
- const { location, days = 3 } = input;
-
- // Your implementation here
- const forecast = [
- { date: '2025-05-21', temperature: 72, conditions: 'Sunny' },
- { date: '2025-05-22', temperature: 68, conditions: 'Partly Cloudy' },
- { date: '2025-05-23', temperature: 65, conditions: 'Rainy' },
- ];
-
- return {
- data: { forecast },
- successful: true,
- error: null,
- };
- } catch (error) {
- return {
- data: {},
- successful: false,
- error: error.message,
- };
- }
+ const { location, days = 3 } = input;
+ const forecast = await getWeatherForecast(location, days);
+ return { forecast };
},
});
+
+const session = await composio.create('default', {
+ experimental: { customTools: [weatherForecast] },
+});
+
+const result = await session.execute('WEATHER_FORECAST', {
+ location: 'San Francisco, CA',
+});
```
## Project Structure
diff --git a/ts/docs/README.md b/ts/docs/README.md
index fadd62ddd..49a898bf5 100644
--- a/ts/docs/README.md
+++ b/ts/docs/README.md
@@ -20,7 +20,7 @@ Composio SDK allows you to:
- Execute tools from various services (like GitHub, Gmail, Slack, etc.)
- Manage user connections to external services
-- Create custom tools
+- Create session-scoped custom tools
- Implement triggers and event handlers
- Integrate with AI providers like OpenAI
@@ -42,7 +42,7 @@ The Composio SDK is built around several key concepts:
- **Connected Accounts**: User connections to external services
- **Auth Configs**: Authentication configurations for external services
- **Providers**: Adapters for AI services that can use tools (e.g., OpenAI)
-- **Custom Tools**: Tools you can create and define yourself
+- **Custom Tools**: Session-scoped local tools created with `experimental_createTool`
- **MCP**: Create and manage MCP Servers and clients
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:
- [Connected Accounts](./api/connected-accounts.md)
- [Auth Configs](./api/auth-configs.md)
- [Providers](./api/providers.md)
-- [Custom Tools](./api/custom-tools.md)
- [MCP](./api/mcp.md)
- [ToolRouter](./api/tool-router.md)
- [Tool Router Session Files](./api/tool-router-files.md)
diff --git a/ts/docs/advanced/error-handling.md b/ts/docs/advanced/error-handling.md
index a7b1efe55..c1c446384 100644
--- a/ts/docs/advanced/error-handling.md
+++ b/ts/docs/advanced/error-handling.md
@@ -172,52 +172,28 @@ try {
}
```
-## Error Handling in Custom Tools
+## Error Handling in Session Custom Tools
-When creating custom tools, implement proper error handling in your handler function:
+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.
```typescript
+import { experimental_createTool } from '@composio/core';
import { z } from 'zod';
-const customTool = await composio.tools.createCustomTool({
+const customTool = experimental_createTool('MY_CUSTOM_TOOL', {
name: 'My Custom Tool',
description: 'A custom tool with error handling',
- slug: 'MY_CUSTOM_TOOL',
inputParams: z.object({
- param1: z.string().describe('Required parameter')
+ param1: z.string().describe('Required parameter'),
}),
execute: async (input) => {
- try {
- // Input is already validated by zod
- const { param1 } = input;
- if (!param1 || param1.trim() === '') {
- return {
- data: {},
- successful: false,
- error: 'param1 cannot be empty',
- };
- }
-
- // Process the request
- // This could throw various errors
- const result = await someExternalService(param1);
-
- return {
- data: { result },
- successful: true,
- error: null,
- };
- } catch (error) {
- // Log the error for debugging
- console.error('Error in custom tool:', error);
-
- // Return a user-friendly error message
- return {
- data: {},
- successful: false,
- error: error.message || 'An unexpected error occurred',
- };
+ const { param1 } = input;
+ if (param1.trim() === '') {
+ throw new Error('param1 cannot be empty');
}
+
+ const result = await someExternalService(param1);
+ return { result };
},
});
```
diff --git a/ts/docs/api/custom-tools.md b/ts/docs/api/custom-tools.md
deleted file mode 100644
index 978380cc7..000000000
--- a/ts/docs/api/custom-tools.md
+++ /dev/null
@@ -1,204 +0,0 @@
-# Custom Tools
-
-Custom tools allow you to create your own tools that can be used with Composio. There are two types of custom tools:
-
-1. Standalone Tools - Simple tools that don't require any authentication
-2. Toolkit-based Tools - Tools that require authentication and can use toolkit credentials
-
-## Creating a Custom Tool
-
-### Standalone Tool
-
-A standalone tool is the simplest form of custom tool. It only requires input parameters and an execute function:
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'CALCULATE_SQUARE',
- name: 'Calculate Square',
- description: 'Calculates the square of a number',
- inputParams: z.object({
- number: z.number().describe('The number to calculate the square of'),
- }),
- execute: async input => {
- const { number } = input;
- return {
- data: { result: number * number },
- error: null,
- successful: true,
- };
- },
-});
-```
-
-### Toolkit-based Tool
-
-A toolkit-based tool has access to two ways of making authenticated requests:
-
-1. Using `executeToolRequest` - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection and baseURL resolution:
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY',
- name: 'Github star composio repositories',
- toolkitSlug: 'github',
- description: 'For any given repository of the user composiohq, star the repository',
- inputParams: z.object({
- repository: z.string().describe('The repository to star'),
- page: z.number().optional().describe('Page number for pagination'),
- customHeader: z.string().optional().describe('Custom header value'),
- }),
- execute: async (input, connectionConfig, executeToolRequest) => {
- // executeToolRequest makes authenticated requests to the toolkit's API
- // You can use relative paths - Composio will automatically inject the baseURL
- const result = await executeToolRequest({
- endpoint: `/user/starred/composiohq/${input.repository}`,
- method: 'PUT',
- body: {},
- // Add custom headers or query parameters
- parameters: [
- // Add query parameters
- {
- name: 'page',
- value: input.page?.toString() || '1',
- in: 'query',
- },
- // Add custom headers
- {
- name: 'x-custom-header',
- value: input.customHeader || 'default-value',
- in: 'header',
- },
- ],
- });
- return result;
- },
-});
-```
-
-2. Using `connectionConfig` - For making direct API calls when needed:
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'GITHUB_DIRECT_API',
- name: 'Direct GitHub API Call',
- description: 'Makes direct calls to GitHub API',
- toolkitSlug: 'github',
- inputParams: z.object({
- repo: z.string().describe('Repository name'),
- }),
- execute: async (input, connectionConfig, executeToolRequest) => {
- // Use connectionConfig for direct API calls
- const result = await fetch(`https://api.github.com/repos/${input.repo}`, {
- headers: {
- Authorization: `Bearer ${connectionConfig.val?.access_token}`,
- },
- });
-
- return {
- data: await result.json(),
- error: null,
- successful: true,
- };
- },
-});
-```
-
-### Using Custom Headers and Query Parameters
-
-You can add custom headers and query parameters to your toolkit-based tools using the `parameters` option in `executeToolRequest`:
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'GITHUB_SEARCH_REPOSITORIES',
- name: 'Search GitHub Repositories',
- description: 'Search for repositories with custom parameters',
- toolkitSlug: 'github',
- inputParams: z.object({
- query: z.string().describe('Search query'),
- perPage: z.number().optional().describe('Results per page'),
- acceptType: z.string().optional().describe('Custom accept header'),
- }),
- execute: async (input, connectionConfig, executeToolRequest) => {
- const result = await executeToolRequest({
- endpoint: '/search/repositories',
- method: 'GET',
- parameters: [
- // Add query parameters for pagination
- {
- name: 'q',
- value: input.query,
- in: 'query',
- },
- {
- name: 'per_page',
- value: (input.perPage || 30).toString(),
- in: 'query',
- },
- // Add custom headers
- {
- name: 'Accept',
- value: input.acceptType || 'application/vnd.github.v3+json',
- in: 'header',
- },
- {
- name: 'X-Custom-Header',
- value: 'custom-value',
- in: 'header',
- },
- ],
- });
- return result;
- },
-});
-```
-
-## Executing Custom Tools
-
-You can execute custom tools just like any other tool:
-
-```typescript
-const result = await composio.tools.execute('TOOL_SLUG', {
- arguments: {
- // Tool input parameters
- },
- userId: 'user-id',
- connectedAccountId: 'optional-account-id', // Required for toolkit-based tools
-});
-```
-
-## Type Safety
-
-The custom tools implementation provides full type safety:
-
-1. Input parameters are validated using Zod schemas
-2. The execute function's parameters are inferred based on whether toolkitSlug is provided:
- - Without toolkitSlug: `(input) => Promise<ToolExecuteResponse>`
- - With toolkitSlug: `(input, connectionConfig, executeToolRequest) => Promise<ToolExecuteResponse>`
-
-## Best Practices
-
-1. Use descriptive names and slugs for your tools
-2. Always provide descriptions for input parameters using `describe()`
-3. Handle errors gracefully in your execute function
-4. For toolkit-based tools:
- - Prefer `executeToolRequest` over direct API calls when possible
- - Use relative paths with `executeToolRequest` - Composio will automatically inject the correct baseURL
- - Use the `parameters` option to add custom headers or query parameters:
- ```typescript
- parameters: [
- { name: 'page', value: '1', in: 'query' }, // Adds ?page=1 to URL
- { name: 'x-custom', value: 'value', in: 'header' }, // Adds header
- ];
- ```
- - Remember that `executeToolRequest` can only call tools from the same toolkit
- - Use `executeToolRequest` to leverage Composio's automatic credential handling
- - Only use `connectionConfig` when you need to make direct API calls or interact with different services
-5. Chain multiple toolkit operations using `executeToolRequest` for better maintainability
-
-## Limitations
-
-1. Custom tools are stored in memory and are not persisted
-2. They need to be recreated when the application restarts
-3. Toolkit-based tools require a valid connected account with the specified toolkit
-4. `executeToolRequest` can only execute tools from the same toolkit that the custom tool belongs to
-5. Each toolkit-based tool can only use one connected account at a time
diff --git a/ts/docs/api/tools.md b/ts/docs/api/tools.md
index 6f12ca72f..4496b4cee 100644
--- a/ts/docs/api/tools.md
+++ b/ts/docs/api/tools.md
@@ -178,46 +178,12 @@ const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
**Throws:**
-- `ComposioCustomToolsNotInitializedError`: If the CustomTools instance is not initialized
- `ComposioToolNotFoundError`: If the tool with the given slug is not found
- `ComposioToolExecutionError`: If there is an error during tool execution
-### createCustomTool(body)
-
-Creates a custom tool that can be used within the Composio SDK.
-
-```typescript
-import { z } from 'zod';
-
-const customTool = await composio.tools.createCustomTool({
- name: 'My Custom Tool',
- description: 'A custom tool that does something specific',
- slug: 'MY_CUSTOM_TOOL',
- inputParams: z.object({
- param1: z.string().describe('Description of param1'),
- param2: z.number().optional().describe('Optional numeric parameter')
- }),
- execute: async (input) => {
- // Custom logic here
- console.log('Input:', input.param1, input.param2);
- return {
- data: { result: 'Success!' },
- error: null,
- successful: true
- };
- },
-});
-```
-
-**Parameters:**
-
-- `body` (CustomToolOptions): The configuration for the custom tool
-
-**Returns:** Promise<Tool> - The created custom tool
-
### getRawComposioTools(query, options?)
-Lists all tools available in the Composio SDK including custom tools. This method provides direct access to tool data without provider-specific wrapping.
+Lists all tools available from the Composio API. This method provides direct access to tool data without provider-specific wrapping.
```typescript
// Get important tools from a toolkit (auto-applies important filter)
@@ -497,17 +463,3 @@ interface ToolExecuteResponse {
sessionInfo?: unknown; // Session information
}
```
-
-### CustomToolOptions
-
-```typescript
-interface CustomToolOptions {
- name: string; // Name of the custom tool
- description: string; // Description of the custom tool
- slug: string; // Unique slug for the custom tool
- inputParameters: Record<string, unknown>; // Input parameters schema
- outputParameters?: Record<string, unknown>; // Output parameters schema
- handler: (params: ToolExecuteParams, context: ExecuteMetadata) => Promise<ToolExecuteResponse>; // Handler function
-}
-```
-
diff --git a/ts/docs/core-concepts.md b/ts/docs/core-concepts.md
index 45c916ec0..35ae0a07d 100644
--- a/ts/docs/core-concepts.md
+++ b/ts/docs/core-concepts.md
@@ -402,30 +402,33 @@ Use direct execution when:
## Custom Tools
-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.
+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`.
```typescript
+import { Composio, experimental_createTool } from '@composio/core';
import { z } from 'zod';
-// Example: Create a custom tool
-const customTool = await composio.tools.createCustomTool({
+const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
+
+const customTool = experimental_createTool('MY_CUSTOM_TOOL', {
name: 'My Custom Tool',
description: 'A custom tool that does something specific',
- slug: 'MY_CUSTOM_TOOL',
inputParams: z.object({
param1: z.string().describe('First parameter'),
- param2: z.number().optional().describe('Optional parameter')
+ param2: z.number().optional().describe('Optional parameter'),
}),
execute: async (input) => {
- // Custom logic here
- console.log('Received input:', input.param1, input.param2);
- return {
- data: { result: 'Success!' },
- error: null,
- successful: true
- };
+ return { result: `Received ${input.param1}` };
},
});
+
+const session = await composio.create('default', {
+ experimental: { customTools: [customTool] },
+});
+
+const result = await session.execute('MY_CUSTOM_TOOL', {
+ param1: 'hello',
+});
```
## Triggers
diff --git a/ts/docs/getting-started.md b/ts/docs/getting-started.md
index e85ee7d7e..a883ea0b8 100644
--- a/ts/docs/getting-started.md
+++ b/ts/docs/getting-started.md
@@ -283,52 +283,38 @@ For a more complete integration, check out the [OpenAI Provider example](../exam
## Creating Custom Tools
-You can extend Composio by creating your own custom tools:
+You can extend Tool Router sessions with your own local custom tools:
```typescript
+import { Composio, experimental_createTool } from '@composio/core';
import { z } from 'zod';
-// Create a custom tool
-const customTool = await composio.tools.createCustomTool({
+const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
+
+const customTool = experimental_createTool('WEATHER_FORECAST', {
name: 'Weather Forecast',
description: 'Get the weather forecast for a location',
- slug: 'WEATHER_FORECAST',
inputParams: z.object({
location: z.string().describe('The location to get the forecast for'),
- days: z.number().optional().default(3).describe('Number of days for the forecast')
+ days: z.number().optional().default(3).describe('Number of days for the forecast'),
}),
execute: async (input) => {
- try {
- const { location, days = 3 } = input;
-
- // Here you would call your weather API
- const forecast = await getWeatherForecast(location, days);
-
- return {
- data: { forecast },
- error: null,
- successful: true,
- };
- } catch (error) {
- return {
- data: {},
- successful: false,
- error: error.message,
- };
- }
+ const { location, days = 3 } = input;
+ const forecast = await getWeatherForecast(location, days);
+ return { forecast };
},
});
-// Now you can use your custom tool
-const result = await composio.tools.execute('WEATHER_FORECAST', {
- userId: 'default',
- arguments: {
- location: 'San Francisco, CA',
- days: 5,
- },
+const session = await composio.create('default', {
+ experimental: { customTools: [customTool] },
+});
+
+const result = await session.execute('WEATHER_FORECAST', {
+ location: 'San Francisco, CA',
+ days: 5,
});
-console.log(result.data.forecast);
+console.log(result.data?.forecast);
```
For more advanced session management features, check out the [Session Management Guide](./advanced/session-management.md).
diff --git a/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/README.md b/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/README.md
index 1a069c144..40aa6d9c4 100644
--- a/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/README.md
+++ b/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/README.md
@@ -7,7 +7,7 @@ This package tests `@composio/core` file operations in Cloudflare Workers enviro
Verifies that:
1. `composio.files.upload()` throws the expected "not supported in Cloudflare Workers" error
2. `composio.files.download()` throws the expected "not supported in Cloudflare Workers" error
-3. The `FileToolModifier.workerd.ts` is correctly loaded and provides the expected error message when `dangerouslyAllowAutoUploadDownloadFiles` is explicitly enabled
+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)
4. Composio initializes correctly with the default configuration (`dangerouslyAllowAutoUploadDownloadFiles: false` in workerd runtime)
5. Composio can be explicitly initialized with `dangerouslyAllowAutoUploadDownloadFiles: false`
@@ -18,7 +18,6 @@ Verifies that:
| `GET /` | Lists all available test endpoints |
| `GET /test/files/upload` | Tests that `files.upload()` throws the expected error |
| `GET /test/files/download` | Tests that `files.download()` throws the expected error |
-| `GET /test/file-modifier/error-message` | Tests the error when `dangerouslyAllowAutoUploadDownloadFiles: true` is explicitly set |
| `GET /test/auto-upload-disabled` | Tests Composio initialization with explicit `dangerouslyAllowAutoUploadDownloadFiles: false` |
| `GET /test/default-config` | Tests Composio initialization with default configuration (no explicit setting) |
diff --git a/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/src/index.ts b/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/src/index.ts
index d60e486e4..ccbc85b0e 100644
--- a/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/src/index.ts
+++ b/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/src/index.ts
@@ -4,7 +4,6 @@
* and that the FileToolModifier.workerd.ts is properly loaded.
*/
import { Composio } from '@composio/core';
-import { z } from 'zod/v3';
import { Hono } from 'hono';
type Bindings = {
@@ -22,7 +21,6 @@ app.get('/', c => {
endpoints: [
'/test/files/upload',
'/test/files/download',
- '/test/file-modifier/error-message',
'/test/auto-upload-disabled',
'/test/default-config',
],
@@ -93,61 +91,6 @@ app.get('/test/files/download', async c => {
}
});
-/**
- * Test: FileToolModifier behavior (triggers the auto-upload/download error)
- *
- * The FileToolModifier.workerd.ts throws an error when automatic file upload/download is enabled.
- * In workerd runtime, the default is off, so we explicitly opt in here to test the error.
- *
- * This endpoint actually executes a tool to trigger the real error from FileToolModifier.workerd.ts.
- */
-app.get('/test/file-modifier/error-message', async c => {
- try {
- const composio = new Composio({
- apiKey: c.env.COMPOSIO_API_KEY,
- dangerouslyAllowAutoUploadDownloadFiles: true,
- });
-
- // Use a local custom tool to avoid depending on remote Composio tool registry.
- // Any execute() with automatic file handling enabled will trigger FileToolModifier
- // in the workerd runtime.
- await composio.tools.createCustomTool({
- slug: 'CUSTOM_FILE_TOOL',
- name: 'Custom File Tool',
- inputParams: z.object({
- file: z.string(),
- }),
- execute: async () => ({
- data: {},
- error: null,
- successful: true,
- logId: undefined,
- sessionInfo: undefined,
- }),
- });
-
- await composio.tools.execute('CUSTOM_FILE_TOOL', {
- arguments: {
- file: 'https://example.com/test.pdf',
- },
- dangerouslySkipVersionCheck: true,
- });
-
- // If we get here, the test failed - execution should have thrown
- return c.json(
- {
- error: 'Expected tool execution to throw FileToolModifier error, but it did not',
- },
- { status: 500 }
- );
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- return c.json({
- error: errorMessage,
- });
- }
-});
-
/**
* Test: Composio initialization with automatic file upload/download disabled
*
diff --git a/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/test/files.spec.ts b/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/test/files.spec.ts
index 0952e2566..1f85d8a15 100644
--- a/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/test/files.spec.ts
+++ b/ts/e2e-tests/runtimes/cloudflare/cf-workers-files/test/files.spec.ts
@@ -1,10 +1,15 @@
import { env, createExecutionContext, waitOnExecutionContext } from 'cloudflare:test';
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { Composio, type Tool } from '@composio/core';
import app from '../src/index';
const IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
describe('@composio/core Files - Cloudflare Workers compatibility', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it('should list the available endpoints', async () => {
const request = new IncomingRequest('http://localhost/');
const ctx = createExecutionContext();
@@ -23,7 +28,6 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
[
"/test/files/upload",
"/test/files/download",
- "/test/file-modifier/error-message",
"/test/auto-upload-disabled",
"/test/default-config",
]
@@ -60,19 +64,43 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
expect(body.error).toContain('not supported in Cloudflare Workers');
});
- it('should throw FileToolModifier error when executing a tool in Cloudflare Workers', async () => {
- const request = new IncomingRequest('http://localhost/test/file-modifier/error-message');
- const ctx = createExecutionContext();
- const response = await app.fetch(request, env, ctx);
- await waitOnExecutionContext(ctx);
-
- expect(response.status).toBe(200);
-
- const body = (await response.json()) as {
- error?: string;
+ it('should surface the edge-runtime FileToolModifier error from execute() when auto-upload is enabled', async () => {
+ // Runs inside workerd (vitest-pool-workers), so `#file_tool_modifier` resolves to the
+ // .workerd variant — the exact module under test. We drive the real public execute()
+ // pipeline and stub only the network tool lookup, so the before-execute file modifier
+ // is reached without depending on a remote tool registry or network access.
+ const composio = new Composio({
+ apiKey: env.COMPOSIO_API_KEY,
+ dangerouslyAllowAutoUploadDownloadFiles: true,
+ });
+
+ const fileTool: Tool = {
+ slug: 'CUSTOM_FILE_TOOL',
+ name: 'Custom File Tool',
+ description: 'Fixture tool with a file-uploadable input',
+ inputParameters: {
+ type: 'object',
+ properties: {
+ file: {
+ type: 'string',
+ file_uploadable: true,
+ },
+ },
+ required: ['file'],
+ },
+ toolkit: { slug: 'custom', name: 'custom' },
};
- expect(body.error).toContain('not available on edge runtimes');
+ vi.spyOn(composio.tools, 'getRawComposioToolBySlug').mockResolvedValue(fileTool);
+
+ await expect(
+ composio.tools.execute('CUSTOM_FILE_TOOL', {
+ arguments: {
+ file: 'https://example.com/test.pdf',
+ },
+ dangerouslySkipVersionCheck: true,
+ })
+ ).rejects.toThrow('not available on edge runtimes');
});
it('should successfully initialize Composio with automatic file handling disabled', async () => {
diff --git a/ts/examples/cjs/package.json b/ts/examples/cjs/package.json
index 3005d187e..0e6219712 100644
--- a/ts/examples/cjs/package.json
+++ b/ts/examples/cjs/package.json
@@ -14,8 +14,7 @@
"packageManager": "[email protected]",
"dependencies": {
"@composio/core": "workspace:*",
- "dotenv": "^16.4.1",
- "zod": "catalog:"
+ "dotenv": "^16.4.1"
},
"devDependencies": {
"@types/bun": "^1.2.9",
diff --git a/ts/examples/cjs/src/index.cjs b/ts/examples/cjs/src/index.cjs
index 108959dfc..99e49e0a3 100644
--- a/ts/examples/cjs/src/index.cjs
+++ b/ts/examples/cjs/src/index.cjs
@@ -1,31 +1,16 @@
const { Composio } = require('@composio/core');
-const { z } = require('zod/v3');
require('dotenv/config');
-const composio = new Composio()
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+});
async function main() {
- console.log('Creating custom tool...');
+ console.log('Fetching tools enum...');
- const tool = await composio.tools.createCustomTool({
- name: 'My Custom Tool',
- description: 'A custom tool that does something specific',
- slug: 'MY_CUSTOM_TOOL',
- inputParams: z.object({
- param1: z.string().describe('First parameter'),
- }),
- execute: async (_input) => {
- return {
- data: {
- result: 'Success!',
- },
- error: null,
- successful: true,
- };
- },
- });
+ const tools = await composio.tools.getToolsEnum();
- console.log('Custom tool created:', tool);
+ console.log('Tools enum fetched:', tools.items.length);
}
main()
diff --git a/ts/examples/custom-tools/.env.example b/ts/examples/custom-tools/.env.example
deleted file mode 100644
index 0e728257c..000000000
--- a/ts/examples/custom-tools/.env.example
+++ /dev/null
@@ -1,6 +0,0 @@
-# Composio API Key - Get it from https://app.composio.dev
-COMPOSIO_API_KEY=your_composio_api_key_here
-
-# Add other environment variables as needed for your example
-# OPENAI_API_KEY=your_openai_api_key_here
-# ANTHROPIC_API_KEY=your_anthropic_api_key_here
diff --git a/ts/examples/custom-tools/README.md b/ts/examples/custom-tools/README.md
deleted file mode 100644
index 9a86c3d97..000000000
--- a/ts/examples/custom-tools/README.md
+++ /dev/null
@@ -1,165 +0,0 @@
-# Custom Tools Examples
-
-This directory contains examples demonstrating how to create and use custom tools with Composio SDK.
-
-## Examples
-
-### 1. Simple Custom Tool (`simple.ts`)
-
-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:
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'CALCULATE_SQUARE',
- name: 'Calculate Square',
- description: 'Calculates the square of a number',
- inputParams: z.object({
- number: z.number().describe('The number to calculate the square of'),
- }),
- execute: async input => {
- const { number } = input;
- return {
- data: { result: number * number },
- error: null,
- successful: true,
- };
- },
-});
-```
-
-### 2. Toolkit-based Tools (`auth-credentials.ts`)
-
-Demonstrates two approaches to making authenticated requests in toolkit-based tools:
-
-#### Using executeToolRequest (Recommended)
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'GITHUB_LIST_AND_STAR',
- name: 'List and Star Repository',
- description: 'Lists repositories and stars them',
- toolkitSlug: 'github',
- inputParams: z.object({
- owner: z.string().describe('Repository owner'),
- }),
- execute: async (input, connectionConfig, executeToolRequest) => {
- // executeToolRequest can only call tools from the 'github' toolkit
- // Uses the same connected account credentials automatically
- const listResult = await executeToolRequest({
- slug: 'LIST_REPOSITORIES', // must be a github toolkit tool
- arguments: { owner: input.owner },
- });
-
- const starResult = await executeToolRequest({
- slug: 'STAR_REPOSITORY', // must be a github toolkit tool
- arguments: {
- owner: input.owner,
- repo: listResult.data.repositories[0].name,
- },
- });
-
- return {
- data: { listed: listResult.data, starred: starResult.data },
- error: null,
- successful: true,
- };
- },
-});
-```
-
-#### Using Direct API Calls
-
-```typescript
-const tool = await composio.tools.createCustomTool({
- slug: 'GITHUB_STAR_REPO',
- name: 'Star GitHub Repository',
- toolkitSlug: 'github',
- description: 'Stars a GitHub repository using direct API call',
- inputParams: z.object({
- repository: z.string().describe('The repository to star'),
- }),
- execute: async (input, connectionConfig) => {
- // Use connectionConfig for direct API calls or when interacting with different services
- const result = await fetch(
- `https://api.github.com/user/starred/composiohq/${input.repository}`,
- {
- method: 'PUT',
- headers: {
- Authorization: `Bearer ${connectionConfig.val?.access_token}`,
- },
- }
- );
- return {
- data: await result.json(),
- error: null,
- successful: true,
- };
- },
-});
-```
-
-## Running the Examples
-
-1. Set up your environment:
-
- ```bash
- cp .env.example .env
- ```
-
-2. Add your Composio API key to `.env`:
-
- ```
- COMPOSIO_API_KEY=your_api_key_here
- ```
-
-3. Run an example:
-
- ```bash
- # Run the simple example
- pnpm start:simple
-
- # Run the auth credentials example
- pnpm start:auth
- ```
-
-## Key Concepts
-
-1. **Standalone vs Toolkit-based Tools**
-
- - Standalone tools only receive input parameters
- - Toolkit-based tools have access to both `executeToolRequest` and `connectionConfig`
-
-2. **Authentication Methods**
-
- - `executeToolRequest`: Recommended way to use toolkit tools
- - Can only execute tools from the same toolkit
- - Uses the connected account credentials automatically
- - No need to manage auth tokens
- - Better maintainability and security
- - `connectionConfig`: For direct API calls
- - Use when you need to make direct API calls
- - Use when you need to interact with different services
- - Requires manual token management
- - More flexible but requires more maintenance
-
-3. **Type Safety**
-
- - Input parameters are validated using Zod schemas
- - TypeScript infers the correct execute function signature based on toolkitSlug
-
-4. **Error Handling**
-
- - Tools should always return a ToolExecuteResponse
- - Handle errors gracefully and provide meaningful error messages
-
-## Related Examples
-
-- [OpenAI Example](../openai) - Shows integration with OpenAI
-- [LangChain Example](../langchain) - Shows integration with LangChain
-- [More Examples](../) - Browse all available examples
-
-## Support
-
-- [Documentation](https://docs.composio.dev)
-- [Discord Community](https://discord.gg/composio)
-- [GitHub Issues](https://github.com/composio/composio/issues)
diff --git a/ts/examples/custom-tools/package.json b/ts/examples/custom-tools/package.json
deleted file mode 100644
index 77172850d..000000000
--- a/ts/examples/custom-tools/package.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "custom-tools-example",
- "private": true,
- "version": "0.1.0",
- "description": "Example project for Custom-tools",
- "main": "src/index.ts",
- "scripts": {
- "clean": "git clean -xdf node_modules",
- "start": "bun src/index.ts",
- "dev": "bun --watch src/index.ts",
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "keywords": [
- "composio",
- "example",
- "custom-tools"
- ],
- "author": "",
- "license": "ISC",
- "packageManager": "[email protected]",
- "dependencies": {
- "@composio/core": "workspace:*",
- "dotenv": "^16.4.1",
- "zod": "catalog:"
- },
- "devDependencies": {
- "@types/bun": "^1.2.9",
- "typescript": "catalog:"
- }
-}
diff --git a/ts/examples/custom-tools/src/connection-config.ts b/ts/examples/custom-tools/src/connection-config.ts
deleted file mode 100644
index e735032e2..000000000
--- a/ts/examples/custom-tools/src/connection-config.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Custom-tools Example
- *
- * This example demonstrates how to use Composio SDK for custom-tools with auth credentials.
- *
- * Prerequisites:
- * 1. Set up your COMPOSIO_API_KEY in the .env file
- * 3. Run the example: pnpm start
- */
-
-import { Composio } from '@composio/core';
-import 'dotenv/config';
-import { z } from 'zod';
-
-/**
- * Initialize Composio
- */
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
-});
-
-/**
- * Create a custom hackernews tool
- * This tool will be registerd in the composio instance and store in memory temporarily.
- */
-const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';
-const tool = await composio.tools.createCustomTool({
- slug: customToolSlug,
- name: 'Github star composio repositories',
- toolkitSlug: 'github',
- description: 'For any given repository of the user composiohq, star the repository',
- inputParams: z.object({
- repository: z.string().describe('The repository to star'),
- }),
- execute: async (input, connectionConfig) => {
- console.log('🚀 ~ execute: ~ params:', input);
- console.log('🚀 ~ execute: ~ connectionConfig:', connectionConfig);
- /**
- * The auth credentials are the auth credentials for the connected account.
- * You can use them to make requests to the API.
- */
- const result = await fetch(
- `https://api.github.com/user/starred/composiohq/${input.repository}`,
- {
- method: 'PUT',
- headers: {
- Authorization: `Bearer ${connectionConfig?.val?.access_token}`,
- },
- }
- );
- const data = await result.json();
- return {
- data: data,
- error: null,
- successful: true,
- };
- },
-});
-
-console.log('🚀 created tool:', tool);
-
-/**
- * Main function to run the example
- */
-async function main() {
- try {
- console.log('🚀 Starting Custom-tools Example...');
-
- // Get available tools
- const tools = await composio.tools.get('default', customToolSlug);
-
- console.log('tools:', tools);
-
- const result = await composio.tools.execute(customToolSlug, {
- arguments: {
- repository: 'composio',
- },
- userId: 'default',
- });
-
- console.log('🚀 Result:', result);
- } catch (error) {
- console.error('❌ Error running example:', error);
- }
-}
-
-// Run the example
-main().catch(console.error);
diff --git a/ts/examples/custom-tools/src/index.ts b/ts/examples/custom-tools/src/index.ts
deleted file mode 100644
index d6a7f5517..000000000
--- a/ts/examples/custom-tools/src/index.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Custom-tools Example
- *
- * This example demonstrates how to use Composio SDK for custom-tools.
- *
- * Prerequisites:
- * 1. Set up your COMPOSIO_API_KEY in the .env file
- * 3. Run the example: pnpm start
- */
-
-import { Composio } from '@composio/core';
-import 'dotenv/config';
-import { z } from 'zod';
-
-/**
- * Initialize Composio
- */
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
-});
-
-/**
- * Create a custom hackernews tool
- * This tool will be registerd in the composio instance and store in memory temporarily.
- */
-const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';
-const tool = await composio.tools.createCustomTool({
- slug: customToolSlug,
- name: 'Github star composio repositories',
- toolkitSlug: 'github',
- description: 'For any given repository of the user composiohq, star the repository',
- inputParams: z.object({
- repository: z.string().describe('The repository to star'),
- }),
- execute: async (input, connectionConfig, executeToolRequest) => {
- console.log('🚀 ~ execute: ~ params:', input);
- console.log('🚀 ~ execute: ~ connectionConfig:', connectionConfig);
-
- const result = await executeToolRequest({
- endpoint: `/user/starred/composiohq/${input.repository}`,
- method: 'PUT',
- });
- return result;
- },
-});
-
-console.log('🚀 created tool:', tool);
-
-/**
- * Main function to run the example
- */
-async function main() {
- try {
- console.log('🚀 Starting Custom-tools Example...');
-
- // Get available tools
- const tools = await composio.tools.get('default', customToolSlug);
-
- console.log('tools:', tools);
-
- const result = await composio.tools.execute(customToolSlug, {
- arguments: {
- repository: 'composio',
- },
- userId: 'default',
- });
-
- console.log('🚀 Result:', result);
- } catch (error) {
- console.error('❌ Error running example:', error);
- }
-}
-
-// Run the example
-main().catch(console.error);
diff --git a/ts/examples/custom-tools/src/simple.ts b/ts/examples/custom-tools/src/simple.ts
deleted file mode 100644
index e7084b1bc..000000000
--- a/ts/examples/custom-tools/src/simple.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Custom-tools Example
- *
- * This example demonstrates how to use Composio SDK for simple custom-tools.
- *
- * Prerequisites:
- * 1. Set up your COMPOSIO_API_KEY in the .env file
- * 3. Run the example: pnpm start
- */
-
-import { Composio } from '@composio/core';
-import 'dotenv/config';
-import { z } from 'zod';
-
-/**
- * Initialize Composio
- */
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
-});
-
-/**
- * Create a custom calculate square of a number tool
- * This tool will be registerd in the composio instance and store in memory temporarily.
- */
-const customToolSlug = 'CALCULATE_SQUARE_OF_A_NUMBER';
-const tool = await composio.tools.createCustomTool({
- slug: customToolSlug,
- name: 'Calculate square of a number',
- description: 'For any given number the tool calculates the square of the number',
- inputParams: z.object({
- number: z.number().describe('The number to calculate the square of'),
- }),
- execute: async input => {
- const { number } = input;
- const result = Number(number) * Number(number);
-
- return {
- data: {
- result,
- },
- error: null,
- successful: true,
- };
- },
-});
-
-console.log('🚀 created tool:', tool);
-
-/**
- * Main function to run the example
- */
-async function main() {
- try {
- console.log('🚀 Starting Custom-tools Example...');
-
- // Get available tools
- const tools = await composio.tools.get('default', customToolSlug);
-
- console.log('tools:', tools);
-
- const result = await composio.tools.execute(customToolSlug, {
- arguments: {
- number: 2,
- },
- userId: 'default',
- });
-
- console.log('🚀 Result:', result);
- } catch (error) {
- console.error('❌ Error running example:', error);
- }
-}
-
-// Run the example
-main().catch(console.error);
diff --git a/ts/examples/custom-tools/tsconfig.json b/ts/examples/custom-tools/tsconfig.json
deleted file mode 100644
index f736a53ab..000000000
--- a/ts/examples/custom-tools/tsconfig.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2022",
- "module": "esnext",
- "declaration": true,
- "declarationDir": "./dist",
- "outDir": "./dist",
- "rootDir": "./src",
- "strict": true,
- "esModuleInterop": true,
- "moduleResolution": "bundler",
- "skipLibCheck": true,
- "resolveJsonModule": true
- },
- "include": ["src"]
-}
diff --git a/ts/packages/core/scripts/generate-docs.ts b/ts/packages/core/scripts/generate-docs.ts
index f16692447..0c7e28c27 100644
--- a/ts/packages/core/scripts/generate-docs.ts
+++ b/ts/packages/core/scripts/generate-docs.ts
@@ -21,7 +21,6 @@ const TEMP_JSON = join(PACKAGE_DIR, '.typedoc-output.json');
// Internal classes that should NOT be documented (accessed via other APIs)
const INTERNAL_CLASSES = new Set([
- 'CustomTools', // Internal - accessed via composio.tools.createCustomTool()
'AuthScheme', // Utility class
'ConnectionRequest', // Utility
'Files', // Not yet stable API
diff --git a/ts/packages/core/src/errors/ToolErrors.ts b/ts/packages/core/src/errors/ToolErrors.ts
index e550fae52..8f1427f4b 100644
--- a/ts/packages/core/src/errors/ToolErrors.ts
+++ b/ts/packages/core/src/errors/ToolErrors.ts
@@ -6,7 +6,6 @@ export const ToolErrorCodes = {
TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
INVALID_MODIFIER: 'INVALID_MODIFIER',
- CUSTOM_TOOLS_NOT_INITIALIZED: 'CUSTOM_TOOLS_NOT_INITIALIZED',
TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
GLOBAL_EXECUTE_TOOL_FN_NOT_SET: 'GLOBAL_EXECUTE_TOOL_FN_NOT_SET',
@@ -61,22 +60,6 @@ export class ComposioInvalidModifierError extends ComposioError {
}
}
-export class ComposioCustomToolsNotInitializedError extends ComposioError {
- constructor(
- message: string = 'Custom tools not initialized',
- options: Omit<ComposioErrorOptions, 'code'> = {}
- ) {
- super(message, {
- ...options,
- code: ToolErrorCodes.CUSTOM_TOOLS_NOT_INITIALIZED,
- possibleFixes: options.possibleFixes || [
- 'Ensure the custom tools class is initialized in the Tools instance',
- ],
- });
- this.name = 'ComposioCustomToolsNotInitializedError';
- }
-}
-
export class ComposioToolExecutionError extends ComposioError {
constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {
super(message, {
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.ts
index 3118a2a3d..3c4cb9d30 100644
--- a/ts/packages/core/src/models/CustomTool.ts
+++ b/ts/packages/core/src/models/CustomTool.ts
@@ -34,7 +34,6 @@ import {
type CustomToolsMapEntry,
type CustomToolWireDefinition,
type CustomToolkitWireDefinition,
- type InputParamsSchema,
} from '../types/customTool.types';
import type {
SessionCreateResponse,
@@ -49,6 +48,16 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
/** Maximum allowed length for the final prefixed slug. */
const MAX_SLUG_LENGTH = 60;
+type InputParamsSchema = {
+ definitions: {
+ input: {
+ type: string;
+ properties: Record<string, unknown>;
+ required?: string[];
+ };
+ };
+};
+
/**
* Compute the final slug length for a tool given its context.
* Returns the expected length of LOCAL_[TOOLKIT_]SLUG.
diff --git a/ts/packages/core/src/models/CustomTools.ts b/ts/packages/core/src/models/CustomTools.ts
deleted file mode 100644
index ae22e680f..000000000
--- a/ts/packages/core/src/models/CustomTools.ts
+++ /dev/null
@@ -1,342 +0,0 @@
-/**
- * @fileoverview Custom tools class for Composio SDK, used to manage custom tools created by users.
- *
- * @author Musthaq Ahamad <[email protected]>
- * @date 2025-05-05
- * @module CustomTools
- */
-import ComposioClient from '@composio/client';
-import {
- CustomToolInputParameter,
- CustomToolOptions,
- CustomToolRegistry,
- InputParamsSchema,
-} from '../types/customTool.types';
-import * as zodToJsonSchema from 'zod-to-json-schema';
-import {
- Tool,
- ToolExecuteParams,
- ToolExecuteResponse,
- ToolList,
- ToolProxyParams,
-} from '../types/tool.types';
-import logger from '../utils/logger';
-import {
- ComposioInvalidExecuteFunctionError,
- ComposioToolNotFoundError,
-} from '../errors/ToolErrors';
-import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsErrors';
-import { ComposioError } from '../errors/ComposioError';
-import { telemetry } from '../telemetry/Telemetry';
-import { ConnectedAccountRetrieveResponse } from '../types/connectedAccounts.types';
-import { ValidationError } from '../errors';
-import { transformConnectedAccountResponse } from '../utils/transformers/connectedAccounts';
-import { ConnectionData } from '../types/connectedAccountAuthStates.types';
-import { AuthSchemeTypes } from '../types/authConfigs.types';
-
-export class CustomTools {
- private readonly client: ComposioClient;
- private readonly customToolsRegistry: CustomToolRegistry;
-
- constructor(client: ComposioClient) {
- if (!client) {
- throw new ComposioError('ComposioClient is required');
- }
- this.client = client;
- this.customToolsRegistry = new Map();
- telemetry.instrument(this, 'CustomTools');
- }
-
- /**
- * Create a custom tool and registers it in the registry.
- * This is just an in memory registry and is not persisted.
- * @param {CustomToolOptions} toolOptions CustomToolOptions
- * @returns {Tool} The tool created
- *
- * @example
- * ```typescript
- * // Create a custom tool with input parameters
- * const customTool = await composio.customTools.createTool({
- * name: 'My Custom Tool',
- * description: 'A tool that performs a custom operation',
- * slug: 'MY_CUSTOM_TOOL',
- * inputParams: z.object({
- * query: z.string().describe('The search query'),
- * limit: z.number().optional().describe('Maximum number of results')
- * }),
- * execute: async (input, connectionConfig, executeToolRequest) => {
- * // Custom implementation logic
- * return {
- * data: { results: ['result1', 'result2'] }
- * };
- * }
- * });
- * ```
- */
- async createTool<T extends CustomToolInputParameter>(
- toolOptions: CustomToolOptions<T>
- ): Promise<Tool> {
- const { slug, execute, inputParams, name, description } = toolOptions;
- if (!slug || !execute || !inputParams || !name) {
- throw new Error('Invalid tool options');
- }
- // generate the input parameters schema
- const paramsSchema: InputParamsSchema = zodToJsonSchema.default(inputParams, {
- name: 'input',
- }) as InputParamsSchema;
- const paramsSchemaJson = paramsSchema.definitions.input;
- const toolSchema: Tool = {
- name: name,
- slug: slug,
- description: description,
- inputParameters: {
- title: name,
- type: 'object',
- description: description,
- properties: paramsSchemaJson.properties,
- required: paramsSchemaJson.required,
- },
- // the output parameters are not used yet
- outputParameters: {
- type: 'object',
- title: `Response for ${name}`,
- properties: {},
- },
- tags: [],
- // this is never set to the user provided toolkitslug so that we can differentiate
- // the toolkitslug is used via the execute function.
- toolkit: { name: 'custom', slug: 'custom' },
- };
-
- this.customToolsRegistry.set(slug.toLowerCase(), {
- options: toolOptions as unknown as CustomToolOptions<CustomToolInputParameter>,
- schema: toolSchema,
- });
- return toolSchema;
- }
-
- /**
- * Get all the custom tools from the registry.
- * @param {string[]} param0.toolSlugs The slugs of the tools to get
- * @returns {ToolList} The list of tools
- *
- * @example
- * ```typescript
- * // Get all custom tools
- * const allTools = await composio.customTools.getCustomTools({});
- *
- * // Get specific custom tools by slug
- * const specificTools = await composio.customTools.getCustomTools({
- * toolSlugs: ['MY_CUSTOM_TOOL', 'ANOTHER_CUSTOM_TOOL']
- * });
- * ```
- */
- async getCustomTools({ toolSlugs }: { toolSlugs?: string[] }): Promise<ToolList> {
- const tools: Tool[] = [];
-
- if (toolSlugs) {
- // If specific slugs are provided, only return those tools
- for (const slug of toolSlugs) {
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
- if (tool) {
- tools.push(tool.schema);
- }
- }
- } else {
- // If no slugs provided, return all tools
- return Array.from(this.customToolsRegistry.values()).map(tool => tool.schema);
- }
-
- return tools;
- }
-
- /**
- * Get a custom tool by slug from the registry.
- * @param {string} slug The slug of the tool to get
- * @returns {Tool} The tool
- *
- * @example
- * ```typescript
- * // Get a specific custom tool by its slug
- * const myTool = await composio.customTools.getCustomToolBySlug('MY_CUSTOM_TOOL');
- * if (myTool) {
- * console.log(`Found tool: ${myTool.name}`);
- * } else {
- * console.log('Tool not found');
- * }
- * ```
- */
- async getCustomToolBySlug(slug: string): Promise<Tool | undefined> {
- try {
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
- return tool?.schema;
- } catch (error) {
- logger.error(`Error getting custom tool: ${error}`);
- return undefined;
- }
- }
-
- /**
- * Get the connected account for the user and toolkit.
- * @param {string} toolkitSlug The slug of the toolkit
- * @param {ExecuteMetadata} metadata The metadata of the execution
- * @returns {ConnectedAccount} The connected account
- */
- private async getConnectedAccountForToolkit(
- toolkitSlug: string,
- userId: string,
- connectedAccountId?: string
- ): Promise<ConnectedAccountRetrieveResponse | null> {
- try {
- await this.client.toolkits.retrieve(toolkitSlug);
- // check if the toolkit is a no auth toolkit
- const toolkit = await this.client.toolkits.retrieve(toolkitSlug);
- const isNoAuthToolkit = toolkit.auth_config_details?.some(
- details => details.mode === AuthSchemeTypes.NO_AUTH
- );
- if (isNoAuthToolkit) {
- return null;
- }
- } catch (error) {
- throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
- cause: error,
- });
- }
- const connectedAccounts = await this.client.connectedAccounts.list({
- toolkit_slugs: [toolkitSlug],
- user_ids: [userId],
- });
-
- if (!connectedAccounts.items.length) {
- throw new ComposioConnectedAccountNotFoundError(
- `No connected accounts found for toolkit ${toolkitSlug}`
- );
- }
- // if a connected account id is provided, use it, otherwise use the first connected account
- const connectedAccount = connectedAccountId
- ? connectedAccounts.items.find(item => item.id === connectedAccountId)
- : connectedAccounts.items[0];
-
- if (!connectedAccount) {
- throw new ComposioConnectedAccountNotFoundError(
- `Connected account not found for toolkit ${toolkitSlug} for user ${userId}`
- );
- }
-
- return transformConnectedAccountResponse(connectedAccount);
- }
-
- /**
- * Execute a custom tool
- *
- * @description If a toolkit is used, the connected account id is used to execute the tool.
- * If a connected account id is provided, it is used to execute the tool.
- * If a connected account id is not provided, the first connected account for the toolkit is used.
- *
- * @param {slug} slug The slug of the tool to execute
- * @param {Record<string, unknown>} inputParams The input parameters for the tool
- * @param {ExecuteMetadata} metadata The metadata of the execution
- * @returns {Promise<ToolExecuteResponse>} The response from the tool
- */
- async executeCustomTool(slug: string, body: ToolExecuteParams): Promise<ToolExecuteResponse> {
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
- if (!tool) {
- throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
- }
-
- let connectionConfig: ConnectionData | null = null;
- const { toolkitSlug, execute, inputParams } = tool.options;
- // if a toolkit is used, get the connected account, and auth credentials
- let connectedAccountId: string | undefined = body.connectedAccountId;
- // if a toolkit is used, and a userId is provided, get the connected account
- if (toolkitSlug && toolkitSlug !== 'custom' && body.userId) {
- const connectedAccount = await this.getConnectedAccountForToolkit(
- toolkitSlug,
- body.userId,
- body.connectedAccountId
- );
- logger.debug(
- `[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`,
- JSON.stringify(connectedAccount, null, 2)
- );
- if (!connectedAccount) {
- throw new ComposioConnectedAccountNotFoundError(
- `Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`,
- {
- meta: {
- toolkitSlug,
- userId: body.userId,
- },
- }
- );
- }
- connectionConfig = connectedAccount.state ?? null;
- connectedAccountId = connectedAccount.id;
- }
-
- if (typeof execute !== 'function') {
- throw new ComposioInvalidExecuteFunctionError('Invalid execute function', {
- meta: {
- toolSlug: slug,
- },
- });
- }
- // create a tool proxy request for users to execute in case of a toolkit being used
- const executeToolRequest = async (data: ToolProxyParams): Promise<ToolExecuteResponse> => {
- // if the toolkit is custom, throw an error while trying to execute the tool by user
- if (toolkitSlug && toolkitSlug === 'custom') {
- throw new ComposioInvalidExecuteFunctionError(
- 'Custom tools without a toolkit cannot be executed using the executeToolRequest function',
- {
- possibleFixes: [
- 'Please manually execute the tool using your logic.',
- 'Pass a toolkit slug to execute the tool on behalf of a toolkit credentials',
- ],
- }
- );
- }
- // map the parameters to the composio format
- const parameters = data.parameters?.map(param => ({
- name: param.name,
- type: param.in,
- value: param.value.toString(),
- }));
-
- // execute the tool
- const response = await this.client.tools.proxy({
- endpoint: data.endpoint,
- method: data.method,
- parameters: parameters,
- body: data.body,
- connected_account_id: connectedAccountId,
- /**
- * @deprecated
- * @description
- * This parameter is deprecated and will be removed in the future.
- * Please use custom_auth_params instead.
- *
- */
- // @ts-ignore
- custom_connection_data: data.customConnectionData,
- });
-
- return {
- data: response.data as Record<string, unknown>,
- error: null,
- successful: true,
- logId: undefined,
- sessionInfo: undefined,
- };
- };
-
- // Parse and validate the input using the tool's schema
- const parsedInput = inputParams.safeParse(body.arguments);
- if (!parsedInput.success) {
- throw new ValidationError('Invalid input parameters', {
- cause: parsedInput.error,
- });
- }
-
- return execute(parsedInput.data, connectionConfig, executeToolRequest);
- }
-}
diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.ts
index f297f48c1..25ddb7493 100644
--- a/ts/packages/core/src/models/Tools.ts
+++ b/ts/packages/core/src/models/Tools.ts
@@ -30,8 +30,6 @@ import {
ToolListParams as ComposioToolListParams,
ToolExecuteParams as ComposioToolExecuteParams,
} from '@composio/client/resources/tools';
-import { CustomTools } from './CustomTools';
-import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';
import {
afterExecuteModifier,
ExecuteToolModifiers,
@@ -43,7 +41,6 @@ import { BaseComposioProvider } from '../provider/BaseProvider';
import logger from '../utils/logger';
import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types';
import {
- ComposioCustomToolsNotInitializedError,
ComposioInvalidModifierError,
ComposioToolNotFoundError,
ComposioProviderNotDefinedError,
@@ -98,7 +95,6 @@ export class Tools<
TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
> {
private client: ComposioClient;
- private readonly customTools: CustomTools;
private provider: TProvider;
private autoUploadDownloadFiles: boolean;
private toolkitVersions: ToolkitVersionParam;
@@ -124,7 +120,6 @@ export class Tools<
}
this.client = client;
- this.customTools = new CustomTools(client);
this.provider = config.provider;
this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true;
this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
@@ -142,7 +137,6 @@ export class Tools<
this.execute = this.execute.bind(this);
// Set the execute method for the provider.
this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
- // Bind methods that use customTools to ensure correct 'this' context
this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
this.getRawComposioTools = this.getRawComposioTools.bind(this);
@@ -337,10 +331,12 @@ export class Tools<
}
/**
- * Lists all tools available in the Composio SDK including custom tools.
+ * Lists Composio API tools available to the SDK.
*
- * This method fetches tools from the Composio API in raw format and combines them with
- * any registered custom tools. The response can be filtered and modified as needed.
+ * This method fetches remote Composio tools from the API in raw format. The response can be
+ * filtered and modified as needed. Local experimental custom tools are session-scoped; attach
+ * them when creating or reusing a Tool Router session, then use `session.tools()`,
+ * `session.customTools()`, or `session.execute()`.
* It provides access to the underlying tool data without provider-specific wrapping.
*
* @param {ToolListParams} query - Query parameters to filter the tools (required)
@@ -467,14 +463,7 @@ export class Tools<
}
const caseTransformedTools = tools.items.map(tool => this.transformToolCases(tool));
- const customTools = await this.customTools.getCustomTools({
- toolSlugs: 'tools' in queryParams.data ? queryParams.data.tools : undefined,
- });
-
- let modifiedTools = await this.applyDefaultSchemaModifiers([
- ...caseTransformedTools,
- ...customTools,
- ]);
+ let modifiedTools = await this.applyDefaultSchemaModifiers(caseTransformedTools);
// apply local modifiers if they are provided
if (options?.modifySchema) {
@@ -555,6 +544,9 @@ export class Tools<
* This method fetches a single tool in raw format without provider-specific wrapping,
* providing direct access to the tool's schema and metadata. Tool versions are controlled
* at the Composio SDK initialization level through the `toolkitVersions` configuration.
+ * Local experimental custom tools are session-scoped; attach them when creating or reusing a
+ * Tool Router session, then use `session.tools()`, `session.customTools()`, or
+ * `session.execute()`.
*
* @param {string} slug - The unique identifier of the tool (e.g., 'GITHUB_GET_REPOS')
* @param {GetRawComposioToolBySlugOptions} [options] - Optional configuration for tool retrieval
@@ -584,9 +576,6 @@ export class Tools<
* }
* );
*
- * // Get a custom tool (will check custom tools first)
- * const customTool = await composio.tools.getRawComposioToolBySlug('MY_CUSTOM_TOOL');
- *
* // Access tool properties
* const githubTool = await composio.tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
* console.log({
@@ -600,15 +589,6 @@ export class Tools<
* ```
*/
async getRawComposioToolBySlug(slug: string, options?: ToolRetrievalOptions): Promise<Tool> {
- // check if the tool is a custom tool
- const customTool = await this.customTools.getCustomToolBySlug(slug);
- if (customTool) {
- logger.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
- return customTool;
- } else {
- logger.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
- }
- // if not, fetch the tool from the Composio API
let tool: ToolRetrieveResponse;
try {
// Build API call parameters based on version source
@@ -915,8 +895,7 @@ export class Tools<
/**
* Executes a given tool with the provided parameters.
*
- * This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
- * It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
+ * This method calls the Composio API to execute the tool and returns the response.
*
* **Version Control:**
* By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest",
@@ -933,7 +912,6 @@ export class Tools<
* @param {ExecuteToolModifiers} [modifiers] - Optional modifiers to transform the request or response
* @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
*
- * @throws {ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized
* @throws {ComposioConnectedAccountNotFoundError} If the connected account is not found
* @throws {ComposioToolNotFoundError} If the tool with the given slug is not found
* @throws {ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true
@@ -990,24 +968,14 @@ export class Tools<
body: ToolExecuteParams,
modifiers?: ExecuteToolModifiers
): Promise<ToolExecuteResponse> {
- if (!this.customTools) {
- throw new ComposioCustomToolsNotInitializedError(
- 'CustomTools not initialized. Make sure Tools class is properly constructed.'
- );
- }
-
const executeParams = ToolExecuteParamsSchema.safeParse(body);
if (!executeParams.success) {
throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
}
- // Determine if it's a custom tool or composio tool
- const customTool = await this.customTools.getCustomToolBySlug(slug);
- const tool =
- customTool ??
- (await this.getRawComposioToolBySlug(slug, {
- version: body.version,
- }));
+ const tool = await this.getRawComposioToolBySlug(slug, {
+ version: body.version,
+ });
const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
// Apply before execute modifiers
@@ -1021,10 +989,7 @@ export class Tools<
modifiers
);
- // Execute the tool (custom or composio)
- let result = customTool
- ? await this.customTools.executeCustomTool(customTool.slug, params)
- : await this.executeComposioTool(tool, params);
+ let result = await this.executeComposioTool(tool, params);
// Apply after execute modifiers
result = await this.applyAfterExecuteModifiers(
@@ -1214,55 +1179,4 @@ export class Tools<
custom_connection_data: toolProxyParams.data.customConnectionData,
});
}
-
- /**
- * Creates a custom tool that can be used within the Composio SDK.
- *
- * Custom tools allow you to extend the functionality of Composio with your own implementations
- * while keeping a consistent interface for both built-in and custom tools.
- *
- * @param {CustomToolOptions} body - The configuration for the custom tool
- * @returns {Promise<Tool>} The created custom tool
- *
- * @example
- * ```typescript
- * // creating a custom tool with a toolkit
- * await composio.tools.createCustomTool({
- * name: 'My Custom Tool',
- * description: 'A custom tool that does something specific',
- * slug: 'MY_CUSTOM_TOOL',
- * userId: 'default',
- * connectedAccountId: '123',
- * toolkitSlug: 'github',
- * inputParameters: z.object({
- * param1: z.string().describe('First parameter'),
- * }),
- * execute: async (input, connectionConfig, executeToolRequest) => {
- * // Custom logic here
- * return { data: { result: 'Success!' } };
- * }
- * });
- * ```
- *
- * @example
- * ```typescript
- * // creating a custom tool without a toolkit
- * await composio.tools.createCustomTool({
- * name: 'My Custom Tool',
- * description: 'A custom tool that does something specific',
- * slug: 'MY_CUSTOM_TOOL',
- * inputParameters: z.object({
- * param1: z.string().describe('First parameter'),
- * }),
- * execute: async (input) => {
- * // Custom logic here
- * return { data: { result: 'Success!' } };
- * }
- * });
- */
- async createCustomTool<T extends CustomToolInputParameter>(
- body: CustomToolOptions<T>
- ): Promise<Tool> {
- return this.customTools.createTool(body);
- }
}
diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.ts
index 054575d81..788bf6e09 100644
--- a/ts/packages/core/src/types/customTool.types.ts
+++ b/ts/packages/core/src/types/customTool.types.ts
@@ -1,72 +1,14 @@
import { z } from 'zod/v3';
-import { Tool, ToolProxyParams } from './tool.types';
import type {
SessionProxyExecuteParams,
ToolRouterSessionExecuteResponse,
ToolRouterSessionProxyExecuteResponse,
} from './toolRouter.types';
-import { ToolExecuteResponse } from '@composio/client/resources/tools';
-import { ConnectionData } from './connectedAccountAuthStates.types';
import type {
SessionCreateParams,
SessionCreateResponse,
} from '@composio/client/resources/tool-router/session/session.mjs';
-// ────────────────────────────────────────────────────────────────
-// Legacy custom tool types (used by composio.tools.createCustomTool)
-// ────────────────────────────────────────────────────────────────
-
-type BaseCustomToolOptions<T extends z.ZodType> = {
- name: string;
- description?: string;
- slug: string;
- inputParams: T;
-};
-
-type ToolkitBasedExecute<T extends z.ZodType> = {
- execute: (
- input: z.infer<T>,
- connectionConfig: ConnectionData | null,
- executeToolRequest: (data: ToolProxyParams) => Promise<ToolExecuteResponse>
- ) => Promise<ToolExecuteResponse>;
- toolkitSlug: string;
-};
-
-type StandaloneExecute<T extends z.ZodType> = {
- execute: (input: z.infer<T>) => Promise<ToolExecuteResponse>;
- toolkitSlug?: never;
-};
-
-export type CustomToolOptions<T extends z.ZodType> = BaseCustomToolOptions<T> &
- (ToolkitBasedExecute<T> | StandaloneExecute<T>);
-
-export type CustomToolRegistry = Map<
- string,
- { options: CustomToolOptions<CustomToolInputParameter>; schema: Tool }
->;
-
-export type InputParamsSchema = {
- definitions: {
- input: {
- type: string;
- properties: Record<string, unknown>;
- required?: string[];
- };
- };
-};
-
-export type CustomToolInputParameter = z.ZodType;
-
-export interface CustomToolRegistryItem {
- options: CustomToolOptions<CustomToolInputParameter>;
- schema: Tool;
-}
-
-export interface ExecuteMetadata {
- userId: string;
- connectedAccountId?: string;
-}
-
// ────────────────────────────────────────────────────────────────
// New custom tool types (for tool router integration via createCustomTool())
// ────────────────────────────────────────────────────────────────
diff --git a/ts/packages/core/test/tools/customTools.test.ts b/ts/packages/core/test/tools/customTools.test.ts
deleted file mode 100644
index e791efe36..000000000
--- a/ts/packages/core/test/tools/customTools.test.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { CustomTools } from '../../src/models/CustomTools';
-import { mockClient } from '../utils/mocks/client.mock';
-import { toolMocks } from '../utils/mocks/data.mock';
-import ComposioClient from '@composio/client';
-import { z } from 'zod/v3';
-import { ComposioToolNotFoundError } from '../../src/errors/ToolErrors';
-import { ComposioConnectedAccountNotFoundError } from '../../src/errors/ConnectedAccountsErrors';
-import { ValidationError } from '../../src/errors';
-
-describe('CustomTools', () => {
- let customTools: CustomTools;
-
- const toolOptions = {
- slug: 'CUSTOM_TOOL',
- name: 'Custom Tool',
- description: 'A custom tool for testing',
- inputParams: z.object({
- query: z.string().describe('The search query'),
- }),
- execute: vi.fn().mockResolvedValue(toolMocks.toolExecuteResponse),
- };
-
- beforeEach(() => {
- vi.clearAllMocks();
- customTools = new CustomTools(mockClient as unknown as ComposioClient);
- });
-
- it('should throw an error if client is not provided', () => {
- expect(() => new CustomTools(null as any)).toThrow('ComposioClient is required');
- });
-
- describe('createTool', () => {
- it('should create a custom tool and add it to the registry', async () => {
- const result = await customTools.createTool(toolOptions);
-
- expect(result).toMatchObject({
- slug: toolOptions.slug,
- name: toolOptions.name,
- description: toolOptions.description,
- inputParameters: expect.any(Object),
- outputParameters: expect.any(Object),
- });
-
- // Verify it's in the registry
- const registryTool = await customTools.getCustomToolBySlug(toolOptions.slug);
- expect(registryTool).toBeDefined();
- expect(registryTool?.slug).toEqual(toolOptions.slug);
- });
-
- it('should throw an error for invalid tool options', async () => {
- const invalidOptions = {
- slug: 'INVALID_TOOL',
- // Missing required properties
- };
-
- await expect(customTools.createTool(invalidOptions as any)).rejects.toThrow(Error);
- });
- });
-
- describe('getCustomTools', () => {
- it('should return all tools from the registry when no slugs provided', async () => {
- // Add tools to the registry
- await customTools.createTool(toolOptions);
- await customTools.createTool({
- ...toolOptions,
- slug: 'ANOTHER_TOOL',
- });
-
- const result = await customTools.getCustomTools({});
-
- expect(result).toHaveLength(2);
- expect(result[0].slug).toEqual('CUSTOM_TOOL');
- expect(result[1].slug).toEqual('ANOTHER_TOOL');
- });
-
- it('should filter tools by slug when provided', async () => {
- // Add tools to the registry
- await customTools.createTool(toolOptions);
- await customTools.createTool({
- ...toolOptions,
- slug: 'ANOTHER_TOOL',
- });
-
- const result = await customTools.getCustomTools({
- toolSlugs: ['CUSTOM_TOOL'],
- });
-
- expect(result).toHaveLength(1);
- expect(result[0].slug).toEqual('CUSTOM_TOOL');
- });
- });
-
- describe('executeCustomTool', () => {
- const executeParams = {
- arguments: { query: 'test query' },
- userId: 'test-user',
- };
-
- it('should execute a custom tool with provided parameters', async () => {
- // Add a tool to the registry
- await customTools.createTool(toolOptions);
-
- const result = await customTools.executeCustomTool(toolOptions.slug, executeParams);
-
- expect(toolOptions.execute).toHaveBeenCalledWith(
- executeParams.arguments,
- null,
- expect.any(Function)
- );
- expect(result).toEqual(toolMocks.toolExecuteResponse);
- });
-
- it('should throw an error if tool does not exist', async () => {
- const nonExistentSlug = 'NON_EXISTENT';
-
- await expect(customTools.executeCustomTool(nonExistentSlug, executeParams)).rejects.toThrow(
- ComposioToolNotFoundError
- );
- });
-
- it('should throw validation error for invalid input parameters', async () => {
- await customTools.createTool(toolOptions);
- const invalidParams = {
- ...executeParams,
- arguments: { invalidField: 'test' },
- };
-
- await expect(customTools.executeCustomTool(toolOptions.slug, invalidParams)).rejects.toThrow(
- ValidationError
- );
- });
-
- describe('toolkit-based custom tools', () => {
- const toolkitTool = {
- ...toolOptions,
- toolkitSlug: 'TEST_TOOLKIT',
- };
-
- const mockConnectedAccount = {
- id: 'conn-123',
- auth_config: {
- id: 'auth-123',
- auth_scheme: 'OAUTH2',
- is_composio_managed: true,
- is_disabled: false,
- },
- user_id: 'test-user',
- data: {},
- state: {
- authScheme: 'OAUTH2',
- val: {
- status: 'ACTIVE',
- access_token: 'test-token',
- token_type: 'Bearer',
- },
- },
- status: 'ACTIVE',
- status_reason: null,
- toolkit: {
- slug: 'TEST_TOOLKIT',
- },
- test_request_endpoint: 'https://api.test.com',
- is_disabled: false,
- created_at: '2024-01-01T00:00:00Z',
- updated_at: '2024-01-01T00:00:00Z',
- };
-
- beforeEach(async () => {
- await customTools.createTool(toolkitTool);
- mockClient.toolkits.retrieve.mockResolvedValue({ slug: 'TEST_TOOLKIT' });
- });
-
- it('should fetch and use auth credentials for toolkit-based custom tools', async () => {
- mockClient.connectedAccounts.list.mockResolvedValueOnce({
- items: [mockConnectedAccount],
- totalPages: 1,
- });
-
- await customTools.executeCustomTool(toolkitTool.slug, executeParams);
-
- expect(toolkitTool.execute).toHaveBeenCalledWith(
- executeParams.arguments,
- mockConnectedAccount.state,
- expect.any(Function)
- );
- });
-
- it('should use specified connected account when connectedAccountId is provided', async () => {
- const specificConnectedAccountId = 'conn-456';
- const specificConnectedAccount = {
- ...mockConnectedAccount,
- id: specificConnectedAccountId,
- };
-
- mockClient.connectedAccounts.list.mockResolvedValueOnce({
- items: [mockConnectedAccount, specificConnectedAccount],
- totalPages: 1,
- });
-
- await customTools.executeCustomTool(toolkitTool.slug, {
- ...executeParams,
- connectedAccountId: specificConnectedAccountId,
- });
-
- expect(toolkitTool.execute).toHaveBeenCalledWith(
- executeParams.arguments,
- specificConnectedAccount.state,
- expect.any(Function)
- );
- });
-
- it('should throw error when toolkit is not found', async () => {
- mockClient.toolkits.retrieve.mockRejectedValueOnce(new Error('Toolkit not found'));
-
- await expect(
- customTools.executeCustomTool(toolkitTool.slug, executeParams)
- ).rejects.toThrow(ComposioToolNotFoundError);
- });
-
- it('should throw error when no connected accounts are found', async () => {
- mockClient.connectedAccounts.list.mockResolvedValueOnce({
- items: [],
- totalPages: 1,
- });
-
- await expect(
- customTools.executeCustomTool(toolkitTool.slug, executeParams)
- ).rejects.toThrow(ComposioConnectedAccountNotFoundError);
- });
-
- it('should throw error when specified connected account is not found', async () => {
- mockClient.connectedAccounts.list.mockResolvedValueOnce({
- items: [mockConnectedAccount],
- totalPages: 1,
- });
-
- await expect(
- customTools.executeCustomTool(toolkitTool.slug, {
- ...executeParams,
- connectedAccountId: 'non-existent-id',
- })
- ).rejects.toThrow(ComposioConnectedAccountNotFoundError);
- });
-
- it('should throw error when trying to use executeToolRequest with custom toolkit', async () => {
- const customToolkitTool = {
- ...toolOptions,
- toolkitSlug: 'custom',
- execute: async (input: any, auth: any, executeToolRequest: any) => {
- return executeToolRequest({ slug: 'TEST_TOOL', arguments: {} });
- },
- };
-
- await customTools.createTool(customToolkitTool);
-
- await expect(
- customTools.executeCustomTool(customToolkitTool.slug, executeParams)
- ).rejects.toThrow(
- 'Custom tools without a toolkit cannot be executed using the executeToolRequest function'
- );
- });
- });
- });
-});
diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.ts
index effd7e841..5ff2defa7 100644
--- a/ts/packages/core/test/tools/tools.test.ts
+++ b/ts/packages/core/test/tools/tools.test.ts
@@ -285,21 +285,6 @@ describe('Tools', () => {
expect(result[0].outputParameters).toEqual(toolMocks.transformedTool.outputParameters);
});
- it('should include custom tools in the results', async () => {
- mockClient.tools.list.mockResolvedValueOnce({
- items: [toolMocks.rawTool],
- totalPages: 1,
- });
-
- const getCustomToolsSpy = vi.spyOn(context.tools['customTools'], 'getCustomTools');
- getCustomToolsSpy.mockResolvedValueOnce([toolMocks.customTool as unknown as Tool]);
-
- const result = await context.tools.getRawComposioTools({ tools: ['TEST_TOOL'] });
-
- expect(result).toHaveLength(2);
- expect(result[1].slug).toEqual(toolMocks.customTool.slug);
- });
-
it('should apply schema modifiers when provided', async () => {
const schemaModifier = createSchemaModifier({
description: 'Modified description',
@@ -392,24 +377,9 @@ describe('Tools', () => {
expect(result.slug).toEqual(toolMocks.transformedTool.slug);
});
- it('should check for custom tools first', async () => {
- const slug = 'CUSTOM_TOOL';
-
- const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(toolMocks.customTool as unknown as Tool);
-
- const result = await context.tools.getRawComposioToolBySlug(slug);
-
- expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
- expect(mockClient.tools.retrieve).not.toHaveBeenCalled();
- expect(result.slug).toEqual(toolMocks.customTool.slug);
- });
-
it('should throw an error if tool is not found', async () => {
const slug = 'NONEXISTENT_TOOL';
- const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
mockClient.tools.retrieve.mockRejectedValue(null);
await expect(context.tools.getRawComposioToolBySlug(slug)).rejects.toThrow(
@@ -664,24 +634,6 @@ describe('Tools', () => {
});
describe('execute', () => {
- it('should execute a custom tool', async () => {
- const slug = 'CUSTOM_TOOL';
- const body = { userId: 'test-user', arguments: { query: 'test' } };
-
- const { getCustomToolBySlugSpy } = await mockToolExecution(context.tools, {
- customToolExists: true,
- });
-
- const executeCustomToolSpy = vi.spyOn(context.tools['customTools'], 'executeCustomTool');
- executeCustomToolSpy.mockResolvedValueOnce(toolMocks.toolExecuteResponse);
-
- const result = await context.tools.execute(slug, body);
-
- expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
- expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body);
- expect(result).toEqual(toolMocks.toolExecuteResponse);
- });
-
it('should execute a composio tool', async () => {
const slug = 'COMPOSIO_TOOL';
const body = {
diff --git a/ts/packages/core/test/utils/toolExecuteUtils.ts b/ts/packages/core/test/utils/toolExecuteUtils.ts
index f96427fab..21e0037c1 100644
--- a/ts/packages/core/test/utils/toolExecuteUtils.ts
+++ b/ts/packages/core/test/utils/toolExecuteUtils.ts
@@ -29,10 +29,7 @@ export const setupTest = (context: TestContext) => {
});
};
-export const mockToolExecution = async (
- tools: TestTools,
- { customToolExists = false, connectedAccountId = 'test-connected-account-id' } = {}
-) => {
+export const mockToolExecution = async (tools: TestTools) => {
// Mock client responses
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
mockClient.toolkits.retrieve.mockResolvedValueOnce(toolkitMocks.rawToolkit);
@@ -40,12 +37,6 @@ export const mockToolExecution = async (
connectedAccountMocks.rawConnectedAccountsResponse
);
- // Mock custom tool check
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(
- customToolExists ? (toolMocks.customTool as unknown as Tool) : undefined
- );
-
// Mock composio tool retrieval
const getRawComposioToolBySlugSpy = vi.spyOn(tools, 'getRawComposioToolBySlug');
getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
@@ -54,7 +45,6 @@ export const mockToolExecution = async (
mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
return {
- getCustomToolBySlugSpy,
getRawComposioToolBySlugSpy,
};
};