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
feat: Add Anthropic provider implementation with tests and example
Devin AIafd96e1d36e3
diff --git a/examples/anthropic/package.json b/examples/anthropic/package.jsonnew file mode 100644index 000000000..e8d68e7c1--- /dev/null+++ b/examples/anthropic/package.json@@ -0,0 +1,25 @@+{+ "name": "anthropic-example",+ "private": true,+ "version": "0.1.0",+ "description": "Example for using Anthropic provider with Composio SDK",+ "main": "index.js",+ "scripts": {+ "start": "bun src/index.ts",+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "keywords": [],+ "author": "",+ "license": "ISC",+ "packageManager": "[email protected]",+ "dependencies": {+ "@anthropic-ai/sdk": "^0.18.0",+ "@composio/core": "workspace:*",+ "@composio/anthropic": "workspace:*",+ "dotenv": "^16.4.1"+ },+ "devDependencies": {+ "@types/bun": "^1.2.9",+ "typescript": "^5.8.3"+ }+}diff --git a/examples/anthropic/src/index.ts b/examples/anthropic/src/index.tsnew file mode 100644index 000000000..eafca8b49--- /dev/null+++ b/examples/anthropic/src/index.ts@@ -0,0 +1,115 @@+/**+ * Example for using Anthropic provider with Composio SDK+ */+import { Composio } from '@composio/core';+import { AnthropicProvider } from '@composio/anthropic';+import Anthropic from '@anthropic-ai/sdk';+import 'dotenv/config';++if (!process.env.COMPOSIO_API_KEY) {+ console.error('Missing COMPOSIO_API_KEY environment variable');+ process.exit(1);+}++if (!process.env.ANTHROPIC_API_KEY) {+ console.error('Missing ANTHROPIC_API_KEY environment variable');+ process.exit(1);+}++const anthropic = new Anthropic({+ apiKey: process.env.ANTHROPIC_API_KEY,+});++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ provider: new AnthropicProvider(),+});++async function main() {+ try {+ console.log('Fetching tools from Composio...');+ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');+ console.log(`Fetched ${tools.length} tools`);++ console.log('Creating message with Anthropic...');+ const message = await anthropic.messages.create({+ model: 'claude-3-sonnet-20240229',+ max_tokens: 1024,+ tools: tools,+ messages: [+ {+ role: 'user',+ content: "Fetch the details of the user 'pg' from Hacker News and summarize their profile",+ },+ ],+ });++ console.log('Message created, processing tool calls if any...');++ const toolUseBlocks = message.content.filter(+ (content: any) => content.type === 'tool_use'+ );++ if (toolUseBlocks.length > 0) {+ console.log(`Found ${toolUseBlocks.length} tool calls`);++ const toolResults = await composio.provider.handleToolCalls(+ 'default',+ message+ );++ console.log('Tool results:', toolResults);++ const followUpMessage = await anthropic.messages.create({+ model: 'claude-3-sonnet-20240229',+ max_tokens: 1024,+ messages: [+ {+ role: 'user',+ content: "Fetch the details of the user 'pg' from Hacker News and summarize their profile",+ },+ {+ role: 'assistant',+ content: [+ {+ type: 'text',+ text: "I'll fetch the details for the Hacker News user 'pg'.",+ },+ ...toolUseBlocks,+ ],+ },+ {+ role: 'user',+ content: [+ {+ type: 'tool_result',+ tool_use_id: toolUseBlocks[0].id,+ content: toolResults[0],+ },+ ],+ },+ ],+ });++ const finalResponse = followUpMessage.content+ .filter((content: any) => content.type === 'text')+ .map((content: any) => content.text)+ .join('\n');++ console.log('Final response:');+ console.log(finalResponse);+ } else {+ const response = message.content+ .filter((content: any) => content.type === 'text')+ .map((content: any) => content.text)+ .join('\n');++ console.log('Response (no tool calls):');+ console.log(response);+ }+ } catch (error) {+ console.error('Error:', error);+ }+}++main();diff --git a/packages/providers/anthropic/README.md b/packages/providers/anthropic/README.mdnew file mode 100644index 000000000..a74149ae8--- /dev/null+++ b/packages/providers/anthropic/README.md@@ -0,0 +1,89 @@+# @composio/anthropic++Agentic Provider for Anthropic in Composio SDK.++## Features++- **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++## Installation++```bash+npm install @composio/anthropic+# or+yarn add @composio/anthropic+# or+pnpm add @composio/anthropic+```++## Quick Start++```typescript+import { Composio } from '@composio/core';+import { AnthropicProvider } from '@composio/anthropic';++// Initialize Composio with Anthropic provider+const composio = new Composio({+ apiKey: 'your-composio-api-key',+ provider: new AnthropicProvider(),+});++// Get available tools+const tools = await composio.tools.get('user123', {+ toolkits: ['gmail', 'googlecalendar'],+ limit: 10,+});+```++## Usage Examples++### Basic Example++```typescript+import { Composio } from '@composio/core';+import { AnthropicProvider } from '@composio/anthropic';++// Initialize Composio+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ provider: new AnthropicProvider(),+});++// Get tools+const tools = await composio.tools.get('user123', {+ toolkits: ['gmail'],+});++// Use tools with Anthropic+// Add your usage example here+```++## API Reference++### AnthropicProvider Class++The `AnthropicProvider` class extends `BaseAgenticProvider` and provides anthropic-specific functionality.++#### Methods++##### `wrapTool(tool: Tool, executeTool: ExecuteToolFn): AnthropicTool`++Wraps a tool in the anthropic format.++```typescript+const tool = provider.wrapTool(composioTool, executeTool);+```++## Contributing++We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.++## License++ISC License++## Support++For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).diff --git a/packages/providers/anthropic/package.json b/packages/providers/anthropic/package.jsonnew file mode 100644index 000000000..1d5c3b360--- /dev/null+++ b/packages/providers/anthropic/package.json@@ -0,0 +1,43 @@+{+ "name": "@composio/anthropic",+ "version": "0.1.0",+ "description": "Non-Agentic Provider for Anthropic in Composio SDK",+ "main": "src/index.ts",+ "type": "module",+ "publishConfig": {+ "access": "public",+ "main": "dist/index.js",+ "types": "dist/index.d.ts"+ },+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "require": "./dist/index.cjs"+ }+ },+ "files": [+ "README.md",+ "dist"+ ],+ "scripts": {+ "build": "tsup",+ "test": "vitest run"+ },+ "keywords": ["composio", "provider", "anthropic"],+ "author": "",+ "license": "ISC",+ "packageManager": "[email protected]",+ "dependencies": {+ "@anthropic-ai/sdk": "^0.18.0"+ },+ "peerDependencies": {+ "@composio/core": "^0.1.0"+ },+ "devDependencies": {+ "@composio/core": "workspace:*",+ "tsup": "^8.4.0",+ "typescript": "^5.8.3",+ "vitest": "^1.4.0"+ }+}diff --git a/packages/providers/anthropic/src/index.ts b/packages/providers/anthropic/src/index.tsnew file mode 100644index 000000000..8b1b30e60--- /dev/null+++ b/packages/providers/anthropic/src/index.ts@@ -0,0 +1,159 @@+/**+ * Anthropic Provider+ *+ * This provider provides a set of tools for interacting with Anthropic's API.+ * It implements the non-agentic provider interface for Anthropic's Claude models.+ *+ * @packageDocumentation+ * @module providers/anthropic+ */+import {+ BaseNonAgenticProvider,+ Tool,+ ExecuteToolModifiers,+ ExecuteToolFnOptions,+ ToolExecuteParams+} from '@composio/core';+import Anthropic from '@anthropic-ai/sdk';++/**+ * Anthropic tool format based on their API docs+ */+export interface AnthropicTool {+ name: string;+ description: string;+ input_schema: {+ type: string;+ properties: Record<string, unknown>;+ required: string[];+ };+}++/**+ * Collection of Anthropic tools+ */+export type AnthropicToolCollection = AnthropicTool[];++/**+ * Type for Anthropic tool use block in message content+ */+export interface AnthropicToolUseBlock {+ type: 'tool_use';+ id: string;+ name: string;+ input: Record<string, unknown>;+}++/**+ * Type for Anthropic message content block+ */+export type AnthropicContentBlock = {+ type: string;+ [key: string]: unknown;+};++/**+ * Anthropic Provider implementation for Composio+ */+export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {+ readonly name = 'anthropic';++ /**+ * Wrap a tool in the Anthropic format.+ * @param tool - The tool to wrap.+ * @returns The wrapped tool in Anthropic format.+ */+ override wrapTool(tool: Tool): AnthropicTool {+ const properties = tool.inputParameters?.properties || {};+ const required = tool.inputParameters?.required || [];++ return {+ name: tool.slug,+ description: tool.description || '',+ input_schema: {+ type: 'object',+ properties: properties as Record<string, unknown>,+ required: required as string[],+ },+ };+ }++ /**+ * Wrap a list of tools in the Anthropic format.+ * @param tools - The tools to wrap.+ * @returns The wrapped tools in Anthropic format.+ */+ override wrapTools(tools: Tool[]): AnthropicToolCollection {+ return tools.map(tool => this.wrapTool(tool));+ }++ /**+ * Execute a tool call from Anthropic.+ * @param userId - The user ID+ * @param toolUse - The tool use object from Anthropic+ * @param options - Additional options for tool execution+ * @param modifiers - Modifiers for tool execution+ * @returns The result of the tool execution as a string+ */+ async executeToolCall(+ userId: string,+ toolUse: AnthropicToolUseBlock,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): Promise<string> {+ const payload: ToolExecuteParams = {+ arguments: toolUse.input,+ connectedAccountId: options?.connectedAccountId,+ customAuthParams: options?.customAuthParams,+ userId: userId,+ };+ const result = await this.executeTool(toolUse.name, payload, modifiers);+ return JSON.stringify(result.data);+ }++ /**+ * Handle tool calls from Anthropic's message response+ * @param userId - The user ID+ * @param message - The message response from Anthropic+ * @param options - Additional options for tool execution+ * @param modifiers - Modifiers for tool execution+ * @returns Array of tool execution results+ */+ async handleToolCalls(+ userId: string,+ message: Anthropic.Message,+ options?: ExecuteToolFnOptions,+ modifiers?: ExecuteToolModifiers+ ): Promise<string[]> {+ const outputs: string[] = [];++ // Filter and map tool use blocks from message content+ const toolUseBlocks: AnthropicToolUseBlock[] = [];++ for (const content of message.content) {+ if (+ typeof content === 'object' &&+ content !== null &&+ 'type' in content &&+ typeof content.type === 'string' &&+ content.type.toString() === 'tool_use' &&+ 'id' in content &&+ 'name' in content &&+ 'input' in content+ ) {+ toolUseBlocks.push({+ type: 'tool_use',+ id: String(content.id),+ name: String(content.name),+ input: content.input as Record<string, unknown>+ });+ }+ }++ for (const toolUse of toolUseBlocks) {+ outputs.push(await this.executeToolCall(userId, toolUse, options, modifiers));+ }++ return outputs;+ }+}diff --git a/packages/providers/anthropic/test/anthropic.test.ts b/packages/providers/anthropic/test/anthropic.test.tsnew file mode 100644index 000000000..7ca3af2b9--- /dev/null+++ b/packages/providers/anthropic/test/anthropic.test.ts@@ -0,0 +1,359 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { AnthropicProvider, AnthropicTool, AnthropicToolUseBlock } from '../src';+import { Tool } from '@composio/core';+import Anthropic from '@anthropic-ai/sdk';++vi.mock('@anthropic-ai/sdk', () => {+ return {+ default: vi.fn().mockImplementation(() => ({+ messages: {+ create: vi.fn().mockResolvedValue({+ id: 'msg_123',+ content: [+ { type: 'text', text: 'Hello' },+ {+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool',+ input: { input: 'test-value' },+ },+ ],+ }),+ },+ })),+ };+});++describe('AnthropicProvider', () => {+ let provider: AnthropicProvider;+ let mockTool: Tool;+ let mockExecuteToolFn: any;++ beforeEach(() => {+ provider = new AnthropicProvider();++ mockExecuteToolFn = vi.fn().mockResolvedValue({+ data: { result: 'success' },+ error: null,+ successful: true,+ });+ provider._setExecuteToolFn(mockExecuteToolFn);++ mockTool = {+ slug: 'test-tool',+ name: 'Test Tool',+ description: 'A tool for testing',+ inputParameters: {+ type: 'object',+ properties: {+ input: {+ type: 'string',+ description: 'Test input',+ },+ },+ required: ['input'],+ },+ tags: [],+ };++ vi.clearAllMocks();+ });++ describe('name property', () => {+ it('should have the correct name', () => {+ expect(provider.name).toBe('anthropic');+ });+ });++ describe('_isAgentic property', () => {+ it('should be non-agentic', () => {+ expect(provider._isAgentic).toBe(false);+ });+ });++ describe('wrapTool', () => {+ it('should wrap a tool in Anthropic format', () => {+ const wrapped = provider.wrapTool(mockTool) as AnthropicTool;++ expect(wrapped).toEqual({+ name: mockTool.slug,+ description: mockTool.description,+ input_schema: {+ type: 'object',+ properties: mockTool.inputParameters?.properties,+ required: mockTool.inputParameters?.required,+ },+ });+ });++ it('should handle tools without input parameters', () => {+ const toolWithoutParams: Tool = {+ ...mockTool,+ inputParameters: undefined,+ };++ const wrapped = provider.wrapTool(toolWithoutParams) as AnthropicTool;++ expect(wrapped).toEqual({+ name: toolWithoutParams.slug,+ description: toolWithoutParams.description,+ input_schema: {+ type: 'object',+ properties: {} as Record<string, unknown>,+ required: [] as string[],+ },+ });+ });+ });++ describe('wrapTools', () => {+ it('should wrap multiple tools', () => {+ const anotherTool: Tool = {+ ...mockTool,+ slug: 'another-tool',+ name: 'Another Tool',+ };+ const tools = [mockTool, anotherTool];++ const wrapped = provider.wrapTools(tools);++ expect(wrapped).toHaveLength(2);++ expect(wrapped[0]).toEqual({+ name: mockTool.slug,+ description: mockTool.description,+ input_schema: {+ type: 'object',+ properties: mockTool.inputParameters?.properties,+ required: mockTool.inputParameters?.required,+ },+ });++ expect(wrapped[1]).toEqual({+ name: anotherTool.slug,+ description: anotherTool.description,+ input_schema: {+ type: 'object',+ properties: anotherTool.inputParameters?.properties,+ required: anotherTool.inputParameters?.required,+ },+ });+ });++ it('should return an empty array for empty tools array', () => {+ const wrapped = provider.wrapTools([]);+ expect(wrapped).toEqual([]);+ });+ });++ describe('executeToolCall', () => {+ it('should execute a tool call and return the result as string', async () => {+ const userId = 'test-user';+ const toolUse: AnthropicToolUseBlock = {+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool',+ input: { input: 'test-value' },+ };++ const result = await provider.executeToolCall(userId, toolUse);++ expect(mockExecuteToolFn).toHaveBeenCalledWith(+ 'test-tool',+ {+ arguments: { input: 'test-value' },+ userId: 'test-user',+ connectedAccountId: undefined,+ customAuthParams: undefined,+ },+ undefined+ );+ expect(result).toBe(+ JSON.stringify({ result: 'success' })+ );+ });++ it('should pass options to executeTool', async () => {+ const userId = 'test-user';+ const toolUse: AnthropicToolUseBlock = {+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool',+ input: { input: 'test-value' },+ };++ const options = {+ connectedAccountId: 'conn-123',+ customAuthParams: {+ parameters: [{ name: 'token', value: 'abc123', in: 'header' as const }],+ },+ };++ const modifiers = {+ beforeExecute: vi.fn(params => params),+ afterExecute: vi.fn(response => response),+ };++ await provider.executeToolCall(userId, toolUse, options, modifiers);++ expect(mockExecuteToolFn).toHaveBeenCalledWith(+ 'test-tool',+ {+ arguments: { input: 'test-value' },+ userId: 'test-user',+ connectedAccountId: 'conn-123',+ customAuthParams: options.customAuthParams,+ },+ modifiers+ );+ });+ });++ describe('handleToolCalls', () => {+ it('should handle tool calls from Anthropic message', async () => {+ const userId = 'test-user';+ const message = {+ id: 'msg_123',+ content: [+ { type: 'text', text: 'Hello' },+ {+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool',+ input: { input: 'test-value' },+ },+ ],+ } as Anthropic.Message;++ const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));++ const results = await provider.handleToolCalls(userId, message);++ expect(executeToolCallSpy).toHaveBeenCalledWith(+ userId,+ expect.objectContaining({+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool',+ input: { input: 'test-value' },+ }),+ undefined,+ undefined+ );+ expect(results).toEqual([JSON.stringify({ result: 'success' })]);+ });++ it('should handle multiple tool calls', async () => {+ const userId = 'test-user';+ const message = {+ id: 'msg_123',+ content: [+ { type: 'text', text: 'Hello' },+ {+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool-1',+ input: { input: 'test-value-1' },+ },+ {+ type: 'tool_use',+ id: 'tu_456',+ name: 'test-tool-2',+ input: { input: 'test-value-2' },+ },+ ],+ } as Anthropic.Message;++ const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');+ executeToolCallSpy+ .mockResolvedValueOnce(JSON.stringify({ result: 'success-1' }))+ .mockResolvedValueOnce(JSON.stringify({ result: 'success-2' }));++ const results = await provider.handleToolCalls(userId, message);++ expect(executeToolCallSpy).toHaveBeenCalledTimes(2);+ expect(executeToolCallSpy).toHaveBeenNthCalledWith(+ 1,+ userId,+ expect.objectContaining({+ type: 'tool_use',+ id: 'tu_123',+ name: 'test-tool-1',+ input: { input: 'test-value-1' },+ }),+ undefined,+ undefined+ );+ expect(executeToolCallSpy).toHaveBeenNthCalledWith(+ 2,+ userId,+ expect.objectContaining({+ type: 'tool_use',+ id: 'tu_456',+ name: 'test-tool-2',+ input: { input: 'test-value-2' },+ }),+ undefined,+ undefined+ );+ expect(results).toEqual([+ JSON.stringify({ result: 'success-1' }),+ JSON.stringify({ result: 'success-2' }),+ ]);+ });++ it('should handle messages without tool calls', async () => {+ const userId = 'test-user';+ const message = {+ id: 'msg_123',+ content: [+ { type: 'text', text: 'Hello' },+ ],+ } as Anthropic.Message;++ const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');++ const results = await provider.handleToolCalls(userId, message);++ expect(executeToolCallSpy).not.toHaveBeenCalled();+ expect(results).toEqual([]);+ });+ });++ describe('executeTool', () => {+ it('should execute a tool using the global execute function', async () => {+ const toolSlug = 'test-tool';+ const toolParams = {+ userId: 'test-user',+ arguments: { input: 'test-value' },+ };++ const result = await provider.executeTool(toolSlug, toolParams);++ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);+ expect(result).toEqual({+ data: { result: 'success' },+ error: null,+ successful: true,+ });+ });++ it('should pass modifiers to the global execute function', async () => {+ const toolSlug = 'test-tool';+ const toolParams = {+ userId: 'test-user',+ arguments: { input: 'test-value' },+ };++ const modifiers = {+ beforeExecute: vi.fn(params => params),+ afterExecute: vi.fn(response => response),+ };++ await provider.executeTool(toolSlug, toolParams, modifiers);++ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);+ });+ });+});diff --git a/packages/providers/anthropic/tsconfig.json b/packages/providers/anthropic/tsconfig.jsonnew file mode 100644index 000000000..a05651a3a--- /dev/null+++ b/packages/providers/anthropic/tsconfig.json@@ -0,0 +1,16 @@+{+ "extends": "../../../tsconfig.base.json",+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "declaration": true,+ "declarationDir": "./dist",+ "outDir": "./dist",+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "node",+ "skipLibCheck": true,+ "resolveJsonModule": true+ },+ "include": ["src"]+}diff --git a/packages/providers/anthropic/tsup.config.ts b/packages/providers/anthropic/tsup.config.tsnew file mode 100644index 000000000..f9cdf4040--- /dev/null+++ b/packages/providers/anthropic/tsup.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ entry: ['src/index.ts'],+ format: ['esm', 'cjs'],+ dts: true,+ clean: true,+ minify: false,+ outDir: 'dist',+});