Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Remove global userIDs
haxzief169bb2edac9
diff --git a/README.md b/README.mdindex 319ee5d0d..57dd705eb 100644--- a/README.md+++ b/README.md@@ -11,6 +11,34 @@ The core Composio SDK which allows users to interact with the Composio Platform.- **ConnectedAccounts**: Manage third-party service connections. Includes functionality to create, list, refresh, and manage the status of connected accounts.- **ActionExecution**: Track and manage the execution of actions within the platform.+## Installation++```bash+npm install @composio/core+# or+yarn add @composio/core+# or+pnpm add @composio/core+```++## Configuration++```typescript+interface ComposioConfig {+ apiKey?: string; // Your Composio API key+ baseURL?: string; // Custom API base URL (optional)+ allowTracking?: boolean; // Enable/disable telemetry (default: true)+ allowTracing?: boolean; // Enable/disable tracing (default: true)+ toolset?: TToolset; // Custom toolset (default: OpenAIToolset)+ telemetryTransport?: BaseTelemetryTransport; // Custom telemetry transport+}++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ toolset: new OpenAIToolset(), // Optional: defaults to OpenAIToolset+});+```+## ToolsetsComposio SDK supports two types of toolsets, each with different modifier capabilities:@@ -19,8 +47,6 @@ Composio SDK supports two types of toolsets, each with different modifier capabiThese toolsets only support schema modifiers for transforming tool schemas. They are suitable for simple integrations like OpenAI, Anthropic, etc.-Schema modifiers allow you to transform tool schemas using the `TransformToolSchemaModifier` function:-```typescriptimport { Composio } from '@composio/core';import { OpenAIToolset } from '@composio/openai-toolset';@@ -32,8 +58,8 @@ const composio = new Composio({});// Get a tool with schema modifiers-const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {- schema: (toolSlug: string, tool: Tool) => ({+const tool = await composio.getToolBySlug('user123', 'HACKERNEWS_SEARCH_POSTS', {+ modifyToolSchema: (toolSlug: string, tool: Tool) => ({...tool,description: 'Search HackerNews posts with improved description',inputParameters: {@@ -51,7 +77,7 @@ const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {These toolsets support full modifier capabilities, making them suitable for complex integrations like Vercel, Langchain, etc. They support:-1. **Schema Modifiers**: Transform tool schemas using `TransformToolSchemaModifier`+1. **Schema Modifiers**: Transform tool schemas using `modifyToolSchema`2. **Execution Modifiers**: Transform tool execution behavior- `beforeToolExecute`: Transform input parameters before execution- `afterToolExecute`: Transform output after execution@@ -69,9 +95,9 @@ const composio = new Composio({});// Get a tool with full modifier support-const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {+const tool = await composio.getToolBySlug('user123', 'HACKERNEWS_SEARCH_POSTS', {// Schema modifier- schema: (toolSlug: string, tool: Tool) => ({+ modifyToolSchema: (toolSlug: string, tool: Tool) => ({...tool,description: 'Search HackerNews posts with improved description',inputParameters: {@@ -101,125 +127,56 @@ const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {},}),});--// Execute the tool with execution modifiers-const result = await composio.toolset.executeTool(- tool,- {- arguments: { query: 'AI', limit: 20 },- },- {- beforeToolExecute: (toolSlug: string, params: ToolExecuteParams) => ({- ...params,- arguments: {- ...params.arguments,- limit: Math.min((params.arguments?.limit as number) || 10, 100),- },- }),- afterToolExecute: (toolSlug: string, response: ToolExecuteResponse) => ({- ...response,- data: {- ...response.data,- posts: (response.data?.posts as any[]).map(post => ({- ...post,- url: post.url || `https://news.ycombinator.com/item?id=${post.id}`,- })),- },- }),- }-);```-## Usage+## Creating a Custom Toolset-@composio/core ships with OpenAI toolset by default. You can directly use the tools from composio in `openai` methods.+To create a new toolset, extend either `BaseNonAgenticToolset` or `BaseAgenticToolset` from `@composio/core`:```typescript-import { Composio } from '@composio/core';-import type { Tool } from '@composio/core';--// By default composio ships with OpenAI toolset (non-agentic)-const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,-});--// Get a tool with schema modifiers-const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {- schema: (toolSlug: string, tool: Tool) => ({- ...tool,- description: 'Search HackerNews posts with improved description',- inputParameters: {- ...tool.inputParameters,- limit: {- type: 'number',- description: 'Maximum number of posts to return',- },- },- }),-});-console.log(tool);-```--For more examples, please check the `/examples` directory.--## Using with a different toolset--To use a different toolset, please install the recommended toolset packages.--```typescript-import { Composio } from '@composio/core';-import { VercelToolset } from '@composio/vercel-toolset'; // Agentic toolset-// or-import { OpenAIToolset } from '@composio/openai-toolset'; // Non-agentic toolset-import type { Tool, ToolExecuteParams, ToolExecuteResponse } from '@composio/core';--const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- toolset: new VercelToolset(), // or new OpenAIToolset()-});+import { BaseNonAgenticToolset } from '@composio/core';+import type { Tool, ToolListParams, ToolOptions } from '@composio/core';++interface CustomTool {+ name: string;+ // ... custom tool properties+}++export class CustomToolset extends BaseNonAgenticToolset<Array<CustomTool>, CustomTool> {+ readonly FILE_NAME: string = 'custom/toolset.ts';++ wrapTool = (tool: Tool): CustomTool => {+ return {+ name: tool.name,+ // ... map other properties+ };+ };++ async getTools(+ userId: string,+ params?: ToolListParams,+ options?: ToolOptions+ ): Promise<Array<CustomTool>> {+ const tools = await this.getComposio().tools.getComposioTools(+ userId,+ params,+ options?.modifyToolSchema+ );+ return tools?.map(tool => this.wrapTool(tool)) ?? [];+ }-// Get a tool with appropriate modifiers based on toolset type-const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {- // Schema modifiers (supported by both types)- schema: (toolSlug: string, tool: Tool) => ({- ...tool,- description: 'Search HackerNews posts with improved description',- inputParameters: {- ...tool.inputParameters,- limit: {- type: 'number',- description: 'Maximum number of posts to return',- },- },- }),- // Execution modifiers (only for agentic toolsets)- ...(composio.toolset instanceof VercelToolset && {- beforeToolExecute: (toolSlug: string, params: ToolExecuteParams) => ({- ...params,- arguments: {- ...params.arguments,- limit: Math.min((params.arguments?.limit as number) || 10, 100),- },- }),- afterToolExecute: (toolSlug: string, response: ToolExecuteResponse) => ({- ...response,- data: {- ...response.data,- posts: (response.data?.posts as any[]).map(post => ({- ...post,- url: post.url || `https://news.ycombinator.com/item?id=${post.id}`,- })),- },- }),- }),-});+ async getToolBySlug(userId: string, slug: string, options?: ToolOptions): Promise<CustomTool> {+ const tool = await this.getComposio().tools.getComposioToolBySlug(+ userId,+ slug,+ options?.modifyToolSchema+ );+ return this.wrapTool(tool);+ }+}```-## Creating a new toolset--To create a new Toolset, you need to extend either `BaseNonAgenticToolset` or `BaseAgenticToolset` from `@composio/core` and implement the required methods.--To quickly create a toolset project, execute the following command from the root of the project:+To quickly create a toolset project, use the provided script:```bash# Create a non-agentic toolset (default)@@ -229,40 +186,22 @@ pnpm run create-toolset <your-toolset-name>pnpm run create-toolset <your-toolset-name> --agentic```-For example:--```bash-# Create a non-agentic toolset for Anthropic-pnpm run create-toolset anthropic+## Environment Variables-# Create an agentic toolset for Langchain-pnpm run create-toolset langchain --agentic-```+- `COMPOSIO_API_KEY`: Your Composio API key+- `COMPOSIO_BASE_URL`: Custom API base URL+- `COMPOSIO_LOGGING_LEVEL`: Logging level (silent, error, warn, info, debug)+- `DEVELOPMENT`: Development mode flag+- `CI`: CI environment flag-The script will create a new toolset with the following structure:+## Contributing-```-<toolset-name>/-├── src/-│ └── index.ts # Toolset implementation-├── package.json # Package configuration-├── tsconfig.json # TypeScript configuration-├── tsup.config.ts # Build configuration-└── README.md # Toolset documentation-```+We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.-## Internal+## License-What's not included from @composio/client+ISC License-- [x] Org/Project Mangement with API Keys-- [x] Trigger Subscriptions-- [ ] Zod Schemas for type checking `Ideally strike a minimal balance, since backend has most`-- [ ] Action Execution-- [ ] CLI `Do we need this in the core SDK?`-- [ ] MCP `Not required as this is not necessary`-- [ ] Team Members-- [ ] File uploads/user files-- [ ] Tests+## Support-These models can be still be accessed via the SDK explicitly by using the `@composio/client`.+For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).diff --git a/packages/core/package.json b/packages/core/package.jsonindex e743c4bd8..80d109e5e 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -37,6 +37,7 @@"@composio/client": "0.1.0-alpha.9","openai": "^4.94.0","pusher-js": "^8.4.0",+ "uuid": "^11.1.0","zod": "^3.24.2","zod-to-json-schema": "^3.24.5"}diff --git a/packages/core/src/composio.ts b/packages/core/src/composio.tsindex d4aec16bc..bfe599366 100644--- a/packages/core/src/composio.ts+++ b/packages/core/src/composio.ts@@ -16,6 +16,7 @@ import { IS_DEVELOPMENT_OR_CI } from './utils/constants';import { checkForLatestVersionFromNPM } from './utils/version';import { OpenAIToolset } from './toolset/OpenAIToolset';import { version } from '../package.json';+import { getRandomUUID } from './utils/uuid';export type ComposioConfig<TToolset extends BaseComposioToolset<unknown, unknown> = OpenAIToolset> ={@@ -24,8 +25,6 @@ export type ComposioConfig<TToolset extends BaseComposioToolset<unknown, unknownallowTracking?: boolean;allowTracing?: boolean;toolset?: TToolset;- userId?: string;- connectedAccountIds?: Record<string, string>;telemetryTransport?: BaseTelemetryTransport;};@@ -49,12 +48,6 @@ export class Composio<TToolset extends BaseComposioToolset<unknown, unknown> = Oprivate telemetry: Telemetry | undefined;- /**- * Context variables for the Composio SDK.- */- userId?: string;- connectedAccountIds?: Record<string, string>;-/*** Core models for Composio.*/@@ -85,11 +78,6 @@ export class Composio<TToolset extends BaseComposioToolset<unknown, unknown> = Oif (IS_DEVELOPMENT_OR_CI) {logger.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);}- if (config.userId && config.connectedAccountIds) {- logger.warn(- 'When both userId and connectedAccountIds are provided, preference will be given to connectedAccountIds'- );- }/*** Initialize the Composio SDK client.@@ -109,12 +97,6 @@ export class Composio<TToolset extends BaseComposioToolset<unknown, unknown> = OallowTracking: config.allowTracking ?? true,};- /**- * Set the context variables for the Composio SDK.- */- this.userId = config.userId ?? this.DEFAULT_USER_ID; // entity id of the user- this.connectedAccountIds = config.connectedAccountIds ?? {}; // app name -> account id of the connected account-/*** Set the default toolset, if not provided by the user.*/@@ -142,9 +124,9 @@ export class Composio<TToolset extends BaseComposioToolset<unknown, unknown> = ObaseUrl: baseURLParsed ?? '',frameworkRuntime: 'node',source: 'node', // @TODO: get the source- sessionId: this.userId,composioVersion: version,isBrowser: typeof window !== 'undefined',+ sessionId: getRandomUUID(), // @TODO: get the session id},config.telemetryTransport);@@ -173,15 +155,6 @@ export class Composio<TToolset extends BaseComposioToolset<unknown, unknown> = Othis.telemetry.instrumentTelemetry(this.toolset);}- /**- * Get the connected account id for the given app name.- * @param appName - The name of the app.- * @returns {string | undefined} The connected account id for the given app name.- */- getConnectedAccountId(appName: string): string | undefined {- return this.connectedAccountIds?.[appName];- }-/*** Get the Composio SDK client.* @returns {ComposioClient} The Composio API client.diff --git a/packages/core/src/utils/uuid.ts b/packages/core/src/utils/uuid.tsnew file mode 100644index 000000000..c302f70f3--- /dev/null+++ b/packages/core/src/utils/uuid.ts@@ -0,0 +1,5 @@+import { v4 as uuidv4 } from 'uuid';++export function getRandomUUID(): string {+ return uuidv4();+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 89a2eb5b4..e15d97f9d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -123,6 +123,9 @@ importers:pusher-js:specifier: ^8.4.0version: 8.4.0+ uuid:+ specifier: ^11.1.0+ version: 11.1.0zod:specifier: ^3.24.2version: 3.24.2@@ -1966,6 +1969,10 @@ packages:resolution: {integrity: sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==}hasBin: true+ resolution: {integrity: sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==}+ hasBin: true+resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}engines: {node: '>= 14'}@@ -3799,6 +3806,8 @@ snapshots:+ [email protected]: {}+