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
Create extensive docs
haxzie6dc0c93c3fc7
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 000000000..99a067638--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,359 @@+# Contributing to Composio SDK++Thank you for your interest in contributing to Composio SDK! This document provides guidelines and instructions for contributing to the project.++## Table of Contents++- [Development Setup](#development-setup)+- [Project Structure](#project-structure)+- [Coding Standards](#coding-standards)+- [Documentation Requirements](#documentation-requirements)+- [Pull Request Process](#pull-request-process)+- [Creating New Providers](#creating-new-providers)+- [Testing Guidelines](#testing-guidelines)+- [Release Process](#release-process)++## Development Setup++### Prerequisites++- Node.js (Latest LTS version recommended)+- [pnpm](https://pnpm.io/) (v10.8.0 or later)+- [bun](https://bun.sh) for productivity (optional)++### Getting Started++1. Fork and clone the repository:++ ```bash+ git clone https://github.com/YOUR_USERNAME/sdk-v3.git+ cd sdk-v3+ ```++2. Install dependencies:++ ```bash+ pnpm install+ ```++3. Build the project:++ ```bash+ pnpm build+ ```++4. Run tests:+ ```bash+ pnpm test+ ```++### Development Commands++```bash+# Lint code+pnpm lint++# Fix linting issues+pnpm lint:fix++# Format code+pnpm format++# Create a new provider+pnpm create:provider <provider-name> [--agentic]++# Create a new example+pnpm create:example <example-name>++# Check peer dependencies+pnpm check:peer-deps++# Update peer dependencies+pnpm update:peer-deps+```++## Project Structure++```+composio/+├── packages/ # Main packages directory+│ ├── core/ # Core SDK package+│ └── providers/ # Provider implementations+├── examples/ # Example implementations+├── docs/ # Documentation+├── scripts/ # Development and build scripts+└── .github/ # GitHub configuration+```++## Coding Standards++### File Headers++Every source file must include a header comment with:++```typescript+/**+ * @file Description of what this file does/contains+ * @module path/to/module+ * @description Detailed description of the file's purpose+ *+ * @author Original Author <[email protected]>+ * @contributors+ * - Contributor Name <[email protected]>+ *+ * @copyright Composio 2024+ * @license ISC+ *+ * @see {@link https://related.documentation.link}+ * @see {@link https://another.related.link}+ */+```++### Function Documentation++Every user-facing function must include:++1. TSDoc documentation+2. Example usage+3. Parameter and return type descriptions+4. Error cases++Example:++````typescript+/**+ * Executes a tool with the given parameters.+ *+ * @description+ * This function executes a tool with the provided parameters and returns the result.+ * It handles authentication, parameter validation, and error cases automatically.+ *+ * @example+ * ```typescript+ * const result = await executeTool('GMAIL_SEND_EMAIL', {+ * userId: 'user123',+ * arguments: {+ * to: '[email protected]',+ * subject: 'Hello',+ * body: 'Message content'+ * }+ * });+ * ```+ *+ * @param {string} toolId - The unique identifier of the tool to execute+ * @param {ExecuteToolOptions} options - Tool execution options+ * @returns {Promise<ExecuteToolResult>} The result of the tool execution+ *+ * @throws {ToolNotFoundError} When the specified tool doesn't exist+ * @throws {ValidationError} When required parameters are missing+ * @throws {AuthenticationError} When authentication fails+ *+ * @see {@link https://docs.composio.dev/api/tools#execute}+ */+export async function executeTool(+ toolId: string,+ options: ExecuteToolOptions+): Promise<ExecuteToolResult> {+ // Implementation+}+````++### Code Style++1. Use TypeScript for all new code+2. Follow the existing code style in the repository+3. Use ESLint and Prettier for code formatting+4. Use meaningful variable and function names+5. Keep functions small and focused+6. Write unit tests for all new code+7. Use async/await instead of Promises+8. Use named exports instead of default exports+9. Use const assertions for constants+10. Use type assertions sparingly++### Error Handling++1. Use custom error classes+2. Include meaningful error messages+3. Document error cases in TSDoc+4. Include error codes for API errors+5. Log errors appropriately++Example:++```typescript+/**+ * Custom error for tool execution failures.+ */+export class ToolExecutionError extends ComposioError {+ constructor(+ message: string,+ public readonly toolId: string,+ public readonly cause?: Error+ ) {+ super(message, 'TOOL_EXECUTION_ERROR');+ this.name = 'ToolExecutionError';+ }+}+```++## Documentation Requirements++### Package Documentation++Each package must include:++1. README.md with:++ - Package description+ - Installation instructions+ - Usage examples+ - API reference+ - Environment variables+ - Contributing guidelines++2. API documentation:++ - TSDoc for all public APIs+ - Example code snippets+ - Error handling documentation+ - Type definitions++3. Example implementations:+ - Basic usage example+ - Advanced usage examples+ - Integration examples++### Provider Documentation++Provider packages must additionally include:++1. Provider-specific setup instructions+2. Authentication requirements+3. Supported features+4. Limitations and constraints+5. Integration examples+6. Streaming support details+7. Error handling examples++## Pull Request Process++1. Create a new branch for your changes:++ ```bash+ git checkout -b feature/your-feature-name+ ```++2. Make your changes following the coding standards++3. Add tests for new functionality++4. Update documentation as needed++5. Create a changeset:++ ```bash+ pnpm changeset+ ```++6. Push your changes and create a pull request++7. Wait for review and address any feedback++## Creating New Providers++1. Use the provider creation script:++ ```bash+ pnpm create:provider my-provider [--agentic]+ ```++2. Implement required methods:++ - For non-agentic providers: `wrapTool` and `wrapTools`, and helper functions+ - For agentic providers: `wrapTool`, `wrapTools`, and execution handlers++3. Add comprehensive tests++4. Add provider documentation++5. Create example implementations++## Testing Guidelines++1. Write unit tests for all new code+2. Include integration tests for providers+3. Test error cases+4. Test edge cases+5. Use mocks appropriately+6. Test streaming functionality+7. Test with different Node.js versions++Example test:++```typescript+describe('ToolExecution', () => {+ it('should execute a tool successfully', async () => {+ const result = await executeTool('TEST_TOOL', {+ userId: 'user123',+ arguments: { test: true },+ });+ expect(result.successful).toBe(true);+ });++ it('should handle errors appropriately', async () => {+ await expect(+ executeTool('INVALID_TOOL', {+ userId: 'user123',+ arguments: {},+ })+ ).rejects.toThrow(ToolNotFoundError);+ });+});+```++## Release Process++1. Create a release branch:++ ```bash+ git checkout -b release/v1.2.3+ ```++2. Update version numbers:++ ```bash+ pnpm changeset version+ ```++3. Update CHANGELOG.md++4. Create a release commit:++ ```bash+ git commit -am "Release v1.2.3"+ ```++5. Create a pull request for the release++6. After approval, merge and tag:++ ```bash+ git tag v1.2.3+ git push origin v1.2.3+ ```++7. Publish to npm:+ ```bash+ pnpm changeset publish+ ```++## Questions and Support++- Join our [Discord Community](https://discord.gg/composio)+- Check our [Documentation](https://docs.composio.dev)+- File issues on [GitHub](https://github.com/ComposioHQ/sdk-v3/issues)++## License++By contributing to Composio SDK, you agree that your contributions will be licensed under the ISC License.diff --git a/README.md b/README.mdindex cc64699b7..4367a9dd9 100644--- a/README.md+++ b/README.md@@ -18,6 +18,7 @@ The SDK is thoroughly documented in the [docs](./docs) directory:- [Overview](./docs/overview.md) - Introduction and key concepts- [Getting Started](./docs/getting-started.md) - Quick start guide- [Core Concepts](./docs/core-concepts.md) - Fundamental SDK concepts+- [Configuration](./docs/internal/configuration.md) - Environment variables and SDK configuration### API Reference@@ -42,6 +43,13 @@ The SDK is thoroughly documented in the [docs](./docs) directory:- [Telemetry](./docs/advanced/telemetry.md) - SDK usage tracking- [Custom Providers](./docs/advanced/custom-providers.md) - Detailed provider guide+### Internal Documentation++For SDK maintainers and contributors:++- [Configuration and Environment Variables](./docs/internal/configuration.md) - Detailed guide on SDK configuration+- [Triggers Implementation](./docs/internal/triggers.md) - Internal workings of the trigger system+## Installation```bashdiff --git a/docs/README.md b/docs/README.mdindex 8308bdccf..a6ec02ad9 100644--- a/docs/README.md+++ b/docs/README.md@@ -12,6 +12,7 @@ Composio SDK is a powerful toolkit that enables you to integrate third-party too- [Providers](#providers)- [Examples](#examples)- [Advanced Topics](#advanced-topics)+- [Internal Documentation](#internal-documentation)## Overview@@ -92,8 +93,18 @@ The complete API reference documentation is available here:Composio SDK comes with built-in support for different providers:-- [OpenAI Provider](./providers/openai.md)-- [Custom Providers](./providers/custom.md)+### Non-Agentic Providers++- [OpenAI Provider](../packages/providers/openai/README.md) - OpenAI integration with GPT-4, GPT-3.5, etc.+- [Anthropic Provider](../packages/providers/anthropic/README.md) - Anthropic Claude integration+- [Google Provider](../packages/providers/google/README.md) - Google Gemini integration+- [Cloudflare Provider](../packages/providers/cloudflare/README.md) - Cloudflare Workers AI integration++### Agentic Providers++- [LangChain Provider](../packages/providers/langchain/README.md) - LangChain integration with LCEL support+- [Mastra Provider](../packages/providers/mastra/README.md) - Agentic provider for autonomous behavior+- [Vercel Provider](../packages/providers/vercel/README.md) - Vercel AI SDK integration## Examples@@ -103,6 +114,7 @@ Check out our [examples directory](../examples) for complete code samples:- [OpenAI Integration](../examples/openai)- [LangChain Integration](../examples/langchain)- [Toolkits](../examples/toolkits)+- [Triggers](../examples/triggers)- [Modifiers](../examples/modifiers)## Advanced Topics@@ -111,3 +123,10 @@ Check out our [examples directory](../examples) for complete code samples:- [Telemetry](./advanced/telemetry.md)- [Custom Providers](./advanced/custom-providers.md)- [Modifiers](./advanced/modifiers.md)++## Internal Documentation++For SDK maintainers and contributors:++- [Configuration and Environment Variables](./internal/configuration.md) - Detailed guide on SDK configuration+- [Triggers Implementation](./internal/triggers.md) - Internal workings of the trigger systemdiff --git a/docs/api/triggers.md b/docs/api/triggers.mdnew file mode 100644index 000000000..4a75bd08a--- /dev/null+++ b/docs/api/triggers.md@@ -0,0 +1,140 @@+# Triggers++The Triggers API allows you to manage and subscribe to real-time events from your connected accounts. This guide explains how to work with triggers using the Composio SDK.++## Overview++Triggers are real-time events that occur in your connected accounts. The SDK provides methods to:++- List active triggers+- Create new trigger instances+- Update existing triggers+- Enable/disable triggers+- Subscribe to real-time trigger events+- Manage trigger types++## Methods++### List Active Triggers++Fetch a list of all active triggers with optional filtering:++```typescript+const triggers = await composio.triggers.listActive({+ authConfigIds: ['auth-config-id'],+ connectedAccountIds: ['connected-account-id'],+ limit: 10,+ page: 1,+ showDisabled: false,+ triggerIds: ['trigger-id'],+ triggerNames: ['trigger-name'],+});+```++### Create Trigger Instance++Create a new trigger instance for a specific trigger type:++```typescript+const trigger = await composio.triggers.create('trigger-slug', {+ connectedAccountId: 'connected-account-id',+ triggerConfig: {+ // Trigger specific configuration+ },+});+```++### Update Trigger Instance++Update an existing trigger instance:++```typescript+const updatedTrigger = await composio.triggers.update('trigger-id', {+ // Updated configuration+});+```++### Enable/Disable Triggers++Control trigger activation state:++```typescript+// Disable a trigger+await composio.triggers.disable('trigger-id');++// Enable a trigger+await composio.triggers.enable('trigger-id');+```++### Real-time Trigger Subscription++Subscribe to real-time trigger events with optional filtering:++```typescript+composio.triggers.subscribe(+ triggerData => {+ console.log('Received trigger:', triggerData);+ },+ {+ toolkits: ['toolkit-name'],+ triggerId: 'specific-trigger-id',+ connectedAccountId: 'connected-account-id',+ triggerSlug: ['trigger-type'],+ triggerData: 'custom-data',+ userId: 'user-id',+ }+);+```++#### Trigger Payload Format++When you receive a trigger event, the payload will have the following structure:++```typescript+interface IncomingTriggerPayload {+ id: string; // Unique trigger instance ID+ triggerSlug: string; // Type of trigger+ toolkitSlug: string; // Associated toolkit+ userId: string; // User ID associated with the trigger+ payload: unknown; // Processed trigger payload+ originalPayload: unknown; // Raw trigger payload+ metadata: {+ id: string;+ triggerConfig: unknown; // Trigger configuration+ triggerSlug: string;+ toolkitSlug: string;+ triggerData: string;+ connectedAccount: {+ id: string; // Connected account nano ID+ uuid: string; // Connected account UUID+ authConfigId: string; // Auth config nano ID+ authConfigUUID: string; // Auth config UUID+ userId: string; // User ID+ status: string; // Connection status+ };+ };+}+```++### Unsubscribe from Triggers++Stop receiving trigger events:++```typescript+await composio.triggers.unsubscribe();+```++### Manage Trigger Types++List and retrieve available trigger types:++```typescript+// List all trigger types+const triggerTypes = await composio.triggers.listTypes();++// Get details of a specific trigger type+const triggerType = await composio.triggers.getType('trigger-slug');++// Get enum of all available triggers+const triggerEnum = await composio.triggers.listEnum();+```diff --git a/docs/internal/configuration.md b/docs/internal/configuration.mdnew file mode 100644index 000000000..7e40c9777--- /dev/null+++ b/docs/internal/configuration.md@@ -0,0 +1,137 @@+# Configuration++This guide explains how to configure the Composio SDK using environment variables and initialization options.++## Environment Variables++The SDK supports several environment variables for configuration:++### Core Configuration++- `COMPOSIO_API_KEY`: Your Composio API key++ - Required for authentication+ - Can be obtained from [Composio Dashboard](https://app.composio.dev)+ - Can also be set via SDK initialization or user config file++- `COMPOSIO_BASE_URL`: Custom API base URL+ - Optional+ - Default: `https://backend.composio.dev`+ - Use this to point the SDK to a different API endpoint++### Logging Configuration++- `COMPOSIO_LOG_LEVEL`: Controls the verbosity of SDK logs+ - Values: `silent`, `error`, `warn`, `info`, `debug`+ - Default: `info`+ - Hierarchy (from highest to lowest priority):+ - `silent`: No logs+ - `error`: Only critical errors+ - `warn`: Warnings and errors+ - `info`: General information, warnings, and errors+ - `debug`: Detailed debugging information++### Development and Testing++- `NODE_ENV`: Environment mode++ - Values: `development`, `production`, `test`+ - Affects:+ - Telemetry collection (disabled in development/test)+ - Error handling verbosity+ - Version check notifications++- `DEVELOPMENT`: Development mode flag++ - Set to any value to enable development mode+ - Enables additional debugging features+ - Shows more verbose logs++- `CI`: CI environment flag+ - Set to any value to indicate CI environment+ - Affects certain behaviors like version checks++### Telemetry++- `COMPOSIO_DISABLE_TELEMETRY`: Disable telemetry collection+ - Set to `"true"` to disable+ - Default: `"false"`+ - Alternative to `allowTracking` initialization option++## SDK Initialization Options++When initializing the SDK, you can provide configuration through the constructor:++```typescript+const composio = new Composio({+ apiKey: 'your-api-key', // Override COMPOSIO_API_KEY+ baseURL: 'custom-url', // Override COMPOSIO_BASE_URL+ allowTracking: false, // Disable telemetry+ allowTracing: true, // Enable tracing+ provider: new CustomProvider(), // Custom provider+ telemetryTransport: customTransport, // Custom telemetry transport+});+```++### Configuration Priority++When multiple configuration sources are present, the SDK follows this priority order:++1. Constructor parameters+2. Environment variables+3. User config file+4. Default values++## Examples++### Development Setup++```bash+# Development environment with debug logging+export NODE_ENV=development+export COMPOSIO_LOG_LEVEL=debug+export COMPOSIO_API_KEY=your-api-key+```++### Production Setup++```bash+# Production environment with minimal logging+export NODE_ENV=production+export COMPOSIO_LOG_LEVEL=error+export COMPOSIO_API_KEY=your-api-key+```++### Testing Setup++```bash+# Test environment with telemetry disabled+export NODE_ENV=test+export COMPOSIO_DISABLE_TELEMETRY=true+export COMPOSIO_API_KEY=your-test-api-key+```++## Best Practices++1. **Environment-specific Configuration**++ - Use different log levels for different environments+ - Enable detailed logging in development+ - Use minimal logging in production++2. **Security**++ - Never commit API keys to version control+ - Use environment variables or secure secrets management+ - Consider using different API keys for different environments++3. **Telemetry**++ - Enable telemetry in production for better support+ - Disable telemetry in development and testing+ - Use custom telemetry transport for specific needs++4. **Error Handling**+ - Set appropriate log levels for error tracking+ - Use debug level during development+ - Use error or warn level in productiondiff --git a/docs/internal/triggers.md b/docs/internal/triggers.mdnew file mode 100644index 000000000..d9bb14f1b--- /dev/null+++ b/docs/internal/triggers.md@@ -0,0 +1,101 @@+# Trigger System Implementation++This document explains the internal implementation of the trigger system in the Composio SDK.++## Architecture Overview++The trigger system is built on top of Pusher for real-time communication. The implementation consists of two main components:++1. The Triggers class (`packages/core/src/models/Triggers.ts`)+2. The PusherService class (`packages/core/src/services/pusher/Pusher.ts`)++## Real-time Communication++### Pusher Integration++The SDK uses Pusher as the underlying real-time communication infrastructure. When a client subscribes to triggers, the following process occurs:++1. The SDK initializes a PusherService instance+2. The service connects to Pusher using client credentials+3. A channel subscription is established for the client's triggers+4. Incoming messages are processed and filtered based on user-defined criteria++### Message Flow++```mermaid+sequenceDiagram+ participant Client+ participant SDK+ participant Pusher+ participant ComposioAPI++ Client->>SDK: subscribe(callback, filters)+ SDK->>ComposioAPI: Authenticate Pusher connection+ ComposioAPI-->>SDK: Connection credentials+ SDK->>Pusher: Connect & Subscribe to channel+ Pusher-->>SDK: Connection established+ loop Real-time Events+ Pusher->>SDK: Trigger event+ SDK->>SDK: Apply filters+ SDK->>Client: Filtered event callback+ end+```++## API Endpoints++The SDK interacts with the following Composio API endpoints for trigger management:++### Trigger Instance Management++- `GET /api/v3/trigger_instances/active` - List active triggers+- `POST /api/v3/trigger_instances/{slug}` - Create/update trigger instance+- `PATCH /api/v3/trigger_instances/manage/{id}` - Update trigger instance+- `DELETE /api/v3/trigger_instances/manage/{id}` - Delete trigger instance++### Trigger Types++- `GET /api/v3/triggers/types` - List trigger types+- `GET /api/v3/triggers/types/{slug}` - Get trigger type details+- `GET /api/v3/triggers/types/enum` - Get trigger type enums++### Pusher Authentication++- `POST /api/v3/pusher/auth` - Authenticate Pusher connection++## Data Processing++When a trigger event is received through Pusher, the SDK:++1. Parses the raw event data+2. Validates it against the `IncomingTriggerPayloadSchema`+3. Applies user-defined filters+4. Delivers the processed event to the user's callback++### Filter Processing++The SDK supports filtering triggers based on:++- Toolkit names+- Trigger IDs+- Connected Account IDs+- Trigger slugs+- Trigger data+- User IDs++Filters are applied in a compound manner - all specified filters must match for an event to be delivered.++## Error Handling++The SDK implements robust error handling:++- Schema validation for all incoming and outgoing data+- Connection error recovery+- Callback error isolation (errors in user callbacks don't affect the subscription)+- Automatic reconnection on connection loss++## Security Considerations++- All Pusher communications are authenticated+- API credentials are never exposed to the client+- Each client only receives events they are authorized to see+- Connection credentials are short-lived and rotated regularlydiff --git a/examples/triggers/src/index.ts b/examples/triggers/src/index.tsindex dfdbaad27..b51d8dc25 100644--- a/examples/triggers/src/index.ts+++ b/examples/triggers/src/index.ts@@ -37,7 +37,9 @@ async function main() {console.log(`✅ Found ${tools.length} tools`);// TODO: Add your example implementation here- console.log('📝 Implement your triggers logic here!');+ console.log(+ '📝 Go to https://app.composio.dev to create an app and add a trigger, Once you have an incoming trigger, you will see the events'+ );composio.triggers.subscribe(data => {console.log('🔔 Trigger received:', data);diff --git a/packages/providers/anthropic/README.md b/packages/providers/anthropic/README.mdindex 697cdec1c..e98730f1a 100644--- a/packages/providers/anthropic/README.md+++ b/packages/providers/anthropic/README.md@@ -9,6 +9,7 @@ Non-Agentic Provider for Anthropic in Composio SDK.- **Tool Execution**: Execute tools with proper parameter handling and response formatting- **Caching Support**: Optional tool caching for improved performance- **Modifier Support**: Support for execution modifiers to transform tool inputs and outputs+- **Streaming Support**: First-class support for streaming responses## Installation@@ -20,6 +21,17 @@ yarn add @composio/anthropicpnpm add @composio/anthropic```+## Environment Variables++Required environment variables:++- `COMPOSIO_API_KEY`: Your Composio API key+- `ANTHROPIC_API_KEY`: Your Anthropic API key++Optional environment variables:++- `ANTHROPIC_API_URL`: Custom API base URL (defaults to Anthropic's API)+## Quick Start```typescript@@ -40,13 +52,24 @@ const tools = await composio.tools.get('user123', {});```-## Usage Examples+## Examples++Check out our complete example implementations:++- [Basic Anthropic Integration](../../examples/anthropic/src/index.ts)+- [Streaming Example](../../examples/anthropic/src/streaming.ts)### Basic Example```typescriptimport { Composio } from '@composio/core';import { AnthropicProvider } from '@composio/anthropic';+import Anthropic from '@anthropic-ai/sdk';++// Initialize Anthropic+const anthropic = new Anthropic({+ apiKey: process.env.ANTHROPIC_API_KEY,+});// Initialize Composioconst composio = new Composio({@@ -59,31 +82,93 @@ const tools = await composio.tools.get('user123', {toolkits: ['gmail'],});-// Handle tool execution with modifiers-const modifiers = {- beforeExecute: params => {- // Transform tool parameters before execution- return params;- },- afterExecute: response => {- // Transform tool response after execution- return response;- },-};+// Create a message with tools+const message = await anthropic.messages.create({+ model: 'claude-3-sonnet-20240229',+ max_tokens: 1024,+ tools: tools,+ messages: [+ {+ role: 'user',+ content: 'Send an email to [email protected]',+ },+ ],+});-// Execute a tool with options-const result = await provider.executeTool(- 'tool-name',- {- userId: 'user123',- arguments: { input: 'value' },+// Handle tool calls+if (message.content[0].type === 'tool_calls') {+ const toolCall = message.content[0];+ const result = await composio.provider.executeToolCall('user123', toolCall, {connectedAccountId: 'account123',- customAuthParams: {- parameters: [{ name: 'token', value: 'abc123', in: 'header' }],+ });+ console.log('Tool execution result:', result);+}+```++### Streaming Example++```typescript+import { Composio } from '@composio/core';+import { AnthropicProvider } from '@composio/anthropic';+import Anthropic from '@anthropic-ai/sdk';++const anthropic = new Anthropic({+ apiKey: process.env.ANTHROPIC_API_KEY,+});++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ provider: new AnthropicProvider(),+});++const tools = await composio.tools.get('user123', {+ toolkits: ['gmail'],+});++const stream = await anthropic.messages.stream({+ model: 'claude-3-sonnet-20240229',+ max_tokens: 1024,+ tools: tools,+ messages: [+ {+ role: 'user',+ content: 'Send an email to [email protected]',+ },+ ],+});++for await (const messageChunk of stream) {+ if (messageChunk.type === 'content_block_delta' && messageChunk.delta.type === 'tool_calls') {+ const result = await composio.provider.executeToolCall('user123', messageChunk.delta, {+ connectedAccountId: 'account123',+ });+ console.log('Tool execution result:', result);+ } else {+ console.log('Message chunk:', messageChunk);+ }+}+```++## Provider Configuration++The Anthropic provider can be configured with various options:++```typescript+const provider = new AnthropicProvider({+ // Enable tool caching+ cacheTools: true,+ // Custom execution modifiers+ modifiers: {+ beforeExecute: params => {+ // Transform parameters before execution+ return params;+ },+ afterExecute: response => {+ // Transform response after execution+ return response;},},- modifiers-);+});```## API Referencediff --git a/packages/providers/google/README.md b/packages/providers/google/README.mdindex 872be7521..e4df28e9e 100644--- a/packages/providers/google/README.md+++ b/packages/providers/google/README.md@@ -9,17 +9,30 @@ Google GenAI Provider for Composio SDK.- **Type Safety**: Full TypeScript support with proper type definitions- **Execution Modifiers**: Support for transforming tool inputs and outputs- **Flexible Authentication**: Support for custom authentication parameters+- **Streaming Support**: First-class support for streaming responses## Installation```bash-npm install @composio/google @google/genai+npm install @composio/core @composio/google @google/genai# or-yarn add @composio/google @google/genai+yarn add @composio/core @composio/google @google/genai# or-pnpm add @composio/google @google/genai+pnpm add @composio/core @composio/google @google/genai```+## Environment Variables++Required environment variables:++- `COMPOSIO_API_KEY`: Your Composio API key+- `GEMINI_API_KEY`: Your Google AI API key++Optional environment variables:++- `GOOGLE_PROJECT_ID`: Your Google Cloud project ID (for custom deployments)+- `GOOGLE_LOCATION`: Your Google Cloud location (for custom deployments)+## Quick Start```typescript@@ -43,70 +56,33 @@ const tools = await composio.tools.get('user123', {});```-## Usage Examples+## Examples-### Function Calling Example+Check out our complete example implementations:-```typescript-import { Composio } from '@composio/core';-import { GoogleProvider } from '@composio/google';-import { GoogleGenerativeAI } from '@google/genai';+- [Basic Google Integration](../../examples/google/src/index.ts)-// Initialize Google GenAI-const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);+## Provider Configuration-// Initialize Composio-const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- provider: new GoogleProvider(),-});--// Handle tool execution with modifiers-const modifiers = {- beforeExecute: params => {- // Transform tool parameters before execution- return params;- },- afterExecute: response => {- // Transform tool response after execution- return response;- },-};+The Google provider can be configured with various options:-// Execute a tool with options-const result = await provider.executeTool(- 'tool-name',- {- userId: 'user123',- arguments: { input: 'value' },- connectedAccountId: 'account123',- customAuthParams: {- parameters: [{ name: 'token', value: 'abc123', in: 'header' }],+```typescript+const provider = new GoogleProvider({+ // Custom project configuration+ projectId: 'your-project-id',+ location: 'your-location',+ // Custom execution modifiers+ modifiers: {+ beforeExecute: params => {+ // Transform parameters before execution+ return params;},- },- modifiers-);--// Handle function calls from Google GenAI-const functionCall = {- name: 'tool-name',- args: { param: 'value' },-};--const toolResult = await provider.executeToolCall(- 'user123',- functionCall,- {- connectedAccountId: 'account123',- customAuthParams: {- /* ... */+ afterExecute: response => {+ // Transform response after execution+ return response;},},- {- beforeExecute: params => params,- afterExecute: response => response,- }-);+});```## API Referencediff --git a/packages/providers/langchain/README.md b/packages/providers/langchain/README.mdindex 741a1777e..332efafbf 100644--- a/packages/providers/langchain/README.md+++ b/packages/providers/langchain/README.md@@ -14,13 +14,26 @@ The LangChain provider for Composio SDK, providing seamless integration with Lan## Installation```bash-npm install @composio/langchain+npm install @composio/core @composio/langchain @langchain/core @langchain/openai# or-yarn add @composio/langchain+yarn add @composio/core @composio/langchain @langchain/core @langchain/openai# or-pnpm add @composio/langchain+pnpm add @composio/core @composio/langchain @langchain/core @langchain/openai```+## Environment Variables++Required environment variables:++- `COMPOSIO_API_KEY`: Your Composio API key+- `OPENAI_API_KEY`: Your OpenAI API key (or other LLM provider's key)++Optional environment variables:++- `LANGCHAIN_TRACING_V2`: Enable LangChain tracing (set to "true")+- `LANGCHAIN_ENDPOINT`: Custom LangChain API endpoint+- `LANGCHAIN_API_KEY`: Your LangChain API key (for hosted services)+## Quick Start```typescript@@ -43,7 +56,14 @@ const tools = await composio.tools.get('user123', {const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');```-## Usage Examples+## Examples++Check out our complete example implementations:++- [Basic LangChain Integration](../../examples/langchain/src/index.ts)+- [LCEL Example](../../examples/langchain/src/lcel.ts)+- [RAG Example](../../examples/langchain/src/rag.ts)+- [Streaming Example](../../examples/langchain/src/streaming.ts)### Basic Chain with Streaming@@ -125,65 +145,31 @@ for await (const event of eventStream) {}```-### RAG Application Example+## Provider Configuration-```typescript-import { Composio } from '@composio/core';-import { LangChainProvider } from '@composio/langchain';-import { ChatPromptTemplate } from '@langchain/core/prompts';-import { StringOutputParser } from '@langchain/core/output_parsers';-import { MemoryVectorStore } from 'langchain/vectorstores/memory';-import { OpenAIEmbeddings } from '@langchain/openai';-import { ChatOpenAI } from '@langchain/openai';-import { RunnableSequence, RunnablePassthrough } from '@langchain/core/runnables';--const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- provider: new LangChainProvider(),-});+The LangChain provider can be configured with various options:-// Get tools for the chain-const tools = await composio.tools.get('user123', {- toolkits: ['gmail'],-});--// Setup vector store and retriever-const vectorstore = await MemoryVectorStore.fromTexts(- ['some text', 'more text'],- [{ id: 1 }, { id: 2 }],- new OpenAIEmbeddings()-);--const retriever = vectorstore.asRetriever();--// Create RAG chain-const template = `Answer the question based only on the following context:-{context}--Question: {question}`;--const prompt = ChatPromptTemplate.fromTemplate(template);-const model = new ChatOpenAI({- modelName: 'gpt-4',- streaming: true,-});--const chain = RunnableSequence.from([- {- context: retriever.pipe(formatDocs),- question: new RunnablePassthrough(),+```typescript+const provider = new LangChainProvider({+ // Default model configuration+ model: new ChatOpenAI({+ modelName: 'gpt-4',+ streaming: true,+ }),+ // Custom execution modifiers+ modifiers: {+ beforeExecute: params => {+ // Transform parameters before execution+ return params;+ },+ afterExecute: response => {+ // Transform response after execution+ return response;+ },},- prompt,- model,- new StringOutputParser(),-]);--// Stream the response-const stream = await chain.stream('What is the answer?');--for await (const chunk of stream) {- console.log(chunk);-}+ // Enable tracing+ tracing: true,+});```## API Referencediff --git a/packages/providers/mastra/README.md b/packages/providers/mastra/README.mdindex 281da39d7..8ae4e3bb2 100644--- a/packages/providers/mastra/README.md+++ b/packages/providers/mastra/README.md@@ -7,17 +7,32 @@ Agentic Provider for Mastra in Composio SDK.- **Full Modifier Support**: Support for both schema and execution modifiers- **Tool Execution**: Execute tools with proper parameter handling- **Type Safety**: Full TypeScript support with proper type definitions+- **Agentic Capabilities**: Full support for autonomous agent behavior+- **Streaming Support**: First-class support for streaming responses+- **Custom Execution**: Support for custom tool execution strategies## Installation```bash-npm install @composio/mastra+npm install @composio/core @composio/mastra# or-yarn add @composio/mastra+yarn add @composio/core @composio/mastra# or-pnpm add @composio/mastra+pnpm add @composio/core @composio/mastra```+## Environment Variables++Required environment variables:++- `COMPOSIO_API_KEY`: Your Composio API key+- `MASTRA_API_KEY`: Your Mastra API key++Optional environment variables:++- `MASTRA_API_URL`: Custom API base URL (defaults to Mastra's API)+- `MASTRA_DEBUG`: Enable debug logging (set to "true")+## Quick Start```typescript@@ -26,8 +41,10 @@ import { MastraProvider } from '@composio/mastra';// Initialize Composio with Mastra providerconst composio = new Composio({- apiKey: 'your-composio-api-key',- provider: new MastraProvider(),+ apiKey: process.env.COMPOSIO_API_KEY,+ provider: new MastraProvider({+ apiKey: process.env.MASTRA_API_KEY,+ }),});// Get available tools@@ -37,45 +54,91 @@ const tools = await composio.tools.get('user123', {});```-## Usage Examples+## Examples-### Basic Example+Check out our complete example implementations:-```typescript-import { Composio } from '@composio/core';-import { MastraProvider } from '@composio/mastra';+- [Basic Mastra Integration](../../examples/mastra/src/index.ts)-// Initialize Composio-const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- provider: new MastraProvider(),-});+## Provider Configuration-// Get tools-const tools = await composio.tools.get('user123', {- toolkits: ['gmail'],-});+The Mastra provider can be configured with various options:-// Use tools with Mastra-// Add your usage example here+```typescript+const provider = new MastraProvider({+ // API configuration+ apiKey: process.env.MASTRA_API_KEY,+ apiUrl: 'https://custom-api.mastra.ai',+ // Debug mode+ debug: true,+ // Custom execution modifiers+ modifiers: {+ beforeExecute: params => {+ // Transform parameters before execution+ return params;+ },+ afterExecute: response => {+ // Transform response after execution+ return response;+ },+ },+ // Custom tool execution strategy+ executionStrategy: {+ maxRetries: 3,+ retryDelay: 1000,+ timeout: 30000,+ },+});```## API Reference### MastraProvider Class-The `MastraProvider` class extends `BaseAgenticProvider` and provides mastra-specific functionality.+The `MastraProvider` class extends `BaseAgenticProvider` and provides Mastra-specific functionality.++#### Constructor++```typescript+new MastraProvider(options?: MastraProviderOptions)+```++Options:++- `apiKey`: Your Mastra API key+- `apiUrl`: Custom API base URL+- `debug`: Enable debug logging+- `modifiers`: Custom execution modifiers+- `executionStrategy`: Custom tool execution strategy#### Methods##### `wrapTool(tool: Tool, executeTool: ExecuteToolFn): MastraTool`-Wraps a tool in the mastra format.+Wraps a tool in the Mastra format.```typescriptconst tool = provider.wrapTool(composioTool, executeTool);```+##### `wrapTools(tools: Tool[], executeTool: ExecuteToolFn): MastraToolCollection`++Wraps multiple tools in the Mastra format.++```typescript+const tools = provider.wrapTools(composioTools, executeTool);+```++##### `executeToolCall(userId: string, toolCall: MastraToolCall, options?: ExecuteToolFnOptions): Promise<string>`++Executes a tool call from Mastra and returns the result.++```typescript+const result = await provider.executeToolCall('user123', toolCall, {+ connectedAccountId: 'account123',+});+```+## ContributingWe welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.diff --git a/packages/providers/openai/README.md b/packages/providers/openai/README.mdindex f14327aa2..921171428 100644--- a/packages/providers/openai/README.md+++ b/packages/providers/openai/README.md@@ -21,6 +21,18 @@ yarn add @composio/openaipnpm add @composio/openai```+## Environment Variables++Required environment variables:++- `COMPOSIO_API_KEY`: Your Composio API key+- `OPENAI_API_KEY`: Your OpenAI API key++Optional environment variables:++- `OPENAI_API_BASE`: Custom API base URL (for Azure OpenAI)+- `OPENAI_ORGANIZATION`: OpenAI organization ID+## Quick Start```typescript@@ -43,7 +55,14 @@ const tools = await composio.tools.get('user123', {const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');```-## Usage Examples+## Examples++Check out our complete example implementations:++- [Basic OpenAI Integration](../../examples/openai/src/index.ts)+- [Chat Completions Example](../../examples/openai/src/chat-completions.ts)+- [Assistants Example](../../examples/openai/src/assistants.ts)+- [Tools Example](../../examples/openai/src/tools.ts)### Basic Chat Completion with Streaming@@ -197,6 +216,25 @@ export async function POST(req: Request) {}```+## Provider Configuration++The OpenAI provider can be configured with various options:++```typescript+const provider = new OpenAIProvider({+ // Custom base URL for Azure OpenAI+ baseURL: 'https://your-azure-endpoint.openai.azure.com',+ // Organization ID+ organization: 'org-123',+ // Default model to use+ defaultModel: 'gpt-4',+ // Custom headers+ headers: {+ 'api-key': process.env.OPENAI_API_KEY,+ },+});+```+## API Reference### OpenAIProvider Classdiff --git a/packages/providers/vercel/README.md b/packages/providers/vercel/README.mdindex 423a7fc74..56a5a440f 100644--- a/packages/providers/vercel/README.md+++ b/packages/providers/vercel/README.md@@ -14,13 +14,25 @@ The Vercel AI SDK provider for Composio SDK, providing seamless integration with## Installation```bash-npm install @composio/vercel+npm install @composio/vercel ai# or-yarn add @composio/vercel+yarn add @composio/vercel ai# or-pnpm add @composio/vercel+pnpm add @composio/vercel ai```+## Environment Variables++Required environment variables:++- `COMPOSIO_API_KEY`: Your Composio API key++Optional environment variables (based on model choice):++- `OPENAI_API_KEY`: Your OpenAI API key (if using OpenAI)+- `ANTHROPIC_API_KEY`: Your Anthropic API key (if using Anthropic)+- `GEMINI_API_KEY`: Your Google AI API key (if using Gemini)+## Quick Start```typescript@@ -43,7 +55,11 @@ const tools = await composio.tools.get('user123', {const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');```-## Usage Examples+## Examples++Check out our complete example implementations:++- [Basic Vercel Integration](../../examples/vercel/src/index.ts)### Basic Chat Completion with Streaming@@ -140,42 +156,26 @@ export async function POST(req: Request) {}```-### Structured Output with Streaming--```typescript-import { Composio } from '@composio/core';-import { VercelProvider } from '@composio/vercel';-import { streamObject } from 'ai';--const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- provider: new VercelProvider(),-});+## Provider Configuration-// Example API route that returns structured data-export async function POST(req: Request) {- const { messages } = await req.json();- const tools = await composio.tools.get('user123', {- toolkits: ['gmail'],- });+The Vercel provider can be configured with various options:- const stream = streamObject({- model: openai('gpt-4'),- messages,- tools,- schema: {- type: 'object',- properties: {- name: { type: 'string' },- age: { type: 'number' },- interests: { type: 'array', items: { type: 'string' } },- },- required: ['name', 'age', 'interests'],+```typescript+const provider = new VercelProvider({+ // Default model configuration+ model: openai('gpt-4'),+ // Custom execution modifiers+ modifiers: {+ beforeExecute: params => {+ // Transform parameters before execution+ return params;},- });-- return stream.toDataStreamResponse();-}+ afterExecute: response => {+ // Transform response after execution+ return response;+ },+ },+});```## API Reference