@devries-cameron20 / composio Mirror · read-only / commits / caef90807
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 18:30 UTC

docs: refresh README(s) (#3801)

## Summary Rewrites the stale root `README.md` against the current docs (structure modeled on [earendil-works/pi](https://github.com/earendil-works/pi)'s README). - **Quickstarts** now use the session-based API (`composio.create()` → `session.tools()`) that the docs treat as canonical, replacing the legacy `composio.tools.get()` flow - **Positioning** matches the docs welcome page: 1000+ pre-authenticated toolkits, per-user sessions, auth, triggers, and a sandbox - **New sections**: CLI install (curl / Homebrew / npm), sessions-via-MCP note, repository layout, minimum runtime versions - **Provider table** merged with package links; adds the Claude Agent SDK providers (both SDKs) and the experimental Pi provider (`@composio/experimental`); documents the Python `composio-gemini`/`composio-google`/`composio-google-adk` split - **Removed**: Rube section (no longer in docs), cover banner (replaced with theme-adaptive brand logomark from brand.composio.dev), master-branch pointer, internal OpenAPI-pull section, private `@composio/ts-builders` listing Docs-only change — no changeset needed. ## Preview Rendered view: [README.md on this branch](https://github.com/ComposioHQ/composio/blob/docs/refresh-root-readme/README.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

Rahul Tarak committed Jul 10, 2026 at 06:14 UTC caef908075a32a7ebdf1a514e866607097e87440
29 files changed +1265 -3750
README.md
+126 -199
@@ -1,257 +1,184 @@
1 +<p align="center">
2 + <a href="https://composio.dev">
3 + <picture>
4 + <source media="(prefers-color-scheme: dark)" srcset="https://brand.composio.dev/logos/Logomark-White.svg">
5 + <img alt="Composio logo" src="https://brand.composio.dev/logos/Logomark-Black.svg" width="96">
6 + </picture>
7 + </a>
8 +</p>
9
2 -<div align="center">
10 +<p align="center">
11 + <a href="https://composio.dev"><b>composio.dev</b></a> •
12 + <a href="https://docs.composio.dev">Documentation</a> •
13 + <a href="https://docs.composio.dev/docs/quickstart">Quickstart</a>
14 +</p>
15
4 -<img src="https://raw.githubusercontent.com/ComposioHQ/composio/next/public/cover.png" alt="Composio Logo" width="auto" height="auto" style="margin-bottom: 20px;"/>
16 +<p align="center">
17 + <a href="https://github.com/ComposioHQ/composio/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/ComposioHQ/composio?style=social" /></a>
18 + <a href="https://www.npmjs.com/package/@composio/core"><img alt="npm" src="https://img.shields.io/npm/v/@composio/core?label=%40composio%2Fcore" /></a>
19 + <a href="https://pypi.org/project/composio/"><img alt="PyPI" src="https://img.shields.io/pypi/v/composio?label=composio" /></a>
20 + <a href="https://discord.gg/composio"><img alt="Discord" src="https://img.shields.io/badge/discord-community-5865F2?logo=discord&logoColor=white" /></a>
21 + <a href="https://hvtracker.net/agents/composio/"><img alt="HVTrust" src="https://hvtracker.net/badge/composio.svg" /></a>
22 +</p>
23
24 +# Composio
25
7 -# Composio SDK
26 +Composio gives your AI agents 1000+ pre-authenticated toolkits, per-user sessions, authentication, triggers, and a sandbox, so you can ship agents that turn intent into action.
27
9 -Skills that evolve for your Agents
28 +This is the Composio SDK monorepo. It contains:
29
11 -[🌐 Website](https://composio.dev) • [📚 Documentation](https://docs.composio.dev)
30 +- **[`@composio/core`](ts/packages/core)**: TypeScript SDK
31 +- **[`composio`](python)**: Python SDK
32 +- **[`composio` CLI](ts/packages/cli)**: search, execute, and script tools from your shell
33 +- **Provider adapters** for OpenAI Agents, Claude Agent SDK, Vercel AI SDK, LangChain, and [more](#providers)
34
13 -[![GitHub Stars](https://img.shields.io/github/stars/ComposioHQ/composio?style=social)](https://github.com/ComposioHQ/composio/stargazers)
14 -[![PyPI Downloads](https://img.shields.io/pypi/dm/composio?label=PyPI%20Downloads)](https://pypi.org/project/composio/)
15 -[![NPM Downloads](https://img.shields.io/npm/dt/@composio/core?label=NPM%20Downloads)](https://www.npmjs.com/package/@composio/core)
16 -[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/composio)
17 -[![HVTrust](https://hvtracker.net/badge/composio.svg)](https://hvtracker.net/agents/composio/)
18 -</div>
35 +## Quickstart
36
20 -This repository contains the official Software Development Kits (SDKs) for Composio, providing seamless integration capabilities for Python and Typescript Agentic Frameworks and Libraries.
37 +Create a session for a user, hand its tools to your agent, and let the agent take action across 1000+ apps. Grab a `COMPOSIO_API_KEY` from the [dashboard](https://dashboard.composio.dev/settings) first.
38
22 -## Getting Started
23 -
24 -### TypeScript SDK Installation
39 +### TypeScript
40
41 ```bash
27 -# Using npm
28 -npm install @composio/core
29 -
30 -# Using yarn
31 -yarn add @composio/core
32 -
33 -# Using pnpm
34 -pnpm add @composio/core
35 -```
36 -
37 -#### Quick start:
38 -
39 -```typescript
40 -import { Composio } from '@composio/core';
41 -// Initialize the SDK
42 -const composio = new Composio({
43 - // apiKey: 'your-api-key',
44 -});
42 +npm install @composio/core @composio/openai-agents @openai/agents
43 ```
44
47 -#### Simple Agent with OpenAI Agents
48 -
49 -```bash
50 -npm install @composio/openai-agents @openai/agents
51 -```
45 +> `@composio/core` intentionally packages its TypeScript source and SDK docs so the installed package is inspectable to coding agents. If you want a smaller install with the same API, use [`@composio/slim`](ts/packages/slim).
46
47 ```typescript
54 -import { Composio } from '@composio/core';
55 -import { OpenAIAgentsProvider } from '@composio/openai-agents';
56 -import { Agent, run } from '@openai/agents';
48 +import { Composio } from "@composio/core";
49 +import { OpenAIAgentsProvider } from "@composio/openai-agents";
50 +import { Agent, run } from "@openai/agents";
51
58 -const composio = new Composio({
59 - provider: new OpenAIAgentsProvider(),
60 -});
52 +const composio = new Composio({ provider: new OpenAIAgentsProvider() });
53
62 -const userId = 'user@acme.org';
63 -
64 -const tools = await composio.tools.get(userId, {
65 - toolkits: ['HACKERNEWS'],
66 -});
54 +// Each session is scoped to one of your users
55 +const session = await composio.create("user_123");
56 +const tools = await session.tools();
57
58 const agent = new Agent({
69 - name: 'Hackernews assistant',
70 - tools: tools,
59 + name: "Personal Assistant",
60 + instructions: "You are a helpful assistant. Use Composio tools to take action.",
61 + tools,
62 });
63
73 -const result = await run(agent, 'What is the latest hackernews post about?');
74 -
75 -console.log(JSON.stringify(result.finalOutput, null, 2));
76 -// will return the response from the agent with data from HACKERNEWS API.
64 +const result = await run(agent, "Summarize my emails from today");
65 +console.log(result.finalOutput);
66 ```
67
79 -### Python SDK Installation
68 +### Python
69
70 ```bash
82 -# Using pip
83 -pip install composio
84 -
85 -# Using poetry
86 -poetry add composio
71 +pip install composio composio-openai-agents openai-agents
72 ```
73
89 -#### Quick start:
90 -
74 ```python
75 from composio import Composio
93 -
94 -composio = Composio(
95 - # api_key="your-api-key",
96 -)
97 -```
98 -
99 -#### Simple Agent with OpenAI Agents
100 -
101 -```bash
102 -pip install composio_openai_agents openai-agents
103 -```
104 -
105 -```python
106 -import asyncio
107 -from agents import Agent, Runner
108 -from composio import Composio
76 from composio_openai_agents import OpenAIAgentsProvider
77 +from agents import Agent, Runner
78
111 -# Initialize Composio client with OpenAI Agents Provider
79 composio = Composio(provider=OpenAIAgentsProvider())
80
114 -user_id = "user@acme.org"
115 -tools = composio.tools.get(user_id=user_id, toolkits=["HACKERNEWS"])
81 +# Each session is scoped to one of your users
82 +session = composio.create(user_id="user_123")
83 +tools = session.tools()
84
117 -# Create an agent with the tools
85 agent = Agent(
119 - name="Hackernews Agent",
120 - instructions="You are a helpful assistant.",
86 + name="Personal Assistant",
87 + instructions="You are a helpful assistant. Use Composio tools to take action.",
88 tools=tools,
89 )
90
124 -# Run the agent
125 -async def main():
126 - result = await Runner.run(
127 - starting_agent=agent,
128 - input="What's the latest Hackernews post about?",
129 - )
130 - print(result.final_output)
131 -
132 -asyncio.run(main())
133 -# will return the response from the agent with data from HACKERNEWS API.
91 +result = Runner.run_sync(starting_agent=agent, input="Summarize my emails from today")
92 +print(result.final_output)
93 ```
94
136 -For more detailed usage instructions and examples, please refer to each SDK's specific documentation.
95 +By default a session gets meta tools that discover, authenticate, and execute app tools at runtime, so you don't load hundreds of tool definitions into context. Store `session.session_id` and reuse it with `composio.use()` across turns. See [what a session is](https://docs.composio.dev/docs/how-composio-works) and [configuring sessions](https://docs.composio.dev/docs/configuring-sessions) for restricting toolkits, auth configs, and connected accounts.
96 +
97 +**Prefer MCP?** Every session also exposes a hosted MCP endpoint. Pass `mcp: true` to `composio.create()` and point Claude, Cursor, or any MCP client at `session.mcp.url`. See [sessions via MCP](https://docs.composio.dev/docs/sessions-via-mcp).
98
138 -### Open API Specification
99 +## CLI
100
140 -To update the OpenAPI specifications used for generating SDK documentation:
101 +The `composio` CLI runs Composio from your shell and gives coding agents like Claude Code a local tool surface.
102
103 ```bash
143 -# Pull the latest API specifications from the backend
144 -pnpm api:pull
104 +curl -fsSL https://composio.dev/install | bash
105 +composio login
106 ```
107
147 -This command pulls the OpenAPI specification from `https://backend.composio.dev/api/v3/openapi.json` and updates the local API documentation files.
148 -
149 -This is pulled automatically with build step.
108 +Use `composio search` to find tools, `composio execute` to run them, `composio link` to connect accounts, and `composio run` to script workflows in TypeScript. See the [CLI docs](https://docs.composio.dev/docs/cli).
109
151 -## Available SDKs
110 +## Providers
111
153 -### TypeScript SDK (/ts)
112 +A provider adapts Composio tools to your agent framework's native tool format:
113
155 -The TypeScript SDK provides a modern, type-safe way to interact with Composio's services. It's designed for both Node.js and browser environments, offering full TypeScript support with comprehensive type definitions.
156 -
157 -For detailed information about the TypeScript SDK, please refer to the [TypeScript SDK Documentation](/ts/README.md).
114 +| Provider | TypeScript | Python |
115 +|----------|:----------:|:------:|
116 +| OpenAI | [`@composio/openai`](ts/packages/providers/openai) | [`composio-openai`](python/providers/openai) |
117 +| OpenAI Agents | [`@composio/openai-agents`](ts/packages/providers/openai-agents) | [`composio-openai-agents`](python/providers/openai_agents) |
118 +| Anthropic | [`@composio/anthropic`](ts/packages/providers/anthropic) | [`composio-anthropic`](python/providers/anthropic) |
119 +| Claude Agent SDK | [`@composio/claude-agent-sdk`](ts/packages/providers/claude-agent-sdk) | [`composio-claude-agent-sdk`](python/providers/claude_agent_sdk) |
120 +| Vercel AI SDK | [`@composio/vercel`](ts/packages/providers/vercel) | — |
121 +| Google GenAI | [`@composio/google`](ts/packages/providers/google) | [`composio-gemini`](python/providers/gemini), [`composio-google`](python/providers/google) |
122 +| Google ADK | — | [`composio-google-adk`](python/providers/google_adk) |
123 +| LangChain | [`@composio/langchain`](ts/packages/providers/langchain) | [`composio-langchain`](python/providers/langchain) |
124 +| LangGraph | via `@composio/langchain` | [`composio-langgraph`](python/providers/langgraph) |
125 +| LlamaIndex | [`@composio/llamaindex`](ts/packages/providers/llamaindex) | [`composio-llamaindex`](python/providers/llamaindex) |
126 +| Mastra | [`@composio/mastra`](ts/packages/providers/mastra) | — |
127 +| Pi | [`@composio/experimental`](ts/packages/experimental)* | — |
128 +| Cloudflare Workers AI | [`@composio/cloudflare`](ts/packages/providers/cloudflare) | — |
129 +| CrewAI | — | [`composio-crewai`](python/providers/crewai) |
130 +| AutoGen | — | [`composio-autogen`](python/providers/autogen) |
131 +
132 +\* *The [Pi provider](https://docs.composio.dev/docs/providers/pi) is experimental and ships from `@composio/experimental`.*
133 +
134 +Don't see your framework? [Build a custom provider](https://docs.composio.dev/docs/providers/custom-providers), or skip providers entirely and connect over [MCP](https://docs.composio.dev/docs/sessions-via-mcp).
135 +
136 +## All packages
137 +
138 +Everything published from this repo:
139 +
140 +| Package | Description |
141 +|---------|-------------|
142 +| [`@composio/core`](ts/packages/core) | TypeScript SDK |
143 +| [`@composio/slim`](ts/packages/slim) | `@composio/core` without packaged source or docs; same API, smaller install |
144 +| [`composio` CLI](ts/packages/cli) | Standalone CLI binary: `curl -fsSL https://composio.dev/install \| bash` |
145 +| [`@composio/experimental`](ts/packages/experimental) | Experimental integrations, including the Pi provider |
146 +| [`@composio/json-schema-to-zod`](ts/packages/json-schema-to-zod) | JSON Schema to Zod conversion |
147 +| `@composio/*` [provider adapters](#providers) | OpenAI, OpenAI Agents, Anthropic, Claude Agent SDK, Vercel, Google, LangChain, LlamaIndex, Mastra, Cloudflare |
148 +| [`composio`](python) | Python SDK |
149 +| `composio-*` [provider adapters](#providers) | OpenAI, OpenAI Agents, Anthropic, Claude Agent SDK, Gemini, Google, Google ADK, LangChain, LangGraph, LlamaIndex, CrewAI, AutoGen |
150 +
151 +## Repository layout
152 +
153 +```text
154 +ts/ TypeScript SDK workspace
155 + packages/core/ @composio/core
156 + packages/providers/ Provider adapters
157 + packages/cli/ Composio CLI
158 +python/ Python SDK and provider packages
159 +docs/ Documentation site (docs.composio.dev)
160 +```
161
159 -### Python SDK (/python)
162 +The TypeScript SDK is tested against Node 22+; the Python SDK supports Python 3.10+.
163
161 -The Python SDK offers a Pythonic interface to Composio's services, making it easy to integrate Composio into your Python applications. It supports Python 3.10+ and follows modern Python development practices.
164 +## Development
165
163 -For detailed information about the Python SDK, please refer to the [Python SDK Documentation](/python/README.md).
166 +```bash
167 +mise install # pinned toolchain (Node, Python, pnpm)
168 +pnpm install
169 +pnpm build
170 +pnpm test
171 +```
172
165 -## Provider Support
173 +Python commands run from `python/`; see [`python/README.md`](python/README.md). We welcome contributions to both SDKs; read the [contribution guidelines](CONTRIBUTING.md) before submitting pull requests.
174
167 -The following table shows which AI frameworks and platforms are supported in each SDK:
175 +## Support
176
169 -| Provider | TypeScript | Python |
170 -|----------|:----------:|:------:|
171 -| OpenAI | ✅ | ✅ |
172 -| OpenAI Agents | ✅ | ✅ |
173 -| Anthropic | ✅ | ✅ |
174 -| LangChain | ✅ | ✅ |
175 -| LangGraph | ✅* | ✅ |
176 -| LlamaIndex | ✅ | ✅ |
177 -| Vercel AI SDK | ✅ | ❌ |
178 -| Google Gemini | ✅ | ✅ |
179 -| Google ADK | ❌ | ✅ |
180 -| Mastra | ✅ | ❌ |
181 -| Cloudflare Workers AI | ✅ | ❌ |
182 -| CrewAI | ❌ | ✅ |
183 -| AutoGen | ❌ | ✅ |
184 -
185 -\* *LangGraph in TypeScript is supported via the `@composio/langchain` package.*
186 -
187 -> **Don't see your provider?** Learn how to [build a custom provider](https://docs.composio.dev/sdk/typescript/custom-providers) to integrate with any AI framework.
188 -
189 -## Packages
190 -
191 -### Core Packages
192 -
193 -| Package | Version |
194 -|---------|---------|
195 -| **TypeScript** | |
196 -| [@composio/core](https://www.npmjs.com/package/@composio/core) | ![npm version](https://img.shields.io/npm/v/@composio/core) |
197 -| **Python** | |
198 -| [composio](https://pypi.org/project/composio/) | ![PyPI version](https://img.shields.io/pypi/v/composio) |
199 -
200 -### Provider Packages
201 -
202 -| Package | Version |
203 -|---------|---------|
204 -| **TypeScript** | |
205 -| [@composio/openai](https://www.npmjs.com/package/@composio/openai) | ![npm version](https://img.shields.io/npm/v/@composio/openai) |
206 -| [@composio/openai-agents](https://www.npmjs.com/package/@composio/openai-agents) | ![npm version](https://img.shields.io/npm/v/@composio/openai-agents) |
207 -| [@composio/anthropic](https://www.npmjs.com/package/@composio/anthropic) | ![npm version](https://img.shields.io/npm/v/@composio/anthropic) |
208 -| [@composio/langchain](https://www.npmjs.com/package/@composio/langchain) | ![npm version](https://img.shields.io/npm/v/@composio/langchain) |
209 -| [@composio/llamaindex](https://www.npmjs.com/package/@composio/llamaindex) | ![npm version](https://img.shields.io/npm/v/@composio/llamaindex) |
210 -| [@composio/vercel](https://www.npmjs.com/package/@composio/vercel) | ![npm version](https://img.shields.io/npm/v/@composio/vercel) |
211 -| [@composio/google](https://www.npmjs.com/package/@composio/google) | ![npm version](https://img.shields.io/npm/v/@composio/google) |
212 -| [@composio/mastra](https://www.npmjs.com/package/@composio/mastra) | ![npm version](https://img.shields.io/npm/v/@composio/mastra) |
213 -| [@composio/cloudflare](https://www.npmjs.com/package/@composio/cloudflare) | ![npm version](https://img.shields.io/npm/v/@composio/cloudflare) |
214 -| **Python** | |
215 -| [composio-openai](https://pypi.org/project/composio-openai/) | ![PyPI version](https://img.shields.io/pypi/v/composio-openai) |
216 -| [composio-openai-agents](https://pypi.org/project/composio-openai-agents/) | ![PyPI version](https://img.shields.io/pypi/v/composio-openai-agents) |
217 -| [composio-anthropic](https://pypi.org/project/composio-anthropic/) | ![PyPI version](https://img.shields.io/pypi/v/composio-anthropic) |
218 -| [composio-langchain](https://pypi.org/project/composio-langchain/) | ![PyPI version](https://img.shields.io/pypi/v/composio-langchain) |
219 -| [composio-langgraph](https://pypi.org/project/composio-langgraph/) | ![PyPI version](https://img.shields.io/pypi/v/composio-langgraph) |
220 -| [composio-llamaindex](https://pypi.org/project/composio-llamaindex/) | ![PyPI version](https://img.shields.io/pypi/v/composio-llamaindex) |
221 -| [composio-crewai](https://pypi.org/project/composio-crewai/) | ![PyPI version](https://img.shields.io/pypi/v/composio-crewai) |
222 -| [composio-autogen](https://pypi.org/project/composio-autogen/) | ![PyPI version](https://img.shields.io/pypi/v/composio-autogen) |
223 -| [composio-gemini](https://pypi.org/project/composio-gemini/) | ![PyPI version](https://img.shields.io/pypi/v/composio-gemini) |
224 -| [composio-google](https://pypi.org/project/composio-google/) | ![PyPI version](https://img.shields.io/pypi/v/composio-google) |
225 -| [composio-google-adk](https://pypi.org/project/composio-google-adk/) | ![PyPI version](https://img.shields.io/pypi/v/composio-google-adk) |
226 -
227 -### Utility Packages
228 -
229 -| Package | Version |
230 -|---------|---------|
231 -| [@composio/json-schema-to-zod](https://www.npmjs.com/package/@composio/json-schema-to-zod) | ![npm version](https://img.shields.io/npm/v/@composio/json-schema-to-zod) |
232 -| [@composio/ts-builders](https://www.npmjs.com/package/@composio/ts-builders) | ![npm version](https://img.shields.io/npm/v/@composio/ts-builders) |
233 -
234 -_if you are looking for the older sdk, you can find them [here](https://github.com/ComposioHQ/composio/tree/master)_
235 -
236 -## Rube
237 -
238 -[Rube](https://rube.app) is a Model Context Protocol (MCP) server built with Composio. It connects your AI tools to 500+ apps like Gmail, Slack, GitHub, and Notion. Simply install it in your AI client, authenticate once with your apps, and start asking your AI to perform real actions like "Send an email" or "Create a task."
239 -
240 -It integrates with major AI clients like Cursor, Claude Desktop, VS Code, Claude Code and any custom MCP‑compatible client. You can switch between these clients and your integrations follow you.
241 -
242 -
243 -## Contributing
244 -
245 -We welcome contributions to both SDKs! Please read our [contribution guidelines](https://github.com/ComposioHQ/composio/blob/next/CONTRIBUTING.md) before submitting pull requests.
177 +- [Documentation](https://docs.composio.dev)
178 +- [Discord community](https://discord.gg/composio)
179 +- [Open an issue](https://github.com/ComposioHQ/composio/issues)
180 +- [support@composio.dev](mailto:support@composio.dev)
181
182 ## License
183
249 -This project is licensed under the MIT License - see the LICENSE file for details.
250 -
251 -## Support
252 -
253 -If you encounter any issues or have questions about the SDKs:
254 -
255 -- Open an issue in this repository
256 -- Contact our [support team](mailto:support@composio.dev)
257 -- Check our [documentation](https://docs.composio.dev/)
184 +MIT. See [LICENSE](LICENSE).
python/README.md
+72 -421
@@ -1,490 +1,141 @@
1 -![Composio Banner](https://github.com/user-attachments/assets/9ba0e9c1-85a4-4b51-ae60-f9fe7992e819)
1 +<p align="center">
2 + <a href="https://composio.dev">
3 + <picture>
4 + <source media="(prefers-color-scheme: dark)" srcset="https://brand.composio.dev/logos/Logomark-White.svg">
5 + <img alt="Composio logo" src="https://brand.composio.dev/logos/Logomark-Black.svg" width="96">
6 + </picture>
7 + </a>
8 +</p>
9
3 -# Composio
10 +# Composio Python SDK
11
5 -The Composio Python SDK allows you to interact with the Composio Platform. It provides a powerful and flexible way to manage and execute tools, handle authentication, and integrate with various AI frameworks and platforms.
12 +Composio gives your AI agents 1000+ pre-authenticated toolkits, per-user sessions, authentication, triggers, and a sandbox. This package is the Python SDK.
13
7 -[Learn more about the SDK from our docs](https://docs.composio.dev)
14 +- [Documentation](https://docs.composio.dev)
15 +- [Quickstart](https://docs.composio.dev/docs/quickstart)
16 +- [Dashboard](https://dashboard.composio.dev) (grab your `COMPOSIO_API_KEY` from [Settings](https://dashboard.composio.dev/settings))
17
9 -## Core Features
18 +## Install
19
11 -- **Tools**: Manage and execute tools within the Composio ecosystem. Includes functionality to list, retrieve, and execute tools.
12 -- **Toolkits**: Organize and manage collections of tools for specific use cases.
13 -- **Triggers**: Create and manage event triggers that can execute tools based on specific conditions.
14 -- **AuthConfigs**: Configure authentication providers and settings.
15 -- **ConnectedAccounts**: Manage third-party service connections.
16 -- **ActionExecution**: Track and manage the execution of actions within the platform.
17 -- **Provider Integrations**: Built-in support for OpenAI, Anthropic, LangChain, CrewAI, AutoGen, and more.
18 -
19 -## Installation
20 +Requires Python 3.10+.
21
22 ```bash
23 pip install composio
23 -# or
24 -pip install composio-core
25 -```
26 -
27 -### Provider-Specific Installations
28 -
29 -For specific AI framework integrations:
30 -
31 -```bash
32 -# OpenAI integration
33 -pip install composio-openai
34 -
35 -# LangChain integration
36 -pip install composio-langchain
37 -
38 -# CrewAI integration
39 -pip install composio-crewai
40 -
41 -# Anthropic integration
42 -pip install composio-anthropic
43 -
44 -# AutoGen integration
45 -pip install composio-autogen
46 -
47 -# And many more...
48 -```
49 -
50 -## Getting Started
51 -
52 -### Basic Usage with OpenAI
53 -
54 -```python
55 -import os
56 -from composio import Composio
57 -from openai import OpenAI
58 -
59 -# Initialize OpenAI client
60 -openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
61 -
62 -# Initialize Composio with your API key
63 -composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
64 -
65 -def main():
66 - try:
67 - # Fetch tools - single tool or multiple tools
68 - tools = composio.tools.get(user_id="default", slug="HACKERNEWS_GET_USER")
69 - # Or fetch multiple tools: composio.tools.get(user_id="default", toolkits=["hackernews"])
70 -
71 - query = "Find information about the HackerNews user 'pg'"
72 -
73 - # Create chat completion with tools
74 - response = openai_client.chat.completions.create(
75 - model="gpt-4o",
76 - messages=[
77 - {
78 - "role": "system",
79 - "content": "You are a helpful assistant that can use tools to answer questions."
80 - },
81 - {"role": "user", "content": query}
82 - ],
83 - tools=tools,
84 - tool_choice="auto"
85 - )
86 -
87 - # Handle tool calls if the assistant decides to use them
88 - if response.choices[0].message.tool_calls:
89 - print("🔧 Assistant is using tool:", response.choices[0].message.tool_calls[0].function.name)
90 -
91 - # Execute the tool call
92 - tool_result = composio.provider.handle_tool_calls(
93 - response=response,
94 - user_id="default"
95 - )
96 -
97 - print("✅ Tool execution result:", tool_result)
98 -
99 - # Get final response from assistant with tool result
100 - final_response = openai_client.chat.completions.create(
101 - model="gpt-4o",
102 - messages=[
103 - {
104 - "role": "system",
105 - "content": "You are a helpful assistant that can use tools to answer questions."
106 - },
107 - {"role": "user", "content": query},
108 - response.choices[0].message,
109 - {
110 - "role": "tool",
111 - "tool_call_id": response.choices[0].message.tool_calls[0].id,
112 - "content": str(tool_result)
113 - }
114 - ]
115 - )
116 -
117 - print("🤖 Final response:", final_response.choices[0].message.content)
118 - else:
119 - print("🤖 Response:", response.choices[0].message.content)
120 -
121 - except Exception as error:
122 - print("❌ Error:", error)
123 -
124 -if __name__ == "__main__":
125 - main()
24 ```
25
128 -### Using with Provider Integrations
26 +## Quickstart
27
130 -#### OpenAI Provider
28 +Create a session for one of your users and hand its tools to your agent:
29
30 ```python
133 -from composio_openai import OpenAIProvider
134 -from openai import OpenAI
31 from composio import Composio
32
137 -# Initialize with OpenAI provider
138 -openai_client = OpenAI()
139 -composio = Composio(provider=OpenAIProvider())
140 -
141 -# Define task
142 -task = "Star a repo composiohq/composio on GitHub"
33 +composio = Composio() # reads COMPOSIO_API_KEY, or pass api_key=...
34
144 -# Get GitHub tools that are pre-configured
145 -tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
146 -
147 -# Get response from the LLM
148 -response = openai_client.chat.completions.create(
149 - model="gpt-4o-mini",
150 - tools=tools,
151 - messages=[
152 - {"role": "system", "content": "You are a helpful assistant."},
153 - {"role": "user", "content": task},
154 - ],
155 -)
156 -
157 -# Execute the function calls
158 -result = composio.provider.handle_tool_calls(response=response, user_id="default")
159 -print(result)
35 +session = composio.create(user_id="user_123")
36 +tools = session.tools() # OpenAI-format tool definitions by default
37 ```
38
162 -#### LangChain Integration
39 +By default a session gets meta tools that discover, authenticate, and execute app tools at runtime, so you don't load hundreds of tool definitions into context. Store `session.session_id` and reuse the session across turns:
40
41 ```python
165 -from composio_langchain import ComposioToolSet
166 -from langchain_openai import ChatOpenAI
167 -
168 -# Initialize the toolset
169 -toolset = ComposioToolSet()
170 -
171 -# Get tools for a specific toolkit
172 -tools = toolset.get_tools(toolkits=["GITHUB"])
173 -
174 -# Initialize LLM
175 -llm = ChatOpenAI(model="gpt-4o")
42 +session = composio.use(session_id)
43 +```
44
177 -# Create agent with tools
178 -from langchain.agents import create_openai_functions_agent, AgentExecutor
179 -from langchain.prompts import ChatPromptTemplate
45 +See [how Composio works](https://docs.composio.dev/docs/how-composio-works) for sessions and meta tools, and [configuring sessions](https://docs.composio.dev/docs/configuring-sessions) for restricting `toolkits`, `tools`, `auth_configs`, and `connected_accounts` on `composio.create()`.
46
181 -prompt = ChatPromptTemplate.from_messages([
182 - ("system", "You are a helpful assistant"),
183 - ("user", "{input}"),
184 - ("assistant", "{agent_scratchpad}")
185 -])
47 +## Use with an agent framework
48
187 -agent = create_openai_functions_agent(llm, tools, prompt)
188 -agent_executor = AgentExecutor(agent=agent, tools=tools)
49 +Provider packages adapt `session.tools()` to your framework's native tool format. With [OpenAI Agents](https://github.com/ComposioHQ/composio/tree/next/python/providers/openai_agents):
50
190 -# Execute task
191 -result = agent_executor.invoke({"input": "Star the composiohq/composio repository"})
192 -print(result)
51 +```bash
52 +pip install composio composio-openai-agents openai-agents
53 ```
54
195 -## Configuration
196 -
197 -The Composio constructor accepts the following configuration options:
198 -
55 ```python
56 from composio import Composio
201 -from composio.core.provider import OpenAIProvider
202 -
203 -composio = Composio(
204 - api_key="your-api-key", # Your Composio API key
205 - base_url="https://api.composio.dev", # Custom API base URL (optional)
206 - timeout=60, # Request timeout in seconds
207 - max_retries=3, # Maximum number of retries
208 - allow_tracking=True, # Enable/disable telemetry (default: True)
209 - file_download_dir="./downloads", # Directory for file downloads
210 - provider=OpenAIProvider(), # Custom provider (default: OpenAIProvider)
211 - toolkit_versions={ "github": "12202025_01" } # Toolkit versions to use
212 -)
213 -```
214 -
215 -## Modifiers
216 -
217 -Composio SDK supports powerful modifiers to transform tool schemas and execution behavior.
57 +from composio_openai_agents import OpenAIAgentsProvider
58 +from agents import Agent, Runner
59
219 -### Schema Modifiers
60 +composio = Composio(provider=OpenAIAgentsProvider())
61
221 -Schema modifiers allow you to transform tool schemas before they are used:
62 +session = composio.create(user_id="user_123")
63 +tools = session.tools()
64
223 -```python
224 -from composio import schema_modifier
225 -from composio.types import Tool
226 -
227 -@schema_modifier(tools=["HACKERNEWS_GET_USER"])
228 -def modify_schema(tool: str, toolkit: str, schema: Tool) -> Tool:
229 - # Perform modifications on the schema
230 - schema["description"] = "Enhanced HackerNews user lookup with additional features"
231 - schema["parameters"]["properties"]["include_karma"] = {
232 - "type": "boolean",
233 - "description": "Include user karma in response",
234 - "default": True
235 - }
236 - return schema
237 -
238 -# Use the modifier when getting tools
239 -tools = composio.tools.get(
240 - user_id="default",
241 - slug="HACKERNEWS_GET_USER",
242 - modifiers=[modify_schema]
65 +agent = Agent(
66 + name="Personal Assistant",
67 + instructions="You are a helpful assistant. Use Composio tools to take action.",
68 + tools=tools,
69 )
244 -```
245 -
246 -### Execution Modifiers
70
248 -Transform tool execution behavior with before and after execute modifiers:
249 -
250 -```python
251 -from composio import before_execute, after_execute
252 -from composio.types import ToolExecuteParams, ToolExecutionResponse
253 -
254 -@before_execute(tools=["HACKERNEWS_GET_USER"])
255 -def before_execute_modifier(
256 - tool: str,
257 - toolkit: str,
258 - params: ToolExecuteParams
259 -) -> ToolExecuteParams:
260 - # Transform input before execution
261 - print(f"Executing {tool} with params: {params}")
262 - return params
263 -
264 -@after_execute(tools=["HACKERNEWS_GET_USER"])
265 -def after_execute_modifier(
266 - tool: str,
267 - toolkit: str,
268 - response: ToolExecutionResponse
269 -) -> ToolExecutionResponse:
270 - # Transform output after execution
271 - return {
272 - **response,
273 - "data": {
274 - **response["data"],
275 - "processed_at": "2024-01-01T00:00:00Z"
276 - }
277 - }
278 -
279 -# Execute tool with modifiers
280 -response = composio.tools.execute(
281 - user_id="default",
282 - slug="HACKERNEWS_GET_USER",
283 - arguments={"username": "pg"},
284 - modifiers=[before_execute_modifier, after_execute_modifier]
285 -)
71 +result = Runner.run_sync(starting_agent=agent, input="Summarize my emails from today")
72 +print(result.final_output)
73 ```
74
288 -## Connected Accounts
75 +Other Python providers: [`composio-openai`](https://github.com/ComposioHQ/composio/tree/next/python/providers/openai), [`composio-anthropic`](https://github.com/ComposioHQ/composio/tree/next/python/providers/anthropic), [`composio-claude-agent-sdk`](https://github.com/ComposioHQ/composio/tree/next/python/providers/claude_agent_sdk), [`composio-langchain`](https://github.com/ComposioHQ/composio/tree/next/python/providers/langchain), [`composio-langgraph`](https://github.com/ComposioHQ/composio/tree/next/python/providers/langgraph), [`composio-llamaindex`](https://github.com/ComposioHQ/composio/tree/next/python/providers/llamaindex), [`composio-crewai`](https://github.com/ComposioHQ/composio/tree/next/python/providers/crewai), [`composio-autogen`](https://github.com/ComposioHQ/composio/tree/next/python/providers/autogen), [`composio-gemini`](https://github.com/ComposioHQ/composio/tree/next/python/providers/gemini), [`composio-google`](https://github.com/ComposioHQ/composio/tree/next/python/providers/google), [`composio-google-adk`](https://github.com/ComposioHQ/composio/tree/next/python/providers/google_adk). Don't see yours? [Build a custom provider](https://docs.composio.dev/docs/providers/custom-providers).
76
290 -Composio SDK provides a powerful way to manage third-party service connections through Connected Accounts. This feature allows you to authenticate with various services and maintain those connections.
77 +## MCP
78
292 -### Creating a Connected Account
79 +Every session also exposes a hosted MCP endpoint. Pass `mcp=True` and point Claude, Cursor, or any MCP client at it:
80
81 ```python
82 from composio import Composio
296 -from composio.types import auth_scheme
297 -
298 -composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
299 -
300 -# Create a connected account with OAuth
301 -connection_request = composio.connected_accounts.initiate(
302 - user_id="user123",
303 - auth_config_id="ac_12343544", # You can create it from the dashboard
304 - callback_url="https://your-app.com/callback",
305 - data={
306 - # Additional data for the connection
307 - "scope": ["read", "write"]
308 - }
309 -)
310 -
311 -# Wait for the connection to be established
312 -# Default timeout is 60 seconds
313 -connected_account = connection_request.wait_for_connection()
314 -print(connected_account)
315 -```
316 -
317 -### API Key Authentication
318 -
319 -```python
320 -# Create a connected account with API Key
321 -connection_request = composio.connected_accounts.initiate(
322 - user_id="user123",
323 - auth_config_id="ac_12343544",
324 - config=auth_scheme.api_key(
325 - options={
326 - "api_key": "your-api-key-here"
327 - }
328 - )
329 -)
330 -```
331 -
332 -### Managing Connected Accounts
83
334 -```python
335 -# List all connected accounts
336 -accounts = composio.connected_accounts.list(user_id="user123")
337 -
338 -# Get a specific connected account
339 -account = composio.connected_accounts.get("account_id")
340 -
341 -# Enable/Disable a connected account
342 -composio.connected_accounts.enable("account_id")
343 -composio.connected_accounts.disable("account_id")
344 -
345 -# Refresh credentials
346 -composio.connected_accounts.refresh("account_id")
84 +composio = Composio()
85
348 -# Delete a connected account
349 -composio.connected_accounts.delete("account_id")
86 +session = composio.create(user_id="user_123", mcp=True)
87 +print(session.mcp.url) # MCP endpoint for this session
88 +print(session.mcp.headers) # auth headers for the endpoint
89 ```
90
352 -### Connection Statuses
353 -
354 -Connected accounts can have the following statuses:
355 -
356 -- `ACTIVE`: Connection is established and working
357 -- `INACTIVE`: Connection is temporarily disabled
358 -- `PENDING`: Connection is being processed
359 -- `INITIATED`: Connection request has started
360 -- `EXPIRED`: Connection credentials have expired
361 -- `FAILED`: Connection attempt failed
362 -
363 -## Tools and Toolkits
364 -
365 -### Working with Tools
91 +See [sessions via MCP](https://docs.composio.dev/docs/sessions-via-mcp).
92
367 -```python
368 -# Get tools by toolkit
369 -tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
370 -
371 -# Get tools by search
372 -tools = composio.tools.get(user_id="default", search="user")
373 -
374 -# Get tools by toolkit and search
375 -tools = composio.tools.get(user_id="default", toolkits=["GITHUB"], search="star")
376 -
377 -# Execute a tool directly
378 -response = composio.tools.execute(
379 - user_id="default",
380 - slug="HACKERNEWS_GET_USER",
381 - arguments={"username": "pg"}
382 -)
383 -print(response)
384 -```
385 -
386 -### Proxy Calls
93 +## Authentication
94
388 -Make direct API calls through connected accounts:
95 +Sessions manage connections for you by default; the agent walks the user through OAuth with the session's meta tools. To drive the flow yourself, authorize a toolkit from the session:
96
97 ```python
391 -# Execute proxy call (GitHub API)
392 -proxy_response = composio.tools.proxy(
393 - endpoint="/repos/composiohq/composio/issues/1",
394 - method="GET",
395 - connected_account_id="ac_1234", # Use connected account for GitHub
396 - parameters=[
397 - {
398 - "name": "Accept",
399 - "value": "application/vnd.github.v3+json",
400 - "type": "header"
401 - }
402 - ]
403 -)
404 -print(proxy_response)
98 +connection_request = session.authorize("gmail")
99 +print(connection_request.redirect_url) # send the user here to approve access
100 +connection_request.wait_for_connection()
101 ```
102
407 -## Authentication Schemes
408 -
409 -Composio supports various authentication schemes:
410 -
411 -- OAuth2
412 -- OAuth1
413 -- OAuth1a
414 -- API Key
415 -- Basic Auth
416 -- Bearer Token
417 -- Google Service Account
418 -- And more...
103 +See [authentication](https://docs.composio.dev/docs/authentication) for auth configs, custom OAuth apps, and connection lifecycle.
104
420 -## Environment Variables
105 +## Triggers
106
422 -- `COMPOSIO_API_KEY`: Your Composio API key
423 -- `COMPOSIO_BASE_URL`: Custom API base URL
424 -- `COMPOSIO_LOGGING_LEVEL`: Logging level (silent, error, warn, info, debug)
425 -- `DEVELOPMENT`: Development mode flag
426 -- `COMPOSIO_TOOLKIT_VERSION_<TOOLKITNAME>`: Version of the specific toolkit
427 -- `CI`: CI environment flag
428 -
429 -## MCP (Model Context Protocol)
430 -
431 -Create MCP servers for seamless integration with Claude, Cursor, and other MCP-compatible tools:
107 +Subscribe to events from connected apps (new email, new commit, and so on) and react to them:
108
109 ```python
110 from composio import Composio
111
112 composio = Composio()
113
438 -# Create MCP server
439 -mcp_server = composio.mcp.create(
440 - "my-mcp-server",
441 - toolkits=["github", "gmail"],
442 - manually_manage_connections=False
114 +trigger = composio.triggers.create(
115 + slug="GITHUB_COMMIT_EVENT",
116 + user_id="user_123",
117 + trigger_config={"owner": "composiohq", "repo": "composio"},
118 )
119
445 -# Generate server instance for a user
446 -server_instance = mcp_server.generate("user123")
447 -print(f"MCP Server URL: {server_instance['url']}")
448 -```
449 -
450 -## Supported AI Frameworks
451 -
452 -Composio provides dedicated integrations for popular AI frameworks:
120 +subscription = composio.triggers.subscribe()
121
454 -- **OpenAI** - Direct integration with OpenAI's API
455 -- **LangChain** - Tools and agents for LangChain workflows
456 -- **LangGraph** - State machine workflows with LangGraph
457 -- **CrewAI** - Multi-agent systems with CrewAI
458 -- **AutoGen** - Microsoft's AutoGen framework
459 -- **Anthropic** - Claude integration
460 -- **Google AI** - Gemini and other Google AI services
461 -- **LlamaIndex** - RAG and data framework integration
122 +@subscription.handle(trigger_id=trigger.trigger_id)
123 +def handle_event(data):
124 + print("Event received:", data)
125
463 -## Error Handling
464 -
465 -```python
466 -from composio import Composio
467 -from composio.exceptions import ComposioError, ApiKeyNotProvidedError
468 -
469 -try:
470 - composio = Composio() # Will raise ApiKeyNotProvidedError if no API key
471 - tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
472 -except ApiKeyNotProvidedError:
473 - print("Please provide COMPOSIO_API_KEY environment variable")
474 -except ComposioError as e:
475 - print(f"Composio error: {e}")
476 -except Exception as e:
477 - print(f"Unexpected error: {e}")
126 +subscription.wait_forever()
127 ```
128
480 -## Contributing
481 -
482 -We welcome contributions! Please see our [Contributing Guide](../CONTRIBUTING.md) for more details.
129 +`subscribe()` streams events over a WebSocket for local development. In production, register a webhook URL and parse deliveries with `composio.triggers.parse()`. See [setting up triggers](https://docs.composio.dev/docs/setting-up-triggers/creating-triggers).
130
484 -## License
131 +## Development
132
486 -Apache License 2.0
133 +This package lives in the [Composio SDK monorepo](https://github.com/ComposioHQ/composio) under `python/`. See the [contribution guidelines](https://github.com/ComposioHQ/composio/blob/next/CONTRIBUTING.md) to get set up.
134
135 ## Support
136
490 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
137 +- [Documentation](https://docs.composio.dev)
138 +- [Python SDK reference](https://docs.composio.dev/reference/sdk-reference/python)
139 +- [Discord community](https://discord.gg/composio)
140 +- [Open an issue](https://github.com/ComposioHQ/composio/issues)
141 +- [support@composio.dev](mailto:support@composio.dev)
python/providers/anthropic/README.md
+52 -50
@@ -1,71 +1,73 @@
1 -## 🚀🔗 Leveraging Claude with Composio
1 +# composio-anthropic
2
3 -Facilitate the integration of Claude with Composio to empower Claude models to directly interact with external applications, broadening their capabilities and application scope.
3 +Adapts Composio tools to the Claude Messages API tool format and executes the tool calls Claude returns.
4
5 -### Objective
6 -
7 -- **Automate starring a GitHub repository** using conversational instructions via Claude Function Calls.
8 -
9 -### Installation and Setup
10 -
11 -Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.
5 +## Installation
6
7 ```bash
14 -# Install Composio LangChain package
15 -pip install composio-claude
16 -
17 -# Connect your GitHub account
18 -composio-cli add github
19 -
20 -# View available applications you can connect with
21 -composio-cli show-apps
8 +pip install composio composio-anthropic anthropic
9 ```
10
24 -### Usage Steps
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `ANTHROPIC_API_KEY` in your environment.
12
26 -#### 1. Import Base Packages
13 +## Quickstart
14
28 -Prepare your environment by initializing necessary imports from Claude and setting up your client.
15 +`AnthropicProvider` is non-agentic: Claude returns `tool_use` blocks, `handle_tool_calls` executes them, and you send the results back as `tool_result` blocks.
16
17 ```python
18 +import json
19 import anthropic
20 +from composio import Composio
21 +from composio_anthropic import AnthropicProvider
22
33 -# Initialize Claude client
23 +composio = Composio(provider=AnthropicProvider())
24 client = anthropic.Anthropic()
35 -```
36 -
37 -### Step 2: Integrating GitHub Tools with Composio
38 -
39 -This step involves fetching and integrating GitHub tools provided by Composio, enabling enhanced functionality for LangChain operations.
40 -```python
41 -from composio_claude import App, ComposioToolSet
42 -
43 -toolset = ComposioToolSet()
44 -actions = toolset.get_tools(tools=App.GITHUB)
45 -```
25
47 -### Step 3: Agent Execution
26 +# Create a session for your user
27 +session = composio.create(user_id="user_123")
28 +tools = session.tools()
29
49 -This step involves configuring and executing the agent to carry out actions, such as starring a GitHub repository.
30 +messages = [
31 + {"role": "user", "content": "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"}
32 +]
33
51 -```python
52 -my_task = "Star a repo composiohq/composio on GitHub"
53 -
54 -# Create a chat completion request to decide on the action
55 -response = client.beta.tools.messages.create(
56 - model="claude-3-opus-20240229",
57 - max_tokens=1024,
58 - tools= actions,
59 - messages=[{"role": "user", "content": "Star me composiohq/composio repo in github."}],
34 +response = client.messages.create(
35 + model="claude-opus-4-6",
36 + max_tokens=4096,
37 + tools=tools,
38 + messages=messages,
39 )
61 -pprint(response)
40 +
41 +# Agentic loop: keep executing tool calls until the model responds with text
42 +while response.stop_reason == "tool_use":
43 + tool_use_blocks = [block for block in response.content if block.type == "tool_use"]
44 + results = composio.provider.handle_tool_calls(user_id="user_123", response=response)
45 + messages.append({"role": "assistant", "content": response.content})
46 + messages.append({
47 + "role": "user",
48 + "content": [
49 + {"type": "tool_result", "tool_use_id": tool_use_blocks[i].id, "content": json.dumps(result)}
50 + for i, result in enumerate(results)
51 + ]
52 + })
53 + response = client.messages.create(
54 + model="claude-opus-4-6",
55 + max_tokens=4096,
56 + tools=tools,
57 + messages=messages,
58 + )
59 +
60 +# Print final response
61 +for block in response.content:
62 + if block.type == "text":
63 + print(block.text)
64 ```
65
64 -### Step 4: Validate Execution Response
66 +`handle_tool_calls` extracts every `tool_use` block from the response, executes the matching Composio tools, and returns the raw results in order. Claude occasionally emits tool input as a JSON string instead of an object; the provider normalizes this before execution.
67
66 -Execute the following code to validate the response, ensuring that the intended task has been successfully completed.
68 +Building on the Claude Agent SDK instead of the Messages API? Use [`composio-claude-agent-sdk`](../claude_agent_sdk).
69
68 -```python
69 -result = toolset.handle_tool_calls(response)
70 -pprint(result)
71 -```
70 +## Links
71 +
72 +- Anthropic provider docs: https://docs.composio.dev/docs/providers/anthropic
73 +- Composio docs: https://docs.composio.dev
python/providers/autogen/README.md
+61 -1
@@ -1 +1,61 @@
1 -## 🚀🔗 Integrating Composio with Autogen SDK
1 +# composio-autogen
2 +
3 +Adapts Composio tools to AutoGen `FunctionTool` objects and registers them with your caller and executor agents, so your AutoGen agents can take action across 1000+ apps.
4 +
5 +## Installation
6 +
7 +```bash
8 +pip install composio composio-autogen autogen-agentchat
9 +```
10 +
11 +Set `COMPOSIO_API_KEY` (from the [dashboard](https://dashboard.composio.dev/settings)) and `OPENAI_API_KEY` in your environment.
12 +
13 +## Quickstart
14 +
15 +```python
16 +from autogen import AssistantAgent, UserProxyAgent
17 +from composio import Composio
18 +from composio_autogen import AutogenProvider
19 +
20 +composio = Composio(provider=AutogenProvider())
21 +
22 +# Each session is scoped to one of your users
23 +session = composio.create(user_id="user_123")
24 +tools = session.tools()
25 +
26 +chatbot = AssistantAgent(
27 + "chatbot",
28 + system_message="Reply TERMINATE when the task is done or when user's content is empty",
29 + llm_config={"config_list": [{"model": "gpt-5.2"}]},
30 +)
31 +
32 +user_proxy = UserProxyAgent(
33 + "user_proxy",
34 + is_termination_msg=lambda msg: "TERMINATE" in (msg.get("content", "") or ""),
35 + human_input_mode="NEVER",
36 + code_execution_config={"use_docker": False},
37 +)
38 +
39 +# Register tools with both agents
40 +composio.provider.register_tools(caller=chatbot, executor=user_proxy, tools=tools)
41 +
42 +response = user_proxy.initiate_chat(
43 + chatbot,
44 + message="Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
45 +)
46 +
47 +print(response.chat_history)
48 +```
49 +
50 +For multi-turn use, store `session.session_id` and reuse it with `composio.use(session_id)` instead of calling `create()` again.
51 +
52 +## Provider specifics
53 +
54 +AutoGen needs tools registered with two agents, not passed once. Call `composio.provider.register_tools(caller=..., executor=..., tools=tools)`: the `caller` decides which tool to invoke, and the `executor` runs it. This method is unique to the AutoGen provider.
55 +
56 +AutoGen caps function names at 64 characters, so the provider hashes and truncates long tool slugs to stay under the limit. The registered name will not always match the original Composio slug.
57 +
58 +## Links
59 +
60 +- [AutoGen provider docs](https://docs.composio.dev/docs/providers/autogen)
61 +- [Composio documentation](https://docs.composio.dev)
python/providers/claude_agent_sdk/README.md
+37 -71
@@ -1,98 +1,64 @@
1 -# Composio Claude Code Agents Provider
1 +# composio-claude-agent-sdk
2
3 -Use Composio tools with the Claude Code Agents SDK.
3 +Adapts Composio tools to the [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/python), exposing them to Claude through an in-process MCP server.
4
5 ## Installation
6
7 -### Prerequisites
8 -
9 -1. **Claude Code CLI**: The Claude Agent SDK requires Claude Code to be installed:
10 -
11 - ```bash
12 - # macOS/Linux/WSL
13 - curl -fsSL https://claude.ai/install.sh | bash
14 -
15 - # or via Homebrew
16 - brew install --cask claude-code
17 -
18 - # or via npm
19 - npm install -g @anthropic-ai/claude-code
20 - ```
21 -
22 -2. **Anthropic API Key**: Set your API key as an environment variable:
23 - ```bash
24 - export ANTHROPIC_API_KEY="your-api-key"
25 - ```
26 -
27 -### Install the package
28 -
7 ```bash
30 -pip install composio-claude-agent-sdk
8 +pip install composio composio-claude-agent-sdk claude-agent-sdk
9 ```
10
33 -## Usage
11 +The Claude Agent SDK also requires the Claude Code CLI: `npm install -g @anthropic-ai/claude-code`.
12 +
13 +Set `COMPOSIO_API_KEY` (from the [dashboard](https://dashboard.composio.dev/settings)) and `ANTHROPIC_API_KEY` in your environment.
14 +
15 +## Quickstart
16
17 ```python
18 import asyncio
19 +
20 from composio import Composio
21 from composio_claude_agent_sdk import ClaudeAgentSDKProvider
39 -from claude_agent_sdk import query, ClaudeAgentOptions
22 +from claude_agent_sdk import (
23 + AssistantMessage,
24 + ClaudeAgentOptions,
25 + TextBlock,
26 + create_sdk_mcp_server,
27 + query,
28 +)
29
41 -# Initialize Composio with the Claude Code Agents provider
30 composio = Composio(provider=ClaudeAgentSDKProvider())
31
44 -async def main():
45 - # Get tools from Composio
46 - tools = composio.tools.get(
47 - user_id="default",
48 - toolkits=["gmail"],
49 - )
50 -
51 - # Create an MCP server configuration with the tools
52 - mcp_server = composio.provider.create_mcp_server(tools)
53 -
54 - # Run a Claude agent with access to Composio tools
55 - async for message in query(
56 - prompt="Fetch my latest email from Gmail",
57 - options=ClaudeAgentOptions(
58 - mcp_servers={"composio": mcp_server},
59 - permission_mode="bypassPermissions",
60 - ),
61 - ):
62 - if message.type == "assistant":
63 - print(message.message)
64 -
65 -asyncio.run(main())
66 -```
32 +# Each session is scoped to one of your users
33 +session = composio.create(user_id="user_123")
34 +tools = session.tools()
35
68 -## API Reference
36 +server = create_sdk_mcp_server(name="composio", version="1.0.0", tools=tools)
37
70 -### ClaudeCodeAgentsProvider
38
72 -The main provider class for integrating Composio tools with Claude Code Agents SDK.
39 +async def main():
40 + options = ClaudeAgentOptions(
41 + system_prompt="You are a helpful assistant. Use tools to complete tasks.",
42 + permission_mode="bypassPermissions",
43 + mcp_servers={"composio": server},
44 + )
45 + async for message in query(prompt="Summarize my emails from today", options=options):
46 + if isinstance(message, AssistantMessage):
47 + for block in message.content:
48 + if isinstance(block, TextBlock):
49 + print(block.text)
50
74 -#### Constructor Options
51
76 -```python
77 -ClaudeCodeAgentsProvider(
78 - server_name: str = "composio", # Name for the MCP server
79 - server_version: str = "1.0.0", # Version for the MCP server
80 -)
52 +asyncio.run(main())
53 ```
54
83 -#### Methods
84 -
85 -- `wrap_tool(tool, execute_tool)` - Wraps a single Composio tool as a Claude Agent SDK MCP tool
86 -- `wrap_tools(tools, execute_tool)` - Wraps multiple Composio tools
87 -- `create_mcp_server(wrapped_tools)` - Creates an MCP server configuration from wrapped tools
55 +For multi-turn use, store `session.session_id` and reuse it with `composio.use(session_id)` instead of calling `create()` again.
56
89 -## Environment Variables
57 +## How tools are exposed
58
91 -- `COMPOSIO_API_KEY` - Your Composio API key (get one at https://app.composio.dev)
92 -- `ANTHROPIC_API_KEY` - Your Anthropic API key (get one at https://console.anthropic.com)
59 +`session.tools()` returns `SdkMcpTool` objects that plug straight into `create_sdk_mcp_server`. The provider also ships `composio.provider.create_mcp_server(tools)` if you prefer a preconfigured server (name `composio`, customizable via `ClaudeAgentSDKProvider(server_name=..., server_version=...)`).
60
61 ## Links
62
96 -- [Composio Documentation](https://docs.composio.dev)
97 -- [Claude Agent SDK Documentation](https://platform.claude.com/docs/en/agent-sdk/python)
98 -- [GitHub Repository](https://github.com/ComposioHQ/composio)
63 +- [Quickstart](https://docs.composio.dev/docs/quickstart)
64 +- [Composio documentation](https://docs.composio.dev)
python/providers/crewai/README.md
+65 -1
@@ -1 +1,65 @@
1 -# CrewAI plugin
\ No newline at end of file
1 +# composio-crewai
2 +
3 +Adapts Composio tools to CrewAI's `BaseTool` format so your crew's agents can act across 1000+ apps through a single Composio session.
4 +
5 +## Installation
6 +
7 +```bash
8 +pip install composio composio-crewai crewai
9 +```
10 +
11 +Set `COMPOSIO_API_KEY` (get one from [dashboard.composio.dev/settings](https://dashboard.composio.dev/settings)) and `OPENAI_API_KEY` in your environment:
12 +
13 +```bash
14 +export COMPOSIO_API_KEY=xxxxxxxxx
15 +export OPENAI_API_KEY=xxxxxxxxx
16 +```
17 +
18 +## Quickstart
19 +
20 +Create a session for your user, fetch its tools, and pass them to an `Agent`. CrewAI runs the task end to end; each tool executes itself through Composio.
21 +
22 +```python
23 +from crewai import Agent, Crew, Task
24 +from composio import Composio
25 +from composio_crewai import CrewAIProvider
26 +
27 +composio = Composio(provider=CrewAIProvider())
28 +
29 +# Each session is scoped to one of your users
30 +session = composio.create(user_id="user_123")
31 +tools = session.tools()
32 +
33 +agent = Agent(
34 + role="Email Agent",
35 + goal="Send emails on behalf of the user",
36 + backstory="You are an AI agent that sends emails using Gmail.",
37 + tools=tools,
38 + llm="gpt-5.2",
39 +)
40 +
41 +task = Task(
42 + description="Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
43 + agent=agent,
44 + expected_output="Confirmation that the email was sent",
45 +)
46 +
47 +crew = Crew(agents=[agent], tasks=[task])
48 +result = crew.kickoff()
49 +print(result)
50 +```
51 +
52 +## Error handling
53 +
54 +Each Composio tool becomes a CrewAI `BaseTool` whose `args_schema` is built from the tool's input schema, so CrewAI validates arguments before running anything. When validation fails, the tool does not raise; it returns a structured result:
55 +
56 +```python
57 +{"successful": False, "error": "<validation message>", "data": None}
58 +```
59 +
60 +Check `successful` in your task output instead of wrapping calls in `try`/`except`.
61 +
62 +## Links
63 +
64 +- [CrewAI provider docs](https://docs.composio.dev/docs/providers/crewai)
65 +- [Composio documentation](https://docs.composio.dev)
python/providers/gemini/README.md
+27 -51
@@ -1,72 +1,48 @@
1 -## 🚀🔗 Integrating Composio with Google's Gemini SDK
1 +# composio-gemini
2
3 -Streamline the integration of Composio with Google AI Python to enhance the capabilities of Gemini models, allowing them to interact directly with external applications and expanding their operational scope.
3 +Adapts Composio tools to the [`google-genai`](https://pypi.org/project/google-genai/) SDK as Python callables compatible with Gemini's Automatic Function Calling.
4
5 -### Objective
6 -
7 -- **Automate starring a GitHub repository** using conversational instructions via Google AI Python's Function Calling feature.
8 -
9 -### Installation and Setup
10 -
11 -Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.
5 +## Installation
6
7 ```bash
14 -# Install Composio Gemini package
15 -pip install composio-gemini
16 -
17 -# Connect your GitHub account
18 -composio add github
19 -
20 -# View available applications you can connect with
21 -composio apps
8 +pip install composio composio-gemini google-genai
9 ```
10
24 -### Usage Steps
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `GOOGLE_API_KEY` (from https://aistudio.google.com/apikey) in your environment.
12
26 -#### 1. Import Base Packages
13 +## Quickstart
14
28 -Prepare your environment by initializing necessary imports from Google AI Python and setting up your client.
15 +`GeminiProvider` wraps each Composio tool as a typed Python callable. Pass the callables to `GenerateContentConfig(tools=...)` and the `google-genai` SDK derives function declarations from their signatures and executes tool calls automatically inside the chat loop; there is no manual tool-call handling.
16
17 ```python
18 +from composio import Composio
19 +from composio_gemini import GeminiProvider
20 from google import genai
32 -
33 -# Create google client
34 -client = genai.Client()
35 -```
36 -
37 -### Step 2: Integrating GitHub Tools with Composio
38 -
39 -This step involves fetching and integrating GitHub tools provided by Composio, enabling enhanced functionality for Google AI Python operations.
40 -```python
21 from google.genai import types
22
43 -from composio_gemini import Action, ComposioToolSet
23 +composio = Composio(provider=GeminiProvider())
24 +client = genai.Client()
25
45 -# Create composio client
46 -toolset = ComposioToolSet()
26 +# Create a session for your user
27 +session = composio.create(user_id="user_123")
28 +tools = session.tools()
29
48 -# Create tools
49 -tools = toolset.get_tools(
50 - actions=[
51 - Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER,
52 - ]
53 -)
30 +config = types.GenerateContentConfig(tools=tools)
31 +chat = client.chats.create(model="gemini-3-pro-preview", config=config)
32
55 -# Create genai client config
56 -config = types.GenerateContentConfig(
57 - tools=tools, # type: ignore
33 +response = chat.send_message(
34 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"
35 )
36 +print(response.text)
37 ```
38
61 -### Step 3: Agent Execution
39 +If you disable Automatic Function Calling and handle function calls yourself, `composio.provider.handle_response(response)` executes the function calls in a Gemini response and returns `Part` objects ready to send back.
40
63 -This step involves configuring and executing the agent to carry out actions, such as starring a GitHub repository.
41 +## composio-gemini vs composio-google
42
65 -```python
66 -# Use the chat interface.
67 -chat = client.chats.create(model="gemini-2.0-flash", config=config)
68 -response = chat.send_message(
69 - "Can you star composiohq/composio repository on github",
70 -)
71 -print(response.text)
72 -```
43 +This package targets the `google-genai` SDK (`from google import genai`). [`composio-google`](../google) targets the older Vertex AI SDK (`vertexai.generative_models`). For new projects, Google recommends `google-genai`, so use this package.
44 +
45 +## Links
46 +
47 +- Google provider docs: https://docs.composio.dev/docs/providers/google
48 +- Composio docs: https://docs.composio.dev
python/providers/google/README.md
+35 -45
@@ -1,66 +1,56 @@
1 -## 🚀🔗 Integrating Composio with Google AI Python
1 +# composio-google
2
3 -Streamline the integration of Composio with Google AI Python to enhance the capabilities of Gemini models, allowing them to interact directly with external applications and expanding their operational scope.
3 +Adapts Composio tools to the Vertex AI SDK (`vertexai.generative_models`) as `FunctionDeclaration` objects for Gemini function calling.
4
5 -### Objective
6 -
7 -- **Automate starring a GitHub repository** using conversational instructions via Google AI Python's Function Calling feature.
8 -
9 -### Installation and Setup
10 -
11 -Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.
5 +## Installation
6
7 ```bash
14 -# Install Composio LangChain package
15 -pip install composio-google
16 -
17 -# Connect your GitHub account
18 -composio-cli add github
19 -
20 -# View available applications you can connect with
21 -composio-cli show-apps
8 +pip install composio composio-google google-cloud-aiplatform
9 ```
10
24 -### Usage Steps
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) in your environment. Vertex AI authenticates with Google Cloud credentials; run `gcloud auth application-default login` or set `GOOGLE_APPLICATION_CREDENTIALS`.
12
26 -#### 1. Import Base Packages
13 +## Quickstart
14
28 -Prepare your environment by initializing necessary imports from Google AI Python and setting up your client.
15 +`GoogleProvider` is non-agentic: the model returns function calls, and `composio.provider.handle_response` executes every function call in the response and returns the results.
16
17 ```python
31 -from vertexai.generative_models import GenerativeModel
32 -
33 -# Initialize Google AI Python client
34 -model = GenerativeModel("gemini-pro")
35 -```
18 +import vertexai
19 +from vertexai.generative_models import GenerativeModel, Tool
20
37 -### Step 2: Integrating GitHub Tools with Composio
21 +from composio import Composio
22 +from composio_google import GoogleProvider
23
39 -This step involves fetching and integrating GitHub tools provided by Composio, enabling enhanced functionality for Google AI Python operations.
40 -```python
41 -from composio_google import App, ComposioToolset
24 +vertexai.init(project="your-gcp-project", location="us-central1")
25
43 -toolset = ComposioToolset()
44 -actions = toolset.get_tools(apps=[App.GITHUB])
45 -```
26 +composio = Composio(provider=GoogleProvider())
27
47 -### Step 3: Agent Execution
28 +# Create a session for your user
29 +session = composio.create(user_id="user_123")
30 +tools = session.tools()
31
49 -This step involves configuring and executing the agent to carry out actions, such as starring a GitHub repository.
32 +model = GenerativeModel(
33 + "gemini-2.0-flash",
34 + tools=[Tool(function_declarations=tools)],
35 +)
36 +chat = model.start_chat()
37
51 -```python
52 -# Define task
53 -task = "Star a repo composiohq/composio on GitHub"
38 +response = chat.send_message(
39 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"
40 +)
41
55 -# Send a message to the model
56 -response = chat.send_message(task)
42 +# Execute the function calls the model requested
43 +results = composio.provider.handle_response(user_id="user_123", response=response)
44 +print(results)
45 ```
46
59 -### Step 4: Validate Execution Response
47 +To execute a single call instead of the whole response, use `composio.provider.execute_tool_call(user_id="user_123", function_call=part.function_call)`.
48
61 -Execute the following code to validate the response, ensuring that the intended task has been successfully completed.
49 +## composio-google vs composio-gemini
50
63 -```python
64 -result = composio_toolset.handle_response(response)
65 -print("Function call result:", result)
66 -```
51 +This package targets the Vertex AI SDK (`vertexai.generative_models`, installed via `google-cloud-aiplatform`). [`composio-gemini`](../gemini) targets the newer `google-genai` SDK with Automatic Function Calling. For new projects, use `composio-gemini`.
52 +
53 +## Links
54 +
55 +- Google provider docs: https://docs.composio.dev/docs/providers/google
56 +- Composio docs: https://docs.composio.dev
python/providers/google_adk/README.md
+69 -1
@@ -1,2 +1,70 @@
1 -# Composio Provider For Google ADK
1 +# composio-google-adk
2
3 +Adapts Composio tools to [Google ADK](https://google.github.io/adk-docs/) `FunctionTool` objects, so your ADK agents can take action across 1000+ apps.
4 +
5 +## Installation
6 +
7 +```bash
8 +pip install composio composio-google-adk google-adk
9 +```
10 +
11 +Set `COMPOSIO_API_KEY` (from the [dashboard](https://dashboard.composio.dev/settings)) and `GOOGLE_API_KEY` in your environment.
12 +
13 +## Quickstart
14 +
15 +```python
16 +from composio import Composio
17 +from composio_google_adk import GoogleAdkProvider
18 +from google.adk.agents import Agent
19 +from google.adk.runners import Runner
20 +from google.adk.sessions import InMemorySessionService
21 +from google.genai import types
22 +
23 +composio = Composio(provider=GoogleAdkProvider())
24 +
25 +# Each Composio session is scoped to one of your users
26 +composio_session = composio.create(user_id="user_123")
27 +tools = composio_session.tools()
28 +
29 +agent = Agent(
30 + name="personal_assistant",
31 + model="gemini-2.0-flash",
32 + instruction="You are a helpful assistant. Use Composio tools to take action.",
33 + tools=tools,
34 +)
35 +
36 +session_service = InMemorySessionService()
37 +session_service.create_session_sync(
38 + app_name="personal_assistant",
39 + user_id="user_123",
40 + session_id="1234",
41 +)
42 +runner = Runner(
43 + agent=agent,
44 + app_name="personal_assistant",
45 + session_service=session_service,
46 +)
47 +
48 +events = runner.run(
49 + user_id="user_123",
50 + session_id="1234",
51 + new_message=types.Content(
52 + role="user",
53 + parts=[types.Part(text="Star the repository composiohq/composio on GitHub")],
54 + ),
55 +)
56 +for event in events:
57 + if event.is_final_response() and event.content and event.content.parts:
58 + print(event.content.parts[0].text)
59 +```
60 +
61 +For multi-turn use, store `composio_session.session_id` and reuse it with `composio.use(session_id)` instead of calling `create()` again.
62 +
63 +## How tools are wrapped
64 +
65 +`GoogleAdkProvider` turns each Composio tool into a `google.adk.tools.FunctionTool` with a Python signature and docstring generated from the tool's schema, so ADK can pass them to Gemini as regular function declarations.
66 +
67 +## Links
68 +
69 +- [Quickstart](https://docs.composio.dev/docs/quickstart)
70 +- [Composio documentation](https://docs.composio.dev)
python/providers/langchain/README.md
+63 -1
@@ -1 +1,63 @@
1 -# Langchain provider for composio SDK
\ No newline at end of file
1 +# composio-langchain
2 +
3 +Adapts Composio tools to LangChain's `StructuredTool` format so a LangChain agent can call 1000+ apps through a single Composio session.
4 +
5 +## Installation
6 +
7 +```bash
8 +pip install composio composio-langchain langchain langchain-openai
9 +```
10 +
11 +Set `COMPOSIO_API_KEY` (get one from [dashboard.composio.dev/settings](https://dashboard.composio.dev/settings)) and `OPENAI_API_KEY` in your environment:
12 +
13 +```bash
14 +export COMPOSIO_API_KEY=xxxxxxxxx
15 +export OPENAI_API_KEY=xxxxxxxxx
16 +```
17 +
18 +## Quickstart
19 +
20 +Create a session for your user, fetch its tools, and hand them to `create_agent`. LangChain runs the tool loop; each tool executes itself through Composio.
21 +
22 +```python
23 +from composio import Composio
24 +from composio_langchain import LangchainProvider
25 +from langchain.agents import create_agent
26 +from langchain_openai import ChatOpenAI
27 +
28 +composio = Composio(provider=LangchainProvider())
29 +llm = ChatOpenAI(model="gpt-5.2")
30 +
31 +# Each session is scoped to one of your users
32 +session = composio.create(user_id="user_123")
33 +tools = session.tools()
34 +
35 +agent = create_agent(tools=tools, model=llm)
36 +result = agent.invoke(
37 + {
38 + "messages": [
39 + (
40 + "user",
41 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
42 + )
43 + ]
44 + }
45 +)
46 +
47 +print(result["messages"][-1].content)
48 +```
49 +
50 +## Error handling
51 +
52 +Each wrapped tool builds its `args_schema` from the Composio tool's input schema. When argument validation fails, the tool does not raise; it returns a structured result:
53 +
54 +```python
55 +{"successful": False, "error": "<validation message>", "data": None}
56 +```
57 +
58 +Check `successful` in tool output instead of wrapping calls in `try`/`except`.
59 +
60 +## Links
61 +
62 +- [LangChain provider docs](https://docs.composio.dev/docs/providers/langchain)
63 +- [Composio documentation](https://docs.composio.dev)
python/providers/langgraph/README.md
+39 -95
@@ -1,119 +1,63 @@
1 -## 🦜🕸️ Using Composio With LangGraph
1 +# composio-langgraph
2
3 -Integrate Composio with LangGraph Agentic workflows & enable them to interact seamlessly with external apps, enhancing their functionality and reach.
3 +Adapts Composio tools to LangChain's `StructuredTool` format for use in LangGraph agents and graph workflows, giving them access to 1000+ apps through a single Composio session.
4
5 -### Goal
6 -
7 -- **Star a repository on GitHub** using natural language commands through a LangGraph Agent.
8 -
9 -### Installation and Setup
10 -
11 -Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.
5 +## Installation
6
7 ```bash
14 -# Install Composio LangGraph package
15 -pip install composio-langgraph
8 +pip install composio composio-langgraph langgraph langchain langchain-openai
9 +```
10
17 -# Connect your GitHub account
18 -composio-cli add github
11 +Set `COMPOSIO_API_KEY` (get one from [dashboard.composio.dev/settings](https://dashboard.composio.dev/settings)) and `OPENAI_API_KEY` in your environment:
12
20 -# View available applications you can connect with
21 -composio-cli show-apps
13 +```bash
14 +export COMPOSIO_API_KEY=xxxxxxxxx
15 +export OPENAI_API_KEY=xxxxxxxxx
16 ```
17
24 -### Usage Steps
18 +## Quickstart
19
26 -#### 1. Import Base Packages
27 -
28 -Prepare your environment by initializing necessary imports from LangGraph & LangChain for setting up your agent.
20 +Create a session for your user, fetch its tools, and hand them to your agent. The wrapped tools also work anywhere LangGraph accepts LangChain tools, such as a `ToolNode` in a custom graph.
21
22 ```python
31 -from typing import Literal
32 -
23 +from composio import Composio
24 +from composio_langgraph import LanggraphProvider
25 +from langchain.agents import create_agent
26 from langchain_openai import ChatOpenAI
34 -from langgraph.graph import MessagesState, StateGraph
35 -from langgraph.prebuilt import ToolNode
36 -```
37 -
38 -#### 2. Fetch GitHub LangGraph Tools via Composio
27
40 -Access GitHub tools provided by Composio for LangGraph, initialize a `ToolNode` with necessary tools obtaned from `ComposioToolSet`.
28 +composio = Composio(provider=LanggraphProvider())
29 +llm = ChatOpenAI(model="gpt-5.2")
30
42 -```python
43 -from composio_langgraph import Action, ComposioToolSet
44 -
45 -# Initialize the toolset for GitHub
46 -composio_toolset = ComposioToolSet()
47 -tools = composio_toolset.get_actions(
48 - actions=[
49 - Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER,
50 - Action.GITHUB_USERS_GET_AUTHENTICATED,
51 - ])
52 -tool_node = ToolNode(tools)
53 -```
54 -
55 -#### 3. Prepare the model
31 +# Each session is scoped to one of your users
32 +session = composio.create(user_id="user_123")
33 +tools = session.tools()
34
57 -Initialize the LLM class and bind obtained tools to the model.
35 +agent = create_agent(tools=tools, model=llm)
36 +result = agent.invoke(
37 + {
38 + "messages": [
39 + (
40 + "user",
41 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
42 + )
43 + ]
44 + }
45 +)
46
59 -```python
60 -model = ChatOpenAI(temperature=0, streaming=True)
61 -model_with_tools = model.bind_tools(functions)
47 +print(result["messages"][-1].content)
48 ```
63 -#### 4. Define the Graph Nodes
49
65 -LangGraph expects you to define different nodes of the agentic workflow as separate functions. Here we define a node for calling the LLM model.
50 +## Error handling
51
67 -```python
68 -def call_model(state: MessagesState):
69 - messages = state["messages"]
70 - response = model_with_tools.invoke(messages)
71 - return {"messages": [response]}
72 -```
73 -#### 5. Define the Graph Nodes and Edges
74 -
75 -To establish the agent's workflow, we begin by initializing the workflow with `agent` and `tools` node, followed by specifying the connecting edges between nodes, finally compiling the workflow. These edges can be straightforward or conditional, depending on the workflow requirements.
52 +Each wrapped tool builds its `args_schema` from the Composio tool's input schema. When argument validation fails, the tool does not raise; it returns a structured result:
53
54 ```python
78 -def should_continue(state: MessagesState) -> Literal["tools", "__end__"]:
79 - messages = state["messages"]
80 - last_message = messages[-1]
81 - if last_message.tool_calls:
82 - return "tools"
83 - return "__end__"
84 -
85 -
86 -workflow = StateGraph(MessagesState)
87 -
88 -# Define the two nodes we will cycle between
89 -workflow.add_node("agent", call_model)
90 -workflow.add_node("tools", tool_node)
91 -
92 -workflow.add_edge("__start__", "agent")
93 -workflow.add_conditional_edges(
94 - "agent",
95 - should_continue,
96 -)
97 -workflow.add_edge("tools", "agent")
98 -
99 -app = workflow.compile()
55 +{"successful": False, "error": "<validation message>", "data": None}
56 ```
101 -#### 6. Invoke & Check Response
57
103 -After the compilation of workflow, we invoke the LLM with a task, and stream the response.
58 +Check `successful` in tool output instead of wrapping calls in `try`/`except`.
59
105 -```python
106 -for chunk in app.stream(
107 - {
108 - "messages": [
109 - (
110 - "human",
111 - # "Star the Github Repository composiohq/composio",
112 - "Get my information.",
113 - )
114 - ]
115 - },
116 - stream_mode="values",
117 -):
118 - chunk["messages"][-1].pretty_print()
119 -```
60 +## Links
61 +
62 +- [LangChain provider docs](https://docs.composio.dev/docs/providers/langchain) (covers LangGraph)
63 +- [Composio documentation](https://docs.composio.dev)
python/providers/llamaindex/README.md
+52 -3
@@ -1,4 +1,53 @@
1 -## Using Composio With LLamaIndex
1 +# composio-llamaindex
2
3 -Integrate Composio with LLamaIndex Agentic workflows & enable them to interact seamlessly
4 -with external apps, enhancing their functionality and reach.
3 +Adapts Composio tools to LlamaIndex's `FunctionTool` format so a LlamaIndex agent can call 1000+ apps through a single Composio session.
4 +
5 +## Installation
6 +
7 +```bash
8 +pip install composio composio-llamaindex llama-index llama-index-llms-openai
9 +```
10 +
11 +Set `COMPOSIO_API_KEY` (get one from [dashboard.composio.dev/settings](https://dashboard.composio.dev/settings)) and `OPENAI_API_KEY` in your environment:
12 +
13 +```bash
14 +export COMPOSIO_API_KEY=xxxxxxxxx
15 +export OPENAI_API_KEY=xxxxxxxxx
16 +```
17 +
18 +## Quickstart
19 +
20 +Create a session for your user, fetch its tools, and hand them to a `FunctionAgent`. LlamaIndex drives the tool calls; each tool executes itself through Composio.
21 +
22 +```python
23 +import asyncio
24 +
25 +from composio import Composio
26 +from composio_llamaindex import LlamaIndexProvider
27 +from llama_index.core.agent.workflow import FunctionAgent
28 +from llama_index.llms.openai import OpenAI
29 +
30 +composio = Composio(provider=LlamaIndexProvider())
31 +llm = OpenAI(model="gpt-5.2")
32 +
33 +# Each session is scoped to one of your users
34 +session = composio.create(user_id="user_123")
35 +tools = session.tools()
36 +
37 +agent = FunctionAgent(tools=tools, llm=llm)
38 +
39 +
40 +async def main():
41 + result = await agent.run(
42 + user_msg="Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"
43 + )
44 + print(result)
45 +
46 +
47 +asyncio.run(main())
48 +```
49 +
50 +## Links
51 +
52 +- [LlamaIndex provider docs](https://docs.composio.dev/docs/providers/llamaindex)
53 +- [Composio documentation](https://docs.composio.dev)
python/providers/openai/README.md
+52 -55
@@ -1,73 +1,70 @@
1 -## 🚀🔗 Leveraging OpenAI with Composio
1 +# composio-openai
2
3 -Facilitate the integration of OpenAI with Composio to empower OpenAI models to directly interact with external applications, broadening their capabilities and application scope.
3 +Adapts Composio tools to OpenAI function calling, for both the Responses API and the Chat Completions API.
4
5 -### Objective
6 -
7 -- **Automate starring a GitHub repository** using conversational instructions via OpenAI Function Calls.
8 -
9 -### Installation and Setup
10 -
11 -Ensure you have the necessary packages installed and connect your GitHub account to allow your agents to utilize GitHub functionalities.
5 +## Installation
6
7 ```bash
14 -# Install Composio LangChain package
15 -pip install composio-openai
16 -
17 -# Connect your GitHub account
18 -composio-cli add github
19 -
20 -# View available applications you can connect with
21 -composio-cli show-apps
8 +pip install composio composio-openai openai
9 ```
10
24 -### Usage Steps
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `OPENAI_API_KEY` in your environment.
12
26 -#### 1. Import Base Packages
13 +## Quickstart
14
28 -Prepare your environment by initializing necessary imports from OpenAI and setting up your client.
15 +This package exports two providers: `OpenAIResponsesProvider` for the [Responses API](https://platform.openai.com/docs/api-reference/responses) and `OpenAIProvider` for Chat Completions. Both are non-agentic: the model returns tool calls, you execute them with `handle_tool_calls`, and you feed the results back.
16
17 ```python
18 +import json
19 from openai import OpenAI
32 -
33 -# Initialize OpenAI client
34 -openai_client = OpenAI()
35 -```
36 -
37 -### Step 2: Integrating GitHub Tools with Composio
38 -
39 -This step involves fetching and integrating GitHub tools provided by Composio, enabling enhanced functionality for LangChain operations.
40 -```python
41 -from composio_openai import App, ComposioToolSet
42 -
43 -toolset = ComposioToolSet()
44 -actions = toolset.get_tools(apps=[App.GITHUB])
45 -```
46 -
47 -### Step 3: Agent Execution
48 -
49 -This step involves configuring and executing the agent to carry out actions, such as starring a GitHub repository.
50 -
51 -```python
52 -my_task = "Star a repo composiohq/composio on GitHub"
53 -
54 -# Create a chat completion request to decide on the action
55 -response = openai_client.chat.completions.create(model="gpt-5",
56 - tools=actions, # Passing actions we fetched earlier.
57 - messages=[
58 - {"role": "system", "content": "You are a helpful assistant."},
59 - {"role": "user", "content": my_task}
20 +from composio import Composio
21 +from composio_openai import OpenAIResponsesProvider
22 +
23 +composio = Composio(provider=OpenAIResponsesProvider())
24 +client = OpenAI()
25 +
26 +# Create a session for your user
27 +session = composio.create(user_id="user_123")
28 +tools = session.tools()
29 +
30 +response = client.responses.create(
31 + model="gpt-5.2",
32 + tools=tools,
33 + input=[
34 + {
35 + "role": "user",
36 + "content": "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"
37 + }
38 + ]
39 +)
40 +
41 +# Agentic loop: keep executing tool calls until the model responds with text
42 +while True:
43 + tool_calls = [o for o in response.output if o.type == "function_call"]
44 + if not tool_calls:
45 + break
46 + results = composio.provider.handle_tool_calls(response=response, user_id="user_123")
47 + response = client.responses.create(
48 + model="gpt-5.2",
49 + tools=tools,
50 + previous_response_id=response.id,
51 + input=[
52 + {"type": "function_call_output", "call_id": tool_calls[i].call_id, "output": json.dumps(result)}
53 + for i, result in enumerate(results)
54 ]
55 )
56
63 -pprint(response)
57 +# Print final response
58 +for item in response.output:
59 + if item.type == "message":
60 + print(item.content[0].text)
61 ```
62
66 -### Step 4: Validate Execution Response
63 +## Chat Completions
64
68 -Execute the following code to validate the response, ensuring that the intended task has been successfully completed.
65 +`OpenAIProvider` targets `client.chat.completions.create` and is the Composio SDK default, so `Composio()` with no provider uses it. The loop is the same shape: call `handle_tool_calls` on each response, append the results as `tool` messages, and call the API again. See the [docs page](https://docs.composio.dev/docs/providers/openai) for the full example.
66
70 -```python
71 -result = toolset.handle_tool_calls(response)
72 -pprint(result)
73 -```
67 +## Links
68 +
69 +- OpenAI provider docs: https://docs.composio.dev/docs/providers/openai
70 +- Composio docs: https://docs.composio.dev
python/providers/openai_agents/README.md
+20 -39
@@ -1,60 +1,41 @@
1 -# Composio Integration for OpenAI Agents
1 +# composio-openai-agents
2
3 -This package integrates the OpenAI Agents framework with Composio, allowing you to use Composio's rich set of tools with the OpenAI Agents framework.
3 +Adapts Composio tools to the [OpenAI Agents](https://github.com/openai/openai-agents-python) framework's native tool format, so your agents can take action across 1000+ apps.
4
5 ## Installation
6
7 ```bash
8 -pip install composio_openai_agents
8 +pip install composio composio-openai-agents openai-agents
9 ```
10
11 -## Usage
11 +Set `COMPOSIO_API_KEY` (from the [dashboard](https://dashboard.composio.dev/settings)) and `OPENAI_API_KEY` in your environment.
12 +
13 +## Quickstart
14
15 ```python
14 -import asyncio
15 -import dotenv
16 +from composio import Composio
17 +from composio_openai_agents import OpenAIAgentsProvider
18 from agents import Agent, Runner
19
18 -from composio_openai_agents import Action, ComposioToolSet
19 -
20 -# Load environment variables from .env
21 -dotenv.load_dotenv()
20 +composio = Composio(provider=OpenAIAgentsProvider())
21
23 -# Initialize Composio toolset
24 -composio_toolset = ComposioToolSet()
22 +# Each session is scoped to one of your users
23 +session = composio.create(user_id="user_123")
24 +tools = session.tools()
25
26 -# Get all the tools
27 -tools = composio_toolset.get_tools(actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER])
28 -
29 -# Create an agent with the tools
26 agent = Agent(
31 - name="GitHub Agent",
32 - instructions="You are a helpful assistant that helps users with GitHub tasks.",
27 + name="Personal Assistant",
28 + instructions="You are a helpful assistant. Use Composio tools to take action.",
29 tools=tools,
30 )
31
36 -# Run the agent
37 -async def main():
38 - result = await Runner.run(agent, "Star the repository composiohq/composio on GitHub")
39 - print(result.final_output)
40 -
41 -asyncio.run(main())
32 +result = Runner.run_sync(starting_agent=agent, input="Summarize my emails from today")
33 +print(result.final_output)
34 ```
35
44 -## Features
45 -
46 -- Seamlessly integrate Composio's tools with OpenAI Agents
47 -- Access hundreds of pre-built API integrations
48 -- Maintain consistent schema formats between frameworks
49 -- Error handling for validation issues
50 -- Proper type annotations that work with mypy and pylance
51 -
52 -## Requirements
53 -
54 -- Python 3.9+
55 -- OpenAI Agents framework
56 -- Composio (with valid API key)
36 +By default a session gets meta tools that discover, authenticate, and execute app tools at runtime. For multi-turn use, store `session.session_id` and reuse it with `composio.use(session_id)` instead of calling `create()` again.
37
58 -## License
38 +## Links
39
60 -Apache 2.0
\ No newline at end of file
40 +- [Quickstart](https://docs.composio.dev/docs/quickstart)
41 +- [Composio documentation](https://docs.composio.dev)
ts/README.md
+54 -270
@@ -1,305 +1,89 @@
1 -# Composio SDK v3
1 +# Composio TypeScript workspace
2
3 -The Composio SDK is a powerful toolkit that enables you to integrate third-party tools and services into your applications. It helps you connect to various services (toolkits), execute tools, and manage user connections seamlessly.
3 +This directory contains the TypeScript half of the Composio SDK monorepo: the core SDK, provider adapters, the CLI, examples, and end-to-end tests. For an overview of Composio itself, start at the [root README](../README.md) and [docs.composio.dev](https://docs.composio.dev).
4
5 -## Features
6 -
7 -- Execute tools from various services (GitHub, Gmail, Slack, etc.)
8 -- Manage user connections to external services
9 -- Create session-scoped custom tools with your own logic
10 -- Integrate with AI providers like OpenAI
11 -- Powerful middleware and modifier support
12 -- Extensive error handling
13 -
14 -## Documentation
15 -
16 -The SDK is thoroughly documented in the [docs](./docs) directory:
17 -
18 -- [Overview](./docs/overview.md) - Introduction and key concepts
19 -- [Getting Started](./docs/getting-started.md) - Quick start guide
20 -- [Core Concepts](./docs/core-concepts.md) - Fundamental SDK concepts
21 -- [Configuration](./docs/internal/configuration.md) - Environment variables and SDK configuration
22 -
23 -### API Reference
24 -
25 -- [Composio Class](./docs/api/composio.md) - Main SDK class
26 -- [Tools](./docs/api/tools.md) - Listing, fetching, and executing tools
27 -- [Tool Router](./docs/api/tool-router.md) - Sessions, search, and custom tools
28 -- [Toolkits](./docs/api/toolkits.md) - Working with tool collections
29 -- [Connected Accounts](./docs/api/connected-accounts.md) - User authentication
30 -- [Auth Configs](./docs/api/auth-configs.md) - Authentication configuration
31 -- [Providers](./docs/api/providers.md) - AI integration options
32 -
33 -### Provider Documentation
34 -
35 -- [OpenAI Provider](./docs/providers/openai.md) - Using OpenAI with Composio
36 -- [Google Provider](./docs/providers/google.md) - Using Google GenAI with Composio
37 -- [Custom Providers](./docs/providers/custom.md) - Creating new providers
38 -
39 -### Advanced Topics
40 -
41 -- [Error Handling](./docs/advanced/error-handling.md) - Managing errors
42 -- [Middleware and Modifiers](./docs/advanced/modifiers.md) - Customizing tools
43 -- [Telemetry](./docs/advanced/telemetry.md) - SDK usage tracking
44 -- [Custom Providers](./docs/advanced/custom-providers.md) - Detailed provider guide
45 -
46 -### Internal Documentation
47 -
48 -For SDK maintainers and contributors:
49 -
50 -- [Configuration and Environment Variables](./docs/internal/configuration.md) - Detailed guide on SDK configuration
51 -- [Triggers Implementation](./docs/internal/triggers.md) - Internal workings of the trigger system
52 -
53 -## Installation
5 +If you just want to use the SDK:
6
7 ```bash
56 -# Using npm
8 npm install @composio/core
58 -
59 -# Using yarn
60 -yarn add @composio/core
61 -
62 -# Using pnpm
63 -pnpm add @composio/core
9 ```
10
66 -## Quick Start
67 -
11 ```typescript
12 import { Composio } from '@composio/core';
13
71 -// Initialize the SDK
72 -const composio = new Composio({
73 - apiKey: 'your-api-key',
74 -});
75 -
76 -// Get tools from a specific toolkit
77 -const tools = await composio.tools.get('default', {
78 - toolkits: ['github'],
79 -});
80 -
81 -// Get a specific tool
82 -const specificTool = await composio.tools.get('default', 'GITHUB_GET_REPOS');
83 -
84 -// Execute a tool
85 -const result = await composio.tools.execute('GITHUB_GET_REPO', {
86 - userId: 'default',
87 - arguments: {
88 - owner: 'composio',
89 - repo: 'sdk',
90 - },
91 -});
14 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
15
93 -console.log(result.data);
16 +const session = await composio.create('user_123');
17 +const tools = await session.tools();
18 ```
19
96 -## OpenAI Integration
97 -
98 -```typescript
99 -import { Composio } from '@composio/core';
100 -import OpenAI from 'openai';
101 -
102 -// Initialize Composio and OpenAI
103 -const composio = new Composio({
104 - apiKey: 'your-composio-api-key',
105 -});
106 -
107 -const openai = new OpenAI({
108 - apiKey: 'your-openai-api-key',
109 -});
20 +See the [`@composio/core` README](packages/core/README.md) and the [quickstart](https://docs.composio.dev/docs/quickstart) for the full flow, including provider setup for your agent framework.
21
111 -// Get GitHub tools
112 -const tools = await composio.tools.get('default', {
113 - toolkits: ['github'],
114 -});
22 +## Packages
23
24 +Published packages:
25
117 -// Create a chat completion with the tools
118 -const completion = await openai.chat.completions.create({
119 - model: 'gpt-4',
120 - messages: [
121 - { role: 'system', content: 'You are a helpful assistant with access to GitHub tools.' },
122 - { role: 'user', content: 'Find information about the Composio SDK repository' },
123 - ],
124 - tools, // Pass the tools to OpenAI
125 -});
26 +| Package | Description |
27 +|---------|-------------|
28 +| [`@composio/core`](packages/core) | The Composio SDK. Ships its TypeScript source and SDK docs so installed copies are inspectable by coding agents. |
29 +| [`@composio/slim`](packages/slim) | Same API as `@composio/core` without the packaged source and docs; smaller install. |
30 +| [`composio` CLI](packages/cli) | Standalone CLI binary: search, execute, and script tools from your shell. |
31 +| [`@composio/*` providers](packages/providers) | Adapters that format Composio tools for agent frameworks (OpenAI, Anthropic, Vercel AI SDK, LangChain, and more). See the [provider table](../README.md#providers). |
32 +| [`@composio/experimental`](packages/experimental) | Experimental integrations, currently the Pi provider. |
33 +| [`@composio/json-schema-to-zod`](packages/json-schema-to-zod) | JSON Schema to Zod conversion. |
34
127 -// If the model wants to use a tool
128 -if (completion.choices[0].message.tool_calls) {
129 - const toolCall = completion.choices[0].message.tool_calls[0];
130 - const args = JSON.parse(toolCall.function.arguments);
35 +Internal (unpublished) packages: `cli-keyring` and `cli-local-tools` support the CLI; `ts-builders` generates TypeScript source.
36
132 - // Execute the tool
133 - const result = await composio.tools.execute(toolCall.function.name, {
134 - userId: 'default',
135 - arguments: args,
136 - });
37 +## Layout
38
138 - console.log(result.data);
139 -}
39 +```text
40 +ts/
41 + packages/ Published and internal packages (see above)
42 + examples/ Runnable examples per feature and framework
43 + e2e-tests/ Runtime E2E tests (Node, Deno, Cloudflare Workers, CLI)
44 + docs/ Workspace SDK docs: API notes and internal guides
45 + scripts/ Build, validation, and scaffolding scripts
46 + vendor/ Read-only reference submodules; do not edit
47 ```
48
142 -## Creating Custom Tools
49 +## Development
50
144 -```typescript
145 -import { Composio, experimental_createTool } from '@composio/core';
146 -import { z } from 'zod';
147 -
148 -const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
149 -
150 -const weatherForecast = experimental_createTool('WEATHER_FORECAST', {
151 - name: 'Weather Forecast',
152 - description: 'Get the weather forecast for a location',
153 - inputParams: z.object({
154 - location: z.string().describe('The location to get the forecast for'),
155 - days: z.number().optional().default(3).describe('Number of days for the forecast'),
156 - }),
157 - execute: async (input) => {
158 - const { location, days = 3 } = input;
159 - const forecast = await getWeatherForecast(location, days);
160 - return { forecast };
161 - },
162 -});
51 +Commands run from the repository root. Install the pinned toolchain first:
52
164 -const session = await composio.create('default', {
165 - experimental: { customTools: [weatherForecast] },
166 -});
167 -
168 -const result = await session.execute('WEATHER_FORECAST', {
169 - location: 'San Francisco, CA',
170 -});
53 +```bash
54 +mise install
55 +pnpm install
56 ```
57
173 -## Project Structure
58 +Build and verify:
59
175 -```
176 -composio/
177 -├── packages/ # Main packages directory
178 -│ ├── core/ # Core SDK package
179 -│ └── providers/ # Provider implementations
180 -├── examples/ # Example implementations
181 -│ ├── connected-accounts/ # Connected accounts examples
182 -│ ├── langchain/ # LangChain integration examples
183 -│ ├── openai/ # OpenAI integration examples
184 -│ ├── modifiers/ # Modifiers examples
185 -│ ├── toolkits/ # Toolkits examples
186 -│ └── vercel/ # Vercel AI examples
187 -├── docs/ # Documentation
188 -├── scripts/ # Development and build scripts
189 -└── .github/ # GitHub configuration
60 +```bash
61 +pnpm build:packages # build all TS packages
62 +pnpm typecheck # typecheck all TS packages
63 +pnpm lint:packages # eslint over ts/packages
64 +pnpm test # package unit tests plus example validation
65 ```
66
192 -## Development Setup
67 +Runtime E2E suites (require credentials):
68
194 -1. **Prerequisites**
195 -
196 - - Node.js (Latest LTS version recommended)
197 - - [pnpm](https://pnpm.io/) (v10.8.0 or later)
198 - - [bun](https://bun.sh) for productivity (optional)
199 -
200 -2. **Clone and Install**
201 -
202 - ```bash
203 - git clone https://github.com/ComposioHQ/sdk-v3-ts.git
204 - cd composio
205 - pnpm install
206 - ```
207 -
208 -3. **Build**
209 -
210 - ```bash
211 - pnpm build
212 - ```
213 -
214 -4. **Development Commands**
215 -
216 - ```bash
217 - # Lint code
218 - pnpm lint
219 -
220 - # Fix linting issues
221 - pnpm lint:fix
222 -
223 - # Format code
224 - pnpm format
225 -
226 - # Create a new provider
227 - pnpm create:provider <provider-name> [--agentic]
228 -
229 - # Create a new example
230 - pnpm create:example <example-name>
231 -
232 - # Check peer dependencies
233 - pnpm check:peer-deps
234 -
235 - # Update peer dependencies
236 - pnpm update:peer-deps
237 - ```
238 -
239 -## Creating a New Example
240 -
241 -1. Use the create:example script:
242 -
243 - ```bash
244 - pnpm create:example my-example
245 - ```
246 -
247 -2. The script will create a new example in `examples/my-example` with:
248 -
249 - - `package.json` with minimal dependencies (`@composio/core` and `dotenv`)
250 - - `tsconfig.json` for TypeScript configuration
251 - - `.env.example` and `.env` files for environment variables
252 - - `src/index.ts` with basic Composio SDK setup
253 - - `README.md` with setup and usage instructions
254 - - Dependencies automatically installed
255 -
256 -3. Next steps after creation:
257 - - Edit `.env` and add your `COMPOSIO_API_KEY`
258 - - Customize `src/index.ts` with your example logic
259 - - Add any additional dependencies as needed
260 - - Run with `pnpm start` or `pnpm dev` (with file watching)
261 -
262 -## Creating a New Provider
263 -
264 -1. Use the create:provider script:
265 -
266 - ```bash
267 - pnpm create:provider my-provider [--agentic]
268 - ```
269 -
270 -2. The script will create a new provider in `packages/providers/my-provider` with:
271 -
272 - - Basic provider implementation
273 - - TypeScript configuration
274 - - Package configuration
275 - - README template
276 -
277 -3. Implement the required methods in `src/index.ts`:
278 - - For non-agentic providers: `wrapTool` and `wrapTools`
279 - - For agentic providers: `wrapTool`, `wrapTools`, and execution handlers
280 -
281 -## Release Process
282 -
283 -For detailed information about both automated and manual release processes, please refer to our [Release Process Documentation](./docs/internal/release.md).
284 -
285 -## Environment Variables
286 -
287 -- `COMPOSIO_API_KEY`: Your Composio API key
288 -- `COMPOSIO_BASE_URL`: Custom API base URL (optional)
289 -- `COMPOSIO_LOG_LEVEL`: Logging level (silent, error, warn, info, debug)
290 -- `COMPOSIO_DISABLE_TELEMETRY`: Disable telemetry when set to "true"
291 -- `COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>`: Specific version for a toolkit (e.g., `COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00`)
292 -- `DEVELOPMENT`: Development mode flag
293 -- `CI`: CI environment flag
294 -
295 -## Contributing
69 +```bash
70 +pnpm test:e2e:node
71 +pnpm test:e2e:deno
72 +pnpm test:e2e:cloudflare
73 +pnpm test:e2e:cli
74 +```
75
297 -We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for more details.
76 +Scaffolding:
77
299 -## License
78 +```bash
79 +pnpm create:provider <name> [--agentic] # new provider package
80 +pnpm create:example <name> # new example under ts/examples
81 +```
82
301 -ISC License
83 +Changesets are required for changes to published packages; see the [contribution guidelines](../CONTRIBUTING.md).
84
85 ## Support
86
305 -For support, please visit our [Documentation](./docs) or join our [Discord Community](https://discord.gg/composio).
87 +- [Documentation](https://docs.composio.dev)
88 +- [Discord community](https://discord.gg/composio)
89 +- [Open an issue](https://github.com/ComposioHQ/composio/issues)
ts/packages/core/README.md
+62 -247
@@ -1,304 +1,119 @@
1 -![Composio Banner](https://github.com/user-attachments/assets/9ba0e9c1-85a4-4b51-ae60-f9fe7992e819)
2 -
1 # @composio/core
2
5 -The core Composio SDK which allows users to interact with the Composio Platform. It provides a powerful and flexible way to manage and execute tools, handle authentication, and integrate with various platforms and frameworks.
6 -
7 -[Learn more about the SDK from our docs](https://docs.composio.dev)
3 +The Composio SDK for TypeScript. Create a session for one of your users, hand its tools to your agent, and let the agent take action across 1000+ apps with authentication handled for you.
4
9 -## Core Features
10 -
11 -- **Tools**: Manage and execute tools within the Composio ecosystem. Includes functionality to list, retrieve, and execute tools.
12 -- **Toolkits**: Organize and manage collections of tools for specific use cases.
13 -- **Triggers**: Create and manage event triggers that can execute tools based on specific conditions.
14 -- **AuthConfigs**: Configure authentication providers and settings.
15 -- **ConnectedAccounts**: Manage third-party service connections.
16 -- **ActionExecution**: Track and manage the execution of actions within the platform.
5 +Full documentation lives at [docs.composio.dev](https://docs.composio.dev). This package intentionally ships its TypeScript source and SDK docs so the installed package is inspectable by coding agents; if you want a smaller install with the same API, use [`@composio/slim`](https://www.npmjs.com/package/@composio/slim).
6
7 ## Installation
8
9 ```bash
10 npm install @composio/core
22 -# or
23 -yarn add @composio/core
24 -# or
25 -pnpm add @composio/core
11 ```
12
28 -## Getting Started
13 +## Quickstart
14
30 -### Basic Usage with OpenAI Provider
15 +Grab a `COMPOSIO_API_KEY` from the [dashboard](https://dashboard.composio.dev/settings), then create a session:
16
17 ```typescript
18 import { Composio } from '@composio/core';
34 -import { OpenAI } from 'openai';
35 -
36 -// Initialize OpenAI client
37 -const openai = new OpenAI({
38 - apiKey: process.env.OPENAI_API_KEY,
39 -});
40 -
41 -// Initialize Composio with your API key
42 -const composio = new Composio({
43 - apiKey: process.env.COMPOSIO_API_KEY,
44 -});
45 -
46 -async function main() {
47 - try {
48 - // Fetch tools - single tool or multiple tools
49 - const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
50 - // Or fetch multiple tools: await composio.tools.get('default', { toolkits: ['hackernews'] });
51 -
52 - const query = "Find information about the HackerNews user 'pg'";
53 -
54 - // Create chat completion with tools
55 - const response = await openai.chat.completions.create({
56 - model: 'gpt-4o',
57 - messages: [
58 - {
59 - role: 'system',
60 - content: 'You are a helpful assistant that can use tools to answer questions.',
61 - },
62 - { role: 'user', content: query },
63 - ],
64 - tools: tools,
65 - tool_choice: 'auto',
66 - });
67 -
68 - // Handle tool calls if the assistant decides to use them
69 - if (response.choices[0].message.tool_calls) {
70 - console.log(
71 - '🔧 Assistant is using tool:',
72 - response.choices[0].message.tool_calls[0].function.name
73 - );
74 -
75 - // Execute the tool call
76 - const toolResult = await composio.provider.executeToolCall(
77 - 'default',
78 - response.choices[0].message.tool_calls[0],
79 - {
80 - connectedAccountId: '', // Optional: specify connected account
81 - }
82 - );
83 -
84 - console.log('✅ Tool execution result:', JSON.parse(toolResult));
85 -
86 - // Get final response from assistant with tool result
87 - const finalResponse = await openai.chat.completions.create({
88 - model: 'gpt-4o',
89 - messages: [
90 - {
91 - role: 'system',
92 - content: 'You are a helpful assistant that can use tools to answer questions.',
93 - },
94 - { role: 'user', content: query },
95 - response.choices[0].message,
96 - {
97 - role: 'tool',
98 - tool_call_id: response.choices[0].message.tool_calls[0].id,
99 - content: toolResult,
100 - },
101 - ],
102 - });
103 -
104 - console.log('🤖 Final response:', finalResponse.choices[0].message.content);
105 - } else {
106 - console.log('🤖 Response:', response.choices[0].message.content);
107 - }
108 - } catch (error) {
109 - console.error('❌ Error:', error);
110 - }
111 -}
112 -
113 -main();
114 -```
115 -
116 -## Configuration
19
118 -The Composio constructor accepts the following configuration options:
20 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
21
120 -```typescript
121 -interface ComposioConfig {
122 - apiKey?: string | null; // Your Composio API key
123 - baseURL?: string | null; // Custom API base URL (optional)
124 - allowTracking?: boolean; // Enable/disable telemetry (default: true)
125 - dangerouslyAllowAutoUploadDownloadFiles?: boolean; // Opt-in for automatic file upload/download during tool execution (default: false)
126 - provider?: TProvider; // Custom provider (default: OpenAIProvider)
127 - host?: string; // Name of the host service which is using the SDK, this is for telemetry
128 - defaultHeaders?: ComposioRequestHeaders; // Request headers to be passed to the Composio API client
129 - disableVersionCheck?: boolean; // Whether to disable version check for the Composio SDK (default: false)
130 -}
131 -```
132 -
133 -## Modifiers
134 -
135 -Composio SDK supports powerful modifiers to transform tool schemas and execution behavior.
136 -
137 -### Schema Modifiers
138 -
139 -Schema modifiers allow you to transform tool schemas before they are used:
140 -
141 -```typescript
142 -const tools = await composio.tools.get('user123', 'HACKERNEWS_SEARCH_POSTS', {
143 - modifySchema: ({ toolSlug, toolkitSlug, schema }) => ({
144 - ...tool,
145 - description: 'Enhanced HackerNews search with additional features',
146 - inputParameters: {
147 - ...tool.inputParameters,
148 - limit: {
149 - type: 'number',
150 - description: 'Maximum number of posts to return',
151 - default: 10,
152 - },
153 - },
154 - }),
155 -});
22 +// Each session is scoped to one of your users
23 +const session = await composio.create('user_123');
24 +const tools = await session.tools();
25 ```
26
158 -### Execution Modifiers
27 +By default a session gives your agent a small set of meta tools that discover, authenticate, and execute app tools at runtime, so you never load hundreds of tool definitions into context. Without a provider configured, `session.tools()` returns OpenAI function-calling format.
28
160 -For agentic providers (like Vercel AI and Langchain), you can also modify tool execution behavior:
29 +Sessions persist on the server. For multi-turn conversations, store `session.sessionId` and reuse it instead of calling `create()` again:
30
31 ```typescript
163 -const tools = await composio.tools.get('user123', 'HACKERNEWS_SEARCH_POSTS', {
164 - // Transform input before execution
165 - beforeExecute: ({ toolSlug, toolkitSlug, params }) => ({
166 - ...params,
167 - arguments: {
168 - ...params.arguments,
169 - limit: Math.min((params.arguments?.limit as number) || 10, 100),
170 - },
171 - }),
172 -
173 - // Transform output after execution
174 - afterExecute: ({ toolSlug, toolkitSlug, result }) => ({
175 - ...response,
176 - data: {
177 - ...response.data,
178 - posts: (response.data?.posts as any[]).map(post => ({
179 - ...post,
180 - url: post.url || `https://news.ycombinator.com/item?id=${post.id}`,
181 - })),
182 - },
183 - }),
184 -});
32 +const session = await composio.use(sessionId);
33 ```
34
187 -## Connected Accounts
35 +See [what a session is](https://docs.composio.dev/docs/how-composio-works) and [configuring sessions](https://docs.composio.dev/docs/configuring-sessions) for restricting toolkits, auth configs, and connected accounts.
36
189 -Composio SDK provides a powerful way to manage third-party service connections through Connected Accounts. This feature allows you to authenticate with various services and maintain those connections.
37 +## Providers
38
191 -### Creating a Connected Account
39 +A provider formats session tools for your agent framework and wires up execution:
40
41 ```typescript
42 import { Composio } from '@composio/core';
43 +import { OpenAIAgentsProvider } from '@composio/openai-agents';
44
196 -const composio = new Composio({
197 - apiKey: process.env.COMPOSIO_API_KEY,
198 -});
45 +const composio = new Composio({ provider: new OpenAIAgentsProvider() });
46
200 -// Create a connected account
201 -const connectionRequest = await composio.connectedAccounts.initiate(
202 - 'user123', // userId
203 - 'ac_12343544', // authConfigId: You can create it from the dashboard
204 - {
205 - callbackUrl: 'https://your-app.com/callback',
206 - data: {
207 - // Additional data for the connection
208 - scope: ['read', 'write'],
209 - },
210 - }
211 -);
212 -
213 -// Wait for the connection to be established
214 -// Default timeout is 60 seconds
215 -const connectedAccount = await connectionRequest.waitForConnection();
216 -console.log({ connectedAccount });
47 +const session = await composio.create('user_123');
48 +const tools = await session.tools(); // ready to pass to the OpenAI Agents SDK
49 ```
50
219 -### Waiting for Connection Establishment
51 +Adapters exist for OpenAI, OpenAI Agents, Anthropic, Claude Agent SDK, Vercel AI SDK, Google GenAI, LangChain, LlamaIndex, Mastra, and Cloudflare Workers AI. See the [provider table](https://github.com/ComposioHQ/composio#providers) and the [framework quickstarts](https://docs.composio.dev/docs/quickstart).
52
221 -The `waitForConnection` method is available on both the `ConnectionRequest` and `ConnectedAccounts` classes. It allows you to poll for a connection to become active:
53 +## MCP
54 +
55 +Every session also exposes a hosted MCP endpoint. Pass `mcp: true` to surface it in the type, then point Claude, Cursor, or any MCP client at it:
56
57 ```typescript
224 -// From a ConnectionRequest instance (returned by createConnectedAccount)
225 -const connectedAccount = await connectionRequest.waitForConnection(120000); // 2 minute timeout
58 +const session = await composio.create('user_123', { mcp: true });
59
227 -// From the ConnectedAccounts class (using a connected account ID)
228 -const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_abc123', 60000); // 1 minute timeout
60 +console.log(session.mcp.url);
61 +console.log(session.mcp.headers);
62 ```
63
231 -The method continuously polls the Composio API until the connection:
232 -
233 -- Becomes `ACTIVE` (returns the connected account)
234 -- Enters a terminal state like `FAILED`, `EXPIRED`, or `DELETED` (throws an error)
235 -- Exceeds the specified timeout (throws a timeout error)
64 +See [sessions via MCP](https://docs.composio.dev/docs/sessions-via-mcp).
65
237 -If the connection does not complete within the provided timeout (default: 60 seconds), a `ConnectionRequestTimeoutError` is thrown.
66 +## Modifiers
67
239 -### Managing Connected Accounts
68 +`session.tools()` accepts modifiers to transform tool schemas and intercept execution:
69
70 ```typescript
242 -// List all connected accounts
243 -const accounts = await composio.connectedAccounts.list({
244 - userId: 'user123',
71 +const tools = await session.tools({
72 + modifySchema: ({ toolSlug, toolkitSlug, schema }) => ({
73 + ...schema,
74 + description: `${schema.description} (via my-app)`,
75 + }),
76 + beforeExecute: ({ toolSlug, toolkitSlug, params }) => params,
77 + afterExecute: ({ toolSlug, toolkitSlug, result }) => result,
78 });
246 -
247 -// Get a specific connected account
248 -const account = await composio.connectedAccounts.get('account_id');
249 -
250 -// Enable/Disable a connected account
251 -await composio.connectedAccounts.enable('account_id');
252 -await composio.connectedAccounts.disable('account_id');
253 -
254 -// Refresh credentials
255 -await composio.connectedAccounts.refresh('account_id');
256 -
257 -// Delete a connected account
258 -await composio.connectedAccounts.delete('account_id');
79 ```
80
261 -### Connection Statuses
81 +See [modify tool behavior](https://docs.composio.dev/docs/tools-direct/modify-tool-behavior/schema-modifiers).
82
263 -Connected accounts can have the following statuses:
83 +## Configuration
84
265 -- `ACTIVE`: Connection is established and working
266 -- `INACTIVE`: Connection is temporarily disabled
267 -- `PENDING`: Connection is being processed
268 -- `INITIATED`: Connection request has started
269 -- `EXPIRED`: Connection credentials have expired
270 -- `FAILED`: Connection attempt failed
85 +The `Composio` constructor accepts:
86
272 -### Authentication Schemes
87 +```typescript
88 +interface ComposioConfig {
89 + apiKey?: string | null; // Defaults to COMPOSIO_API_KEY
90 + baseURL?: string | null; // Custom API base URL
91 + provider?: TProvider; // Provider adapter (default: OpenAIProvider)
92 + allowTracking?: boolean; // Enable/disable telemetry (default: true)
93 + defaultHeaders?: ComposioRequestHeaders; // Extra headers for API requests
94 + disableVersionCheck?: boolean; // Skip the SDK version check (default: false)
95 + dangerouslyAllowAutoUploadDownloadFiles?: boolean; // Auto file upload/download during execution (default: false)
96 +}
97 +```
98
274 -Composio supports various authentication schemes:
99 +Environment variables:
100
276 -- OAuth2
277 -- OAuth1
278 -- OAuth1a
279 -- API Key
280 -- Basic Auth
281 -- Bearer Token
282 -- Google Service Account
283 -- And more...
101 +- `COMPOSIO_API_KEY`: your Composio API key
102 +- `COMPOSIO_BASE_URL`: custom API base URL
103 +- `COMPOSIO_LOG_LEVEL`: `silent`, `error`, `warn`, `info`, or `debug`
104 +- `COMPOSIO_TOOLKIT_VERSION_<TOOLKIT>`: pin a toolkit version, e.g. `COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00`
105
285 -## Environment Variables
106 +## Beyond sessions
107
287 -- `COMPOSIO_API_KEY`: Your Composio API key
288 -- `COMPOSIO_BASE_URL`: Custom API base URL
289 -- `COMPOSIO_LOGGING_LEVEL`: Logging level (silent, error, warn, info, debug)
290 -- `DEVELOPMENT`: Development mode flag
291 -- `COMPOSIO_TOOLKIT_VERSION_<TOOLKITNAME>`: Version of the specific tool
292 -- `CI`: CI environment flag
108 +The `Composio` instance also exposes `composio.toolkits`, `composio.triggers`, `composio.authConfigs`, and `composio.connectedAccounts` for managing resources outside a session. The older [direct tool execution](https://docs.composio.dev/docs/tools-direct/executing-tools) flow (`composio.tools.get` and `composio.tools.execute`) still works but is legacy; prefer sessions for new code.
109
294 -## Contributing
110 +## Support
111
296 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
112 +- [Documentation](https://docs.composio.dev)
113 +- [TypeScript SDK reference](https://docs.composio.dev/reference/sdk-reference/typescript)
114 +- [Discord community](https://discord.gg/composio)
115 +- [Open an issue](https://github.com/ComposioHQ/composio/issues)
116
117 ## License
118
300 -ISC License
301 -
302 -## Support
303 -
304 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
119 +MIT
ts/packages/experimental/README.md
+10 -204
@@ -1,214 +1,20 @@
1 # `@composio/experimental`
2
3 -Experimental Composio integrations and helpers.
3 +Experimental additions to the Composio TypeScript SDK. Features ship here before they are ready for [`@composio/core`](../core), so APIs can change or be removed between releases.
4
5 -This package currently includes two framework providers:
6 -
7 -- A **Pi provider** for [`@earendil-works/pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent). It lets Composio tools be passed to Pi SDK sessions as `customTools` and includes a dynamic Tool Router session toolset modeled after the Slack bot integration in `~/composio/slack-bot`.
8 -- An **eve provider** for the [eve](https://github.com/vercel/eve) agent framework (see [eve provider](#eve-provider) below).
9 -
10 -## Install
5 +## Installation
6
7 ```bash
13 -pnpm add @composio/core @composio/experimental @earendil-works/pi-coding-agent
14 -```
15 -
16 -## Static tool wrapping
17 -
18 -Use this when you already know the exact Composio tools to expose to Pi.
19 -
20 -```ts
21 -import { Composio } from '@composio/core';
22 -import { PiProvider } from '@composio/experimental';
23 -import { createAgentSession, SessionManager } from '@earendil-works/pi-coding-agent';
24 -
25 -const provider = new PiProvider();
26 -const composio = new Composio({
27 - apiKey: process.env.COMPOSIO_API_KEY,
28 - provider,
29 -});
30 -
31 -const tools = await composio.tools.get('default', {
32 - tools: ['GITHUB_CREATE_ISSUE'],
33 -});
34 -
35 -const { session } = await createAgentSession({
36 - cwd: process.cwd(),
37 - sessionManager: SessionManager.inMemory(process.cwd()),
38 - customTools: tools,
39 - tools: ['read', 'bash', ...tools.map(tool => tool.name)],
40 -});
41 -
42 -await session.prompt('Create a GitHub issue for the failing test.');
43 -```
44 -
45 -## Dynamic session helpers
46 -
47 -Use this when Pi should search and execute tools dynamically inside one Tool Router session. Prefer the capability form so your app owns connection management and uses one Pi-style `hooks` object for interception/result transforms.
48 -
49 -```ts
50 -import { Composio } from '@composio/core';
51 -import { PiProvider, createPiComposioSystemPrompt } from '@composio/experimental';
52 -import {
53 - createAgentSession,
54 - DefaultResourceLoader,
55 - getAgentDir,
56 - SessionManager,
57 -} from '@earendil-works/pi-coding-agent';
58 -
59 -const provider = new PiProvider();
60 -const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
61 -
62 -const composioSession = await composio.sessions.create('slack:T123:U456', {
63 - toolkits: ['github', 'gmail'],
64 - manageConnections: true,
65 - workbench: { enable: true },
66 -});
67 -
68 -const composioTools = provider.createSessionTools({
69 - sessionId: composioSession.sessionId,
70 - search: composioSession.search.bind(composioSession),
71 - execute: composioSession.execute.bind(composioSession),
72 - callbackUrl: 'https://your-app.example.com/auth/callback',
73 - includeWorkbenchTools: true,
74 - connections: {
75 - getToolkitStates: toolkits => composioSession.toolkits({ toolkits }),
76 - authorizeToolkit: (toolkit, options) => composioSession.authorize(toolkit, options),
77 - isConnected: state => state.connection?.isActive === true,
78 - },
79 - hooks: {
80 - search: (ctx, next) => {
81 - ctx.request.toolkits = ctx.request.toolkits?.map(toolkit =>
82 - toolkit === 'slack' ? 'slackbot' : toolkit
83 - );
84 - return next();
85 - },
86 - execute: (ctx, next) => {
87 - if (ctx.request.toolSlug === 'COMPOSIO_MANAGE_CONNECTIONS') {
88 - return ctx.deny('Meta tools are blocked.');
89 - }
90 - return next();
91 - },
92 - remoteWorkbench: async (ctx, next) => {
93 - const result = await next();
94 - await auditWorkbenchRun({ code: ctx.request.code_to_execute, result });
95 - return result;
96 - },
97 - remoteBash: async (ctx, next) => {
98 - if (ctx.request.command.includes('rm -rf')) {
99 - return ctx.deny('Destructive bash commands are blocked.');
100 - }
101 - return next();
102 - },
103 - onAuthLink: async (ctx, next) => {
104 - // DM the user, store the continuation, or redact public output.
105 - await sendConnectionLinkToUser({ url: ctx.url, toolkit: ctx.toolkit });
106 - return { message: 'Connection link sent out-of-band.' };
107 - // To also send the original result/link to the model, use: return next();
108 - },
109 - },
110 - transformResult: async ({ value }) => value,
111 -});
112 -
113 -const loader = new DefaultResourceLoader({
114 - cwd: process.cwd(),
115 - agentDir: getAgentDir(),
116 - systemPromptOverride: () =>
117 - createPiComposioSystemPrompt(composioSession.sessionId, { includeWorkbenchTools: true }),
118 -});
119 -await loader.reload();
120 -
121 -const { session } = await createAgentSession({
122 - cwd: process.cwd(),
123 - resourceLoader: loader,
124 - sessionManager: SessionManager.inMemory(process.cwd()),
125 - customTools: composioTools,
126 - tools: [
127 - 'read',
128 - 'bash',
129 - 'composio_search_tools',
130 - 'composio_manage_connections',
131 - 'composio_execute_tool',
132 - 'composio_remote_workbench',
133 - 'composio_remote_bash',
134 - ],
135 -});
136 -
137 -await session.prompt('Find my recent GitHub issues and summarize the blockers.');
138 -```
139 -
140 -`composio_manage_connections` uses your `connections.getToolkitStates()` and `connections.authorizeToolkit()` handlers. It does **not** call `session.execute('COMPOSIO_MANAGE_CONNECTIONS', ...)` internally.
141 -
142 -The dynamic helpers are:
143 -
144 -- `composio_search_tools` — search Tool Router for exact tool slugs and schemas.
145 -- `composio_manage_connections` — check/initiate user app connections.
146 -- `composio_execute_tool` — execute exact Composio tool slugs in the session.
147 -- `composio_remote_workbench` — execute Python in the Composio remote workbench for large outputs, remote files, and session-authenticated scripting.
148 -- `composio_remote_bash` — run short bash commands in the Composio remote workbench filesystem.
149 -
150 -Workbench helpers are opt-in because the Tool Router session must be created with workbench enabled.
151 -
152 -## Hooks
153 -
154 -`hooks` follows Pi's extension-event style with middleware semantics. Each hook receives a mutable `ctx.request`, `ctx.deny('reason')`, and a typed `next()` function. Calling `await next()` runs the default Composio behavior and returns the result before anything is sent back to the model. Return that result to pass it through, return a replacement value to control what the model sees, or skip `next()` entirely to divert/deny the operation.
155 -
156 -Available hooks:
157 -
158 -- `search(ctx, next)` — rewrite query/toolkit filters, log search results, or return custom search output.
159 -- `manageConnections(ctx, next)` — rewrite requested toolkits, force reauth, log connection state, or return custom connection output.
160 -- `execute(ctx, next)` — block/rewrite tools, route to another session/execute handler, call `ctx.manageConnections(...)`, log outputs, or return a file/workbench reference instead of inline data.
161 -- `remoteWorkbench(ctx, next)` — rewrite Python code/session metadata, audit workbench runs, or replace large outputs with file/workbench references. Calls through the generic `execute` hook when `next()` is used.
162 -- `remoteBash(ctx, next)` — rewrite/block shell commands, enforce safety policy, audit filesystem access, or replace output. Calls through the generic `execute` hook when `next()` is used.
163 -- `onAuthLink(ctx, next)` — send/redact/resume auth links out-of-band. `return next()` keeps the original model-visible result; returning another value replaces it.
164 -
165 -## Auth link handling
166 -
167 -Embedded agents often need to keep Composio connection URLs out of the public transcript. Use `hooks.onAuthLink()` to choose whether the model sees the original result or a redacted replacement:
168 -
169 -```ts
170 -const tools = provider.createSessionTools({
171 - search: composioSession.search.bind(composioSession),
172 - execute: composioSession.execute.bind(composioSession),
173 - connections: {
174 - getToolkitStates: toolkits => composioSession.toolkits({ toolkits }),
175 - authorizeToolkit: (toolkit, options) => composioSession.authorize(toolkit, options),
176 - },
177 - hooks: {
178 - onAuthLink: async (ctx, next) => {
179 - await sendConnectionLinkToUser({ url: ctx.url, toolkit: ctx.toolkit });
180 -
181 - if (shouldAlsoShowLinkToModel(ctx)) {
182 - return next();
183 - }
184 -
185 - return { message: 'Connection link sent out-of-band.' };
186 - },
187 - },
188 -});
189 -```
190 -
191 -## eve provider
192 -
193 -`EveProvider` is a Composio provider for the [eve](https://github.com/vercel/eve) agent framework. It makes `session.tools()` return eve-native `defineTool`s, so an eve agent gets the Tool Router meta-tools and any preloaded custom toolkits from one call.
194 -
195 -```ts
196 -import { Composio } from '@composio/core';
197 -import { EveProvider, defineComposioTools } from '@composio/experimental/eve';
198 -
199 -const composio = new Composio({ provider: new EveProvider() });
200 -const session = composio.sessions.create('user_123', {
201 - /* toolkits, customToolkits */
202 -});
203 -
204 -// Expose the tools to eve from agent/tools/<name>.ts:
205 -export default defineComposioTools(session);
8 +npm install @composio/core @composio/experimental
9 ```
10
208 -`defineComposioTools(session)` returns a `step.started` dynamic resolver and memoizes `session.tools()`, because the wrapped tools carry live `execute` closures that eve keeps only for step-scoped tools.
11 +## What's inside
12
210 -The provider also takes `(ctx, next)` hooks (`new EveProvider({ hooks })`) around the meta-tools, with the same rewrite, `deny`, transform, and `onAuthLink` semantics as the Pi hooks above.
13 +- `PiProvider` (root export): adapts Composio tools for [`@earendil-works/pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent), including dynamic session helpers that let Pi search, connect, and execute tools at runtime. See the [Pi provider docs](https://docs.composio.dev/docs/providers/pi) for the full guide.
14 +- `EveProvider` (from `@composio/experimental/eve`): adapts Composio tools for the [eve](https://github.com/vercel/eve) agent framework, with hook-based interception and per-tool approval helpers.
15 +- `experimental_createLocalWorkbenchSession` (from `@composio/experimental/workbench`): run a session's sandbox on your local machine instead of the hosted workbench.
16
212 -## Status
17 +## Links
18
214 -Experimental. The dynamic helper names and session helper API may change.
19 +- Pi provider docs: https://docs.composio.dev/docs/providers/pi
20 +- Composio docs: https://docs.composio.dev
ts/packages/providers/README.md
+28 -391
@@ -1,407 +1,44 @@
1 -# Composio Providers
1 +# Composio TypeScript providers
2
3 -This directory contains various providers that implement the Composio SDK for different platforms and frameworks. Each provider provides a way to interact with the Composio Platform using the specific platform's conventions and requirements.
3 +Each package in this directory adapts Composio tools to one agent framework's native tool format. You pass a provider to `new Composio({ provider })`, and `session.tools()` returns tools your framework can call directly.
4
5 -## Types of Providers
5 +## Packages
6
7 -Composio SDK supports two types of providers, each with different modifier capabilities:
7 +| Package | Framework |
8 +|---------|-----------|
9 +| [`@composio/openai`](openai) | OpenAI Chat Completions and Responses APIs |
10 +| [`@composio/openai-agents`](openai-agents) | OpenAI Agents SDK |
11 +| [`@composio/anthropic`](anthropic) | Anthropic Messages API |
12 +| [`@composio/claude-agent-sdk`](claude-agent-sdk) | Claude Agent SDK |
13 +| [`@composio/vercel`](vercel) | Vercel AI SDK |
14 +| [`@composio/google`](google) | Google GenAI |
15 +| [`@composio/langchain`](langchain) | LangChain and LangGraph |
16 +| [`@composio/llamaindex`](llamaindex) | LlamaIndex |
17 +| [`@composio/mastra`](mastra) | Mastra |
18 +| [`@composio/cloudflare`](cloudflare) | Cloudflare Workers AI |
19
9 -### 1. Non-Agentic Providers
20 +Each package README has an install command and a runnable quickstart.
21
11 -These providers only support schema modifiers for transforming tool schemas. They are suitable for simple integrations like OpenAI, Anthropic, etc.
22 +## Provider types
23
13 -Example implementation:
24 +Providers extend one of two base classes from `@composio/core`:
25
15 -```typescript
16 -import { BaseNonAgenticProvider } from '@composio/core';
17 -import type { Tool, SchemaModifiersParams } from '@composio/core';
26 +- **Non-agentic** (`BaseNonAgenticProvider`): format tool schemas for a raw model API (OpenAI, Anthropic, Cloudflare). Your code runs the tool loop, calling helpers like `executeToolCall` or `handleToolCalls` on the provider.
27 +- **Agentic** (`BaseAgenticProvider`): wrap tools with an execute function baked in (LangChain, LlamaIndex, Mastra, Vercel, OpenAI Agents). The framework runs the tool loop itself.
28
19 -export class NonAgenticProvider extends BaseNonAgenticProvider {
20 - async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool> {
21 - // Apply schema modifiers if provided
22 - if (modifiers?.schema) {
23 - return modifiers.schema(toolSlug, tool);
24 - }
25 - return tool;
26 - }
29 +## Creating a new provider
30
28 - async getTools(): Promise<Tool[]> {
29 - // Fetch tools from Composio API
30 - const response = await this.client.getTools();
31 - return response.data;
32 - }
33 -
34 - async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<Tool> {
35 - // Fetch tool from Composio API
36 - const response = await this.client.getToolBySlug(slug);
37 - // Apply schema modifiers if provided
38 - return this.wrapTool(slug, response.data, modifiers);
39 - }
40 -}
41 -```
42 -
43 -### 2. Agentic Providers
44 -
45 -These providers support full modifier capabilities, making them suitable for complex integrations like Vercel, Langchain, etc. They support:
46 -
47 -1. **Schema Modifiers**: Transform tool schemas using `TransformToolSchemaModifier`
48 -2. **Execution Modifiers**: Transform tool execution behavior
49 - - `beforeExecute`: Transform input parameters before execution
50 - - `afterExecute`: Transform output after execution
51 -3. **Execute Modifiers**: Used during tool execution
52 - - `beforeExecute`: Transform input parameters
53 - - `afterExecute`: Transform output
54 -
55 -Example implementation:
56 -
57 -```typescript
58 -import { BaseAgenticProvider } from '@composio/core';
59 -import type { Tool, ModifiersParams, ToolExecuteParams, ToolExecuteResponse } from '@composio/core';
60 -
61 -export class AgenticProvider extends BaseAgenticProvider {
62 - async wrapTool(toolSlug: string, tool: Tool, modifiers?: ModifiersParams): Promise<Tool> {
63 - let wrappedTool = tool;
64 -
65 - // Apply schema modifiers if provided
66 - if (modifiers?.schema) {
67 - wrappedTool = modifiers.schema(toolSlug, wrappedTool);
68 - }
69 -
70 - return wrappedTool;
71 - }
72 -
73 - async getTools(modifiers?: ModifiersParams): Promise<Tool[]> {
74 - // Fetch tools from Composio API
75 - const response = await this.client.getTools();
76 - // Apply modifiers to each tool
77 - return Promise.all(response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers)));
78 - }
79 -
80 - async getToolBySlug(slug: string, modifiers?: ModifiersParams): Promise<Tool> {
81 - // Fetch tool from Composio API
82 - const response = await this.client.getToolBySlug(slug);
83 - // Apply modifiers
84 - return this.wrapTool(slug, response.data, modifiers);
85 - }
86 -
87 - async executeTool(
88 - tool: Tool,
89 - params: ToolExecuteParams,
90 - modifiers?: ModifiersParams
91 - ): Promise<ToolExecuteResponse> {
92 - let executeParams = params;
93 -
94 - // Apply beforeExecute modifier if provided
95 - if (modifiers?.beforeExecute) {
96 - executeParams = modifiers.beforeExecute(tool.slug, executeParams);
97 - }
98 -
99 - // Execute the tool
100 - const response = await this.client.executeTool(tool.slug, executeParams);
101 -
102 - // Apply afterExecute modifier if provided
103 - if (modifiers?.afterExecute) {
104 - return modifiers.afterExecute(tool.slug, response.data);
105 - }
106 -
107 - return response.data;
108 - }
109 -}
110 -```
111 -
112 -## Creating a New Provider
113 -
114 -To create a new provider, you can use the provided script:
31 +Scaffold a package from the repository root:
32
33 ```bash
117 -# Create a non-agentic provider (default)
118 -pnpm run create-provider <your-provider-name>
119 -
120 -# Create an agentic provider
121 -pnpm run create-provider <your-provider-name> --agentic
122 -```
123 -
124 -The script will create a new provider with the following structure:
125 -
126 -```
127 -<provider-name>/
128 -├── src/
129 -│ └── index.ts # Provider implementation
130 -├── package.json # Package configuration
131 -├── tsconfig.json # TypeScript configuration
132 -├── tsup.config.ts # Build configuration
133 -└── README.md # Provider documentation
34 +pnpm create:provider <provider-name> [--agentic]
35 ```
36
136 -## Required Methods
37 +This creates `ts/packages/providers/<provider-name>` with `src/index.ts`, `package.json`, and build config. Implement `wrapTool` and `wrapTools` (plus `executeToolCall` for non-agentic providers), then add tests covering wrapping and execution handling.
38
138 -Each provider must implement the following methods:
139 -
140 -### For Non-Agentic Providers
141 -
142 -```typescript
143 -class NonAgenticProvider extends BaseNonAgenticProvider {
144 - // Wrap a tool with schema modifiers
145 - async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool>;
146 -
147 - // Get all available tools
148 - async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]>;
149 -
150 - // Get a specific tool by slug
151 - async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<Tool>;
152 -}
153 -```
39 +If you are building an adapter outside this repo, see the [custom providers guide](https://docs.composio.dev/docs/providers/custom-providers).
40
155 -### For Agentic Providers
41 +## Links
42
157 -```typescript
158 -class AgenticProvider extends BaseAgenticProvider {
159 - // Wrap a tool with modifiers
160 - async wrapTool(toolSlug: string, tool: Tool, modifiers?: ModifiersParams): Promise<Tool>;
161 -
162 - // Get all available tools
163 - async getTools(modifiers?: ModifiersParams): Promise<Tool[]>;
164 -
165 - // Get a specific tool by slug
166 - async getToolBySlug(slug: string, modifiers?: ModifiersParams): Promise<Tool>;
167 -
168 - // Execute a tool with modifiers
169 - async executeTool(
170 - tool: Tool,
171 - params: ToolExecuteParams,
172 - modifiers?: ModifiersParams
173 - ): Promise<ToolExecuteResponse>;
174 -}
175 -```
176 -
177 -## Modifier Types
178 -
179 -### Schema Modifiers (Both Types)
180 -
181 -```typescript
182 -type SchemaModifiersParams = {
183 - schema?: TransformToolSchemaModifier;
184 -};
185 -
186 -type TransformToolSchemaModifier = (toolSlug: string, tool: Tool) => Tool;
187 -```
188 -
189 -### Execution Modifiers (Agentic Only)
190 -
191 -```typescript
192 -type ModifiersParams = {
193 - schema?: TransformToolSchemaModifier;
194 - beforeExecute?: beforeExecuteModifier;
195 - afterExecute?: afterExecuteModifier;
196 -};
197 -
198 -type beforeExecuteModifier = (toolSlug: string, params: ToolExecuteParams) => ToolExecuteParams;
199 -type afterExecuteModifier = (
200 - toolSlug: string,
201 - response: ToolExecuteResponse
202 -) => ToolExecuteResponse;
203 -```
204 -
205 -## Best Practices
206 -
207 -1. **Type Safety**: Always use TypeScript and ensure proper type definitions for all methods and parameters.
208 -2. **Error Handling**: Implement proper error handling for API calls and tool execution.
209 -3. **Documentation**: Document your provider's features, requirements, and usage examples.
210 -4. **Testing**: Write tests for your provider implementation.
211 -5. **Modifier Support**:
212 - - For non-agentic providers, implement schema modifiers to transform tool schemas
213 - - For agentic providers, implement both schema and execution modifiers for full control over tool behavior
214 -
215 -## Example Implementation
216 -
217 -Here's a complete example of a non-agentic provider implementation:
218 -
219 -```typescript
220 -import { BaseNonAgenticProvider } from '@composio/core';
221 -import type { Tool, SchemaModifiersParams } from '@composio/core';
222 -
223 -export class OpenAIProvider extends BaseNonAgenticProvider {
224 - async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool> {
225 - // Apply schema modifiers if provided
226 - if (modifiers?.schema) {
227 - return modifiers.schema(toolSlug, tool);
228 - }
229 - return tool;
230 - }
231 -
232 - async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]> {
233 - // Fetch tools from Composio API
234 - const response = await this.client.getTools();
235 - // Apply modifiers to each tool
236 - return Promise.all(response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers)));
237 - }
238 -
239 - async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<Tool> {
240 - // Fetch tool from Composio API
241 - const response = await this.client.getToolBySlug(slug);
242 - // Apply modifiers
243 - return this.wrapTool(slug, response.data, modifiers);
244 - }
245 -}
246 -```
247 -
248 -And here's a complete example of an agentic provider implementation:
249 -
250 -```typescript
251 -import { BaseAgenticProvider } from '@composio/core';
252 -import type { Tool, ModifiersParams, ToolExecuteParams, ToolExecuteResponse } from '@composio/core';
253 -
254 -export class VercelProvider extends BaseAgenticProvider {
255 - async wrapTool(toolSlug: string, tool: Tool, modifiers?: ModifiersParams): Promise<Tool> {
256 - let wrappedTool = tool;
257 -
258 - // Apply schema modifiers if provided
259 - if (modifiers?.schema) {
260 - wrappedTool = modifiers.schema(toolSlug, wrappedTool);
261 - }
262 -
263 - return wrappedTool;
264 - }
265 -
266 - async getTools(modifiers?: ModifiersParams): Promise<Tool[]> {
267 - // Fetch tools from Composio API
268 - const response = await this.client.getTools();
269 - // Apply modifiers to each tool
270 - return Promise.all(response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers)));
271 - }
272 -
273 - async getToolBySlug(slug: string, modifiers?: ModifiersParams): Promise<Tool> {
274 - // Fetch tool from Composio API
275 - const response = await this.client.getToolBySlug(slug);
276 - // Apply modifiers
277 - return this.wrapTool(slug, response.data, modifiers);
278 - }
279 -
280 - async executeTool(
281 - tool: Tool,
282 - params: ToolExecuteParams,
283 - modifiers?: ModifiersParams
284 - ): Promise<ToolExecuteResponse> {
285 - let executeParams = params;
286 -
287 - // Apply beforeExecute modifier if provided
288 - if (modifiers?.beforeExecute) {
289 - executeParams = modifiers.beforeExecute(tool.slug, executeParams);
290 - }
291 -
292 - // Execute the tool
293 - const response = await this.client.executeTool(tool.slug, executeParams);
294 -
295 - // Apply afterExecute modifier if provided
296 - if (modifiers?.afterExecute) {
297 - return modifiers.afterExecute(tool.slug, response.data);
298 - }
299 -
300 - return response.data;
301 - }
302 -}
303 -```
304 -
305 -## Usage Examples
306 -
307 -### Using a Non-Agentic Provider
308 -
309 -```typescript
310 -import { Composio } from '@composio/core';
311 -import { OpenAIProvider } from '@composio/openai-provider';
312 -import type { Tool } from '@composio/core';
313 -
314 -const composio = new Composio({
315 - apiKey: process.env.COMPOSIO_API_KEY,
316 - provider: new OpenAIProvider(),
317 -});
318 -
319 -// Get a tool with schema modifiers
320 -const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {
321 - schema: (toolSlug: string, tool: Tool) => ({
322 - ...tool,
323 - description: 'Search HackerNews posts with improved description',
324 - inputParameters: {
325 - ...tool.inputParameters,
326 - limit: {
327 - type: 'number',
328 - description: 'Maximum number of posts to return',
329 - },
330 - },
331 - }),
332 -});
333 -```
334 -
335 -### Using an Agentic Provider
336 -
337 -```typescript
338 -import { Composio } from '@composio/core';
339 -import { VercelProvider } from '@composio/vercel-provider';
340 -import type { Tool, ToolExecuteParams, ToolExecuteResponse } from '@composio/core';
341 -
342 -const composio = new Composio({
343 - apiKey: process.env.COMPOSIO_API_KEY,
344 - provider: new VercelProvider(),
345 -});
346 -
347 -// Get a tool with full modifier support
348 -const tool = await composio.getToolBySlug('HACKERNEWS_SEARCH_POSTS', {
349 - // Schema modifier
350 - schema: (toolSlug: string, tool: Tool) => ({
351 - ...tool,
352 - description: 'Search HackerNews posts with improved description',
353 - inputParameters: {
354 - ...tool.inputParameters,
355 - limit: {
356 - type: 'number',
357 - description: 'Maximum number of posts to return',
358 - },
359 - },
360 - }),
361 - // Execution modifiers
362 - beforeExecute: (toolSlug: string, params: ToolExecuteParams) => ({
363 - ...params,
364 - arguments: {
365 - ...params.arguments,
366 - limit: Math.min((params.arguments?.limit as number) || 10, 100),
367 - },
368 - }),
369 - afterExecute: (toolSlug: string, response: ToolExecuteResponse) => ({
370 - ...response,
371 - data: {
372 - ...response.data,
373 - posts: (response.data?.posts as any[]).map(post => ({
374 - ...post,
375 - url: post.url || `https://news.ycombinator.com/item?id=${post.id}`,
376 - })),
377 - },
378 - }),
379 -});
380 -
381 -// Execute the tool with execution modifiers
382 -const result = await composio.provider.executeTool(
383 - tool,
384 - {
385 - arguments: { query: 'AI', limit: 20 },
386 - },
387 - {
388 - beforeExecute: (toolSlug: string, params: ToolExecuteParams) => ({
389 - ...params,
390 - arguments: {
391 - ...params.arguments,
392 - limit: Math.min((params.arguments?.limit as number) || 10, 100),
393 - },
394 - }),
395 - afterExecute: (toolSlug: string, response: ToolExecuteResponse) => ({
396 - ...response,
397 - data: {
398 - ...response.data,
399 - posts: (response.data?.posts as any[]).map(post => ({
400 - ...post,
401 - url: post.url || `https://news.ycombinator.com/item?id=${post.id}`,
402 - })),
403 - },
404 - }),
405 - }
406 -);
407 -```
43 +- [Provider docs](https://docs.composio.dev/docs/providers)
44 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/anthropic/README.md
+44 -276
@@ -1,309 +1,77 @@
1 # @composio/anthropic
2
3 -Non-Agentic Provider for Anthropic in Composio SDK.
4 -
5 -## Features
6 -
7 -- **Tool Integration**: Seamless integration with Anthropic's tool calling capabilities
8 -- **Type Safety**: Full TypeScript support with proper type definitions
9 -- **Tool Execution**: Execute tools with proper parameter handling and response formatting
10 -- **Caching Support**: Optional tool caching for improved performance
11 -- **Modifier Support**: Support for execution modifiers to transform tool inputs and outputs
12 -- **Streaming Support**: First-class support for streaming responses
3 +Adapts Composio tools to the Claude Messages API and executes the tool calls Claude returns.
4
5 ## Installation
6
7 ```bash
17 -npm install @composio/anthropic
18 -# or
19 -yarn add @composio/anthropic
20 -# or
21 -pnpm add @composio/anthropic
22 -```
23 -
24 -## Environment Variables
25 -
26 -Required environment variables:
27 -
28 -- `COMPOSIO_API_KEY`: Your Composio API key
29 -- `ANTHROPIC_API_KEY`: Your Anthropic API key
30 -
31 -Optional environment variables:
32 -
33 -- `ANTHROPIC_API_URL`: Custom API base URL (defaults to Anthropic's API)
34 -
35 -## Quick Start
36 -
37 -```typescript
38 -import { Composio } from '@composio/core';
39 -import { AnthropicProvider } from '@composio/anthropic';
40 -
41 -// Initialize Composio with Anthropic provider
42 -const composio = new Composio({
43 - apiKey: 'your-composio-api-key',
44 - // Initialize with optional caching
45 - provider: new AnthropicProvider({ cacheTools: true }),
46 -});
47 -
48 -// Get available tools
49 -const tools = await composio.tools.get('user123', {
50 - toolkits: ['gmail', 'googlecalendar'],
51 - limit: 10,
52 -});
8 +npm install @composio/core @composio/anthropic @anthropic-ai/sdk
9 ```
10
55 -## Examples
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `ANTHROPIC_API_KEY` (from https://console.anthropic.com/settings/keys) in your environment.
12
57 -Check out our complete example implementations:
13 +## Quickstart
14
59 -- [Basic Anthropic Integration](../../examples/anthropic/src/index.ts)
60 -- [Streaming Example](../../examples/anthropic/src/streaming.ts)
61 -
62 -### Basic Example
15 +Create a session for your user, pass its tools to the Messages API, and run the tool-call loop until Claude replies with text. `handleToolCalls` executes every `tool_use` block and returns a ready-to-append `user` message of `tool_result` blocks.
16
17 ```typescript
65 -import { Composio } from '@composio/core';
66 -import { AnthropicProvider } from '@composio/anthropic';
18 import Anthropic from '@anthropic-ai/sdk';
68 -
69 -// Initialize Anthropic
70 -const anthropic = new Anthropic({
71 - apiKey: process.env.ANTHROPIC_API_KEY,
72 -});
73 -
74 -// Initialize Composio
75 -const composio = new Composio({
76 - apiKey: process.env.COMPOSIO_API_KEY,
77 - provider: new AnthropicProvider(),
78 -});
79 -
80 -// Get tools
81 -const tools = await composio.tools.get('user123', {
82 - toolkits: ['gmail'],
83 -});
84 -
85 -// Create a message with tools
86 -const message = await anthropic.messages.create({
87 - model: 'claude-3-sonnet-20240229',
88 - max_tokens: 1024,
89 - tools: tools,
90 - messages: [
91 - {
92 - role: 'user',
93 - content: 'Send an email to support@example.com',
94 - },
95 - ],
96 -});
97 -
98 -// Handle tool calls
99 -// Anthropic returns tool calls as `tool_use` content blocks.
100 -for (const block of message.content) {
101 - if (block.type === 'tool_use') {
102 - const result = await composio.provider.executeToolCall('user123', block, {
103 - connectedAccountId: 'account123',
104 - });
105 - console.log('Tool execution result:', result);
106 - }
107 -}
108 -```
109 -
110 -### Streaming Example
111 -
112 -```typescript
19 import { Composio } from '@composio/core';
20 import { AnthropicProvider } from '@composio/anthropic';
115 -import Anthropic from '@anthropic-ai/sdk';
116 -
117 -const anthropic = new Anthropic({
118 - apiKey: process.env.ANTHROPIC_API_KEY,
119 -});
21
22 const composio = new Composio({
122 - apiKey: process.env.COMPOSIO_API_KEY,
23 provider: new AnthropicProvider(),
24 });
25 +const client = new Anthropic();
26
126 -const tools = await composio.tools.get('user123', {
127 - toolkits: ['gmail'],
128 -});
129 -
130 -const stream = await anthropic.messages.stream({
131 - model: 'claude-3-sonnet-20240229',
132 - max_tokens: 1024,
133 - tools: tools,
134 - messages: [
135 - {
136 - role: 'user',
137 - content: 'Send an email to support@example.com',
138 - },
139 - ],
140 -});
141 -
142 -for await (const messageChunk of stream) {
143 - // Anthropic streams tool calls as `tool_use` content blocks, emitted via a
144 - // `content_block_start` event whose `content_block` is the `tool_use` block.
145 - if (
146 - messageChunk.type === 'content_block_start' &&
147 - messageChunk.content_block.type === 'tool_use'
148 - ) {
149 - const result = await composio.provider.executeToolCall('user123', messageChunk.content_block, {
150 - connectedAccountId: 'account123',
151 - });
152 - console.log('Tool execution result:', result);
153 - } else {
154 - console.log('Message chunk:', messageChunk);
155 - }
156 -}
157 -```
158 -
159 -## Provider Configuration
160 -
161 -The Anthropic provider can be configured with various options:
162 -
163 -```typescript
164 -const provider = new AnthropicProvider({
165 - // Enable tool caching
166 - cacheTools: true,
167 - // Custom execution modifiers
168 - modifiers: {
169 - beforeExecute: params => {
170 - // Transform parameters before execution
171 - return params;
172 - },
173 - afterExecute: response => {
174 - // Transform response after execution
175 - return response;
176 - },
177 - },
178 -});
179 -```
180 -
181 -## API Reference
182 -
183 -### AnthropicProvider Class
184 -
185 -The `AnthropicProvider` class extends `BaseNonAgenticProvider` and provides Anthropic-specific functionality.
186 -
187 -#### Constructor
188 -
189 -```typescript
190 -new AnthropicProvider(options?: { cacheTools?: boolean })
191 -```
192 -
193 -- `options.cacheTools`: Optional boolean to enable tool caching (default: false)
194 -
195 -#### Methods
196 -
197 -##### `wrapTool(tool: Tool): AnthropicTool`
198 -
199 -Wraps a Composio tool in the Anthropic format.
200 -
201 -```typescript
202 -const tool = provider.wrapTool(composioTool);
203 -```
204 -
205 -##### `wrapTools(tools: Tool[]): AnthropicToolCollection`
206 -
207 -Wraps multiple Composio tools in the Anthropic format.
208 -
209 -```typescript
210 -const tools = provider.wrapTools(composioTools);
211 -```
212 -
213 -##### `executeToolCall(userId: string, toolUse: AnthropicToolUseBlock, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
27 +// Create a session for your user
28 +const session = await composio.create('user_123');
29 +const tools = await session.tools();
30
215 -Executes a tool call from Anthropic and returns the result as a string.
216 -
217 -```typescript
218 -const result = await composio.provider.executeToolCall(
219 - 'user123',
220 - {
221 - type: 'tool_use',
222 - id: 'tu_123',
223 - name: 'tool-name',
224 - input: { param: 'value' },
225 - },
31 +const messages: Anthropic.MessageParam[] = [
32 {
227 - connectedAccountId: 'account123',
228 - customAuthParams: {
229 - /* ... */
230 - },
33 + role: 'user',
34 + content: "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
35 },
232 - {
233 - beforeExecute: params => params,
234 - afterExecute: response => response,
235 - }
236 -);
237 -```
238 -
239 -##### `handleToolCalls(userId: string, message: Message, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<Anthropic.Messages.MessageParam[]>`
240 -
241 -Processes and executes all tool calls found in an Anthropic message response. This method automatically extracts tool calls from the message content, executes them, and returns their results.
36 +];
37
243 -**Parameters:**
244 -
245 -- `userId` (string): The ID of the user making the tool calls
246 -- `message` (Message): The Anthropic message response containing tool calls
247 -- `options` (optional): Additional options for tool execution
248 - - `connectedAccountId`: ID of the connected account
249 - - `customAuthParams`: Custom authentication parameters
250 -- `modifiers` (optional): Functions to modify tool execution
251 - - `beforeExecute`: Transform parameters before execution
252 - - `afterExecute`: Transform response after execution
253 -
254 -**Returns:**
255 -Promise<Anthropic.Messages.MessageParam[]>: Tool execution results for the assistant message
256 -
257 -**Example:**
38 +let response = await client.messages.create({
39 + model: 'claude-opus-4-6',
40 + max_tokens: 4096,
41 + tools,
42 + messages,
43 +});
44
259 -```typescript
260 -const message = {
261 - id: 'msg_123',
262 - content: [
263 - { type: 'text', text: 'Hello' },
264 - {
265 - type: 'tool_use',
266 - id: 'tu_123',
267 - name: 'test-tool',
268 - input: { param: 'value' },
269 - },
270 - {
271 - type: 'tool_use',
272 - id: 'tu_456',
273 - name: 'another-tool',
274 - input: { param: 'value2' },
275 - },
276 - ],
277 -};
45 +// Agentic loop: keep executing tool calls until the model responds with text
46 +while (response.stop_reason === 'tool_use') {
47 + const toolResults = await composio.provider.handleToolCalls('user_123', response);
48 + messages.push({ role: 'assistant', content: response.content });
49 + messages.push(...toolResults);
50 + response = await client.messages.create({
51 + model: 'claude-opus-4-6',
52 + max_tokens: 4096,
53 + tools,
54 + messages,
55 + });
56 +}
57
279 -const results = await provider.handleToolCalls(
280 - 'user123',
281 - message,
282 - {
283 - connectedAccountId: 'account123',
284 - customAuthParams: {
285 - parameters: [{ name: 'token', value: 'abc123', in: 'header' }],
286 - },
287 - },
288 - {
289 - beforeExecute: params => params,
290 - afterExecute: response => response,
58 +// Print final response
59 +for (const block of response.content) {
60 + if (block.type === 'text') {
61 + console.log(block.text);
62 }
292 -);
293 -
294 -// results will be an array of tool execution responses
295 -// from each tool execution in the order they appeared
296 -// this can be passed directly to LLM
63 +}
64 ```
65
299 -## Contributing
300 -
301 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
66 +Building on the Claude Agent SDK instead? Use [`@composio/claude-agent-sdk`](../claude-agent-sdk), which exposes Composio tools as an in-process MCP server and lets the SDK run the loop.
67
303 -## License
68 +## Provider options
69
305 -ISC License
70 +- `cacheTools`: pass `new AnthropicProvider({ cacheTools: true })` to attach Anthropic's ephemeral `cache_control` to every tool definition and tool-result block. This lets Claude reuse cached tool schemas across requests and can cut prompt cost when you send the same large tool set on every turn. It is the only constructor option.
71 +- `handleToolCalls(userId, message)` returns `Anthropic.Messages.MessageParam[]`, not raw strings, so you append the result directly to your message list. For finer control, `executeToolCall(userId, toolUseBlock)` runs a single `tool_use` block and returns the result as a JSON string.
72 +- Claude occasionally emits a tool's `input` as a JSON string instead of an object; the provider normalizes this before execution.
73
307 -## Support
74 +## Links
75
309 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
76 +- [Anthropic provider docs](https://docs.composio.dev/docs/providers/anthropic)
77 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/claude-agent-sdk/README.md
+32 -108
@@ -1,138 +1,62 @@
1 -# @composio/claude-code-agents
1 +# @composio/claude-agent-sdk
2
3 -Composio provider for the [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) (`@anthropic-ai/claude-agent-sdk`).
4 -
5 -This provider enables seamless integration of Composio tools with Claude Code Agents, allowing you to use any Composio-supported tool (Gmail, Slack, GitHub, etc.) within your Claude agents.
3 +Composio provider for the [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) (`@anthropic-ai/claude-agent-sdk`). It wraps Composio tools as in-process MCP tools that Claude agents can call.
4
5 ## Installation
6
7 ```bash
10 -npm install @composio/claude-agent-sdk @composio/core @anthropic-ai/claude-agent-sdk
8 +npm install @composio/core @composio/claude-agent-sdk @anthropic-ai/claude-agent-sdk
9 ```
10
13 -### Prerequisites
14 -
15 -1. **Claude Code CLI**: The Claude Agent SDK requires Claude Code to be installed:
16 -
17 - ```bash
18 - # macOS/Linux/WSL
19 - curl -fsSL https://claude.ai/install.sh | bash
11 +Set two environment variables:
12
21 - # or via Homebrew
22 - brew install --cask claude-code
13 +- `COMPOSIO_API_KEY` from the [Composio dashboard](https://dashboard.composio.dev/settings)
14 +- `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys)
15
24 - # or via npm
25 - npm install -g @anthropic-ai/claude-code
26 - ```
16 +## Quickstart
17
28 -2. **API Keys**:
29 - - `ANTHROPIC_API_KEY`: Your Anthropic API key from [console.anthropic.com](https://console.anthropic.com)
30 - - `COMPOSIO_API_KEY`: Your Composio API key from [app.composio.dev](https://app.composio.dev)
31 -
32 -## Usage
18 +Create a session for your user, serve its tools through an SDK MCP server, and query Claude:
19
20 ```typescript
35 -import { Composio } from '@composio/core';
36 -import { ClaudeCodeAgentsProvider } from '@composio/claude-code-agents';
37 -import { query, createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk';
38 -
39 -// Initialize Composio
40 -const composio = new Composio({
41 - provider: new ClaudeCodeAgentsProvider(),
42 -});
21 +import { Composio } from "@composio/core";
22 +import { ClaudeAgentSDKProvider } from "@composio/claude-agent-sdk";
23 +import { createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";
24
44 -// Create a tool router session
45 -const session = await composio.create('external_user_id');
25 +const composio = new Composio({ provider: new ClaudeAgentSDKProvider() });
26
47 -// Get tools from the session (native)
27 +// Each session is scoped to one of your users
28 +const session = await composio.create("user_123");
29 const tools = await session.tools();
30 +
31 const customServer = createSdkMcpServer({
50 - name: 'composio',
51 - version: '1.0.0',
52 - tools: tools,
32 + name: "composio",
33 + version: "1.0.0",
34 + tools,
35 });
36
55 -// Initialize Claude client
56 -for await (const content of query({
57 - prompt: 'Fetch my last email from gmail',
37 +for await (const stream of query({
38 + prompt: "Summarize my emails from today",
39 options: {
40 mcpServers: { composio: customServer },
60 - permissionMode: 'bypassPermissions',
41 + permissionMode: "bypassPermissions",
42 },
43 })) {
63 - if (content.type === 'assistant') {
64 - console.log('Claude:', content.message);
44 + if (stream.type === "assistant") {
45 + for (const block of stream.message.content) {
46 + if (block.type === "text") process.stdout.write(block.text);
47 + }
48 }
49 }
67 -
68 -console.log(`✅ Received response from Claude`);
50 ```
51
71 -## API Reference
72 -
73 -### `ClaudeCodeAgentsProvider`
74 -
75 -The main provider class for integrating Composio tools with Claude Code Agents.
76 -
77 -#### Constructor Options
78 -
79 -```typescript
80 -interface ClaudeAgentSDKProviderOptions {
81 - serverName?: string; // Name for the MCP server (default: 'composio')
82 - serverVersion?: string; // Version for the MCP server (default: '1.0.0')
83 -}
84 -```
85 -
86 -#### Methods
87 -
88 -##### `wrapTool(tool, executeTool)`
89 -
90 -Wraps a single Composio tool as a Claude Agent SDK MCP tool.
91 -
92 -##### `wrapTools(tools, executeTool)`
52 +For multi-turn conversations, store `session.sessionId` and reuse it with `composio.use(sessionId)` instead of creating a new session each turn.
53
94 -Wraps multiple Composio tools as Claude Agent SDK MCP tools.
54 +## How it works
55
96 -## How It Works
97 -
98 -The Claude Agent SDK uses MCP (Model Context Protocol) servers to provide tools to Claude agents. This provider:
99 -
100 -1. Converts Composio tool definitions to MCP tool format
101 -2. Creates an in-process MCP server using `createSdkMcpServer()`
102 -3. Handles tool execution by routing calls through Composio's execution layer
103 -
104 -## Examples
105 -
106 -### Using Multiple Tools
107 -
108 -```typescript
109 -const tools = await composio.tools.get('default', [
110 - 'GMAIL_SEND_EMAIL',
111 - 'GMAIL_LIST_EMAILS',
112 - 'SLACK_POST_MESSAGE',
113 -]);
114 -
115 -const mcpServer = composio.provider.createMcpServer(tools, composio.tools.execute);
116 -
117 -for await (const message of query({
118 - prompt: 'Check my latest emails and post a summary to #general on Slack',
119 - options: {
120 - mcpServers: { composio: mcpServer },
121 - },
122 -})) {
123 - console.log(message);
124 -}
125 -```
126 -
127 -### Custom Server Name
128 -
129 -```typescript
130 -const provider = new ClaudeCodeAgentsProvider({
131 - serverName: 'my-composio-tools',
132 - serverVersion: '2.0.0',
133 -});
134 -```
56 +The Claude Agent SDK provides tools to agents through MCP (Model Context Protocol) servers. `ClaudeAgentSDKProvider` converts each Composio tool definition into an MCP tool and routes execution back through Composio, so `createSdkMcpServer` can serve them in process; no separate server to run.
57
136 -## License
58 +## Links
59
138 -ISC
60 +- [Composio quickstart](https://docs.composio.dev/docs/quickstart)
61 +- [Composio documentation](https://docs.composio.dev)
62 +- [Claude Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview)
ts/packages/providers/cloudflare/README.md
+28 -139
@@ -1,166 +1,55 @@
1 # @composio/cloudflare
2
3 -The Cloudflare AI provider for Composio SDK, providing seamless integration with Cloudflare's AI capabilities and Workers AI.
4 -
5 -## Features
6 -
7 -- **Workers AI Integration**: Seamless integration with Cloudflare Workers AI
8 -- **Streaming Support**: First-class support for streaming responses
9 -- **Model Support**: Support for all Cloudflare AI models (@cf/meta/llama-2-7b-chat-int8, etc.)
10 -- **Edge Deployment**: Deploy and run AI models at the edge
11 -- **Tool Execution**: Execute tools with proper parameter handling
12 -- **Type Safety**: Full TypeScript support with proper type definitions
3 +The Cloudflare provider formats Composio tools for Cloudflare Workers AI function calling (`AiTextGenerationToolInput`).
4
5 ## Installation
6
7 ```bash
17 -npm install @composio/cloudflare
18 -# or
19 -yarn add @composio/cloudflare
20 -# or
21 -pnpm add @composio/cloudflare
8 +npm install @composio/core @composio/cloudflare @cloudflare/workers-types
9 ```
10
24 -## Quick Start
25 -
26 -```typescript
27 -import { Composio } from '@composio/core';
28 -import { CloudflareProvider } from '@composio/cloudflare';
29 -
30 -// Initialize Composio with Cloudflare provider
31 -const composio = new Composio({
32 - apiKey: 'your-composio-api-key',
33 - provider: new CloudflareProvider({
34 - accountId: 'your-cloudflare-account-id',
35 - apiToken: 'your-cloudflare-api-token',
36 - }),
37 -});
38 -
39 -// Get available tools
40 -const tools = await composio.tools.get('user123', {
41 - toolkits: ['gmail', 'googlecalendar'],
42 - limit: 10,
43 -});
44 -```
45 -
46 -## Usage Examples
47 -
48 -### Basic Chat Completion with Streaming
49 -
50 -```typescript
51 -import { Composio } from '@composio/core';
52 -import { CloudflareProvider } from '@composio/cloudflare';
53 -import { Ai } from '@cloudflare/ai';
54 -
55 -// Initialize Composio
56 -const composio = new Composio({
57 - apiKey: process.env.COMPOSIO_API_KEY,
58 - provider: new CloudflareProvider(),
59 -});
60 -
61 -// In your Worker
62 -export default {
63 - async fetch(request: Request, env: Env, ctx: ExecutionContext) {
64 - const ai = new Ai(env.AI);
65 - const tools = await composio.tools.get('user123', {
66 - toolkits: ['gmail'],
67 - });
68 -
69 - const messages = [
70 - { role: 'system', content: 'You are a helpful assistant.' },
71 - { role: 'user', content: 'What can you do?' },
72 - ];
73 -
74 - const stream = await ai.run('@cf/meta/llama-2-7b-chat-int8', {
75 - messages,
76 - tools,
77 - stream: true,
78 - });
11 +Set `COMPOSIO_API_KEY` with your API key from [the dashboard](https://dashboard.composio.dev/settings). In a Worker, add it as a secret (`wrangler secret put COMPOSIO_API_KEY`) and bind Workers AI as `AI` in your `wrangler.toml`; no separate model API key is needed.
12
80 - return new Response(stream, {
81 - headers: {
82 - 'content-type': 'text/event-stream',
83 - },
84 - });
85 - },
86 -};
87 -```
13 +## Quickstart
14
89 -### Multi-Modal Example
15 +Create a session for your user, pass its tools to `env.AI.run`, and execute any tool calls the model returns:
16
17 ```typescript
18 import { Composio } from '@composio/core';
19 import { CloudflareProvider } from '@composio/cloudflare';
94 -import { Ai } from '@cloudflare/ai';
95 -
96 -// Initialize Composio
97 -const composio = new Composio({
98 - apiKey: process.env.COMPOSIO_API_KEY,
99 - provider: new CloudflareProvider(),
100 -});
20
102 -// In your Worker
21 export default {
104 - async fetch(request: Request, env: Env, ctx: ExecutionContext) {
105 - const ai = new Ai(env.AI);
106 - const tools = await composio.tools.get('user123', {
107 - toolkits: ['gmail'],
22 + async fetch(request: Request, env: Env): Promise<Response> {
23 + const composio = new Composio({
24 + apiKey: env.COMPOSIO_API_KEY,
25 + provider: new CloudflareProvider(),
26 });
27
110 - // Image analysis
111 - const imageResponse = await ai.run('@cf/microsoft/resnet-50', {
112 - image: await request.arrayBuffer(),
28 + // Create a session for your user
29 + const session = await composio.create('user_123');
30 + const tools = await session.tools();
31 +
32 + const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
33 + messages: [
34 + { role: 'system', content: 'You are a helpful assistant.' },
35 + { role: 'user', content: 'Summarize my emails from today' },
36 + ],
37 + // session.tools() returns a collection keyed by tool slug
38 + tools: Object.values(tools),
39 });
40
115 - // Use image analysis in chat
116 - const messages = [
117 - { role: 'system', content: 'You are a helpful assistant.' },
118 - {
119 - role: 'user',
120 - content: 'What do you see in this image?',
121 - context: { image_analysis: imageResponse },
122 - },
123 - ];
41 + const results = [];
42 + for (const toolCall of response.tool_calls ?? []) {
43 + results.push(await composio.provider.executeToolCall('user_123', toolCall, {}));
44 + }
45
125 - const stream = await ai.run('@cf/meta/llama-2-7b-chat-int8', {
126 - messages,
127 - tools,
128 - stream: true,
129 - });
130 -
131 - return new Response(stream, {
132 - headers: {
133 - 'content-type': 'text/event-stream',
134 - },
135 - });
46 + return Response.json({ response, results });
47 },
48 };
49 ```
50
140 -## API Reference
141 -
142 -### CloudflareProvider Class
143 -
144 -The `CloudflareProvider` class extends `BaseComposioProvider` and provides Cloudflare-specific functionality.
145 -
146 -#### Methods
147 -
148 -##### `executeToolCall(tool: ToolCall): Promise<string>`
149 -
150 -Executes a tool call and returns the result.
151 -
152 -```typescript
153 -const result = await composio.provider.executeToolCall(toolCall);
154 -```
155 -
156 -## Contributing
157 -
158 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
159 -
160 -## License
161 -
162 -ISC License
51 +`executeToolCall` takes the `{ name, arguments }` tool calls that Workers AI emits, runs the matching Composio tool for that user, and returns the result as a JSON string.
52
164 -## Support
53 +## Links
54
166 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
55 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/google/README.md
+41 -94
@@ -1,124 +1,71 @@
1 # @composio/google
2
3 -Google GenAI Provider for Composio SDK.
4 -
5 -## Features
6 -
7 -- **Google GenAI Integration**: Seamless integration with Google's Generative AI models (Gemini)
8 -- **Function Calling Support**: Convert Composio tools to Google GenAI function declarations
9 -- **Type Safety**: Full TypeScript support with proper type definitions
10 -- **Execution Modifiers**: Support for transforming tool inputs and outputs
11 -- **Flexible Authentication**: Support for custom authentication parameters
12 -- **Streaming Support**: First-class support for streaming responses
3 +Adapts Composio tools to Gemini function declarations for the Google GenAI SDK (`@google/genai`) and executes the function calls the model returns.
4
5 ## Installation
6
7 ```bash
8 npm install @composio/core @composio/google @google/genai
18 -# or
19 -yarn add @composio/core @composio/google @google/genai
20 -# or
21 -pnpm add @composio/core @composio/google @google/genai
9 ```
10
24 -## Environment Variables
25 -
26 -Required environment variables:
27 -
28 -- `COMPOSIO_API_KEY`: Your Composio API key
29 -- `GEMINI_API_KEY`: Your Google AI API key
30 -
31 -Optional environment variables:
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `GOOGLE_API_KEY` (from https://aistudio.google.com/apikey) in your environment.
12
33 -- `GOOGLE_PROJECT_ID`: Your Google Cloud project ID (for custom deployments)
34 -- `GOOGLE_LOCATION`: Your Google Cloud location (for custom deployments)
13 +## Quickstart
14
36 -## Quick Start
15 +Create a session for your user, pass its tools to Gemini as function declarations, and run the loop: execute each function call with `composio.provider.executeToolCall`, feed the result back, and repeat until the model replies with text.
16
17 ```typescript
18 import { Composio } from '@composio/core';
19 import { GoogleProvider } from '@composio/google';
41 -import { GoogleGenerativeAI } from '@google/genai';
20 +import { GoogleGenAI, type Part } from '@google/genai';
21
43 -// Initialize Google GenAI
44 -const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
45 -
46 -// Initialize Composio with Google provider
22 const composio = new Composio({
48 - apiKey: process.env.COMPOSIO_API_KEY,
23 provider: new GoogleProvider(),
24 });
25 +const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY! });
26
52 -// Get available tools
53 -const tools = await composio.tools.get('user123', {
54 - toolkits: ['gmail', 'calendar'],
55 - limit: 10,
56 -});
57 -```
58 -
59 -## Examples
27 +// Create a session for your user
28 +const session = await composio.create('user_123');
29 +const tools = await session.tools();
30
61 -Check out our complete example implementations:
62 -
63 -- [Basic Google Integration](../../examples/google/src/index.ts)
64 -
65 -## API Reference
66 -
67 -### GoogleProvider Class
68 -
69 -The `GoogleProvider` class extends `BaseNonAgenticProvider` and provides Google GenAI-specific functionality.
70 -
71 -#### Methods
72 -
73 -##### `wrapTool(tool: Tool): GoogleTool`
74 -
75 -Wraps a Composio tool in the Google GenAI function declaration format.
76 -
77 -```typescript
78 -const wrappedTool = provider.wrapTool(composioTool);
79 -```
80 -
81 -##### `wrapTools(tools: Tool[]): GoogleGenAIToolCollection`
82 -
83 -Wraps multiple Composio tools in the Google GenAI function declaration format.
84 -
85 -```typescript
86 -const wrappedTools = provider.wrapTools(composioTools);
87 -```
88 -
89 -##### `executeToolCall(userId: string, tool: GoogleGenAIFunctionCall, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
90 -
91 -Executes a tool call from Google GenAI and returns the result as a JSON string.
92 -
93 -```typescript
94 -const result = await provider.executeToolCall('user123', functionCall, options, modifiers);
95 -```
31 +const chat = ai.chats.create({
32 + model: 'gemini-3-pro-preview',
33 + config: {
34 + tools: [{ functionDeclarations: tools }],
35 + },
36 +});
37
97 -#### Types
38 +let response = await chat.sendMessage({
39 + message: "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
40 +});
41
99 -```typescript
100 -interface GoogleGenAIFunctionCall {
101 - name: string;
102 - args: Record<string, unknown>;
42 +// Agentic loop: keep executing tool calls until the model responds with text
43 +while (response.functionCalls && response.functionCalls.length > 0) {
44 + const parts: Part[] = [];
45 + for (const fc of response.functionCalls) {
46 + const result = await composio.provider.executeToolCall('user_123', {
47 + name: fc.name || '',
48 + args: (fc.args || {}) as Record<string, unknown>,
49 + });
50 + parts.push({
51 + functionResponse: {
52 + id: fc.id,
53 + name: fc.name,
54 + response: JSON.parse(result),
55 + },
56 + });
57 + }
58 + response = await chat.sendMessage({ message: parts });
59 }
60
105 -type GoogleTool = {
106 - name: string;
107 - description: string;
108 - parameters: Schema;
109 -};
110 -
111 -type GoogleGenAIToolCollection = GoogleTool[];
61 +console.log(response.text);
62 ```
63
114 -## Contributing
115 -
116 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
117 -
118 -## License
64 +## Tool execution
65
120 -ISC License
66 +Gemini function calling is non-agentic; the model returns function calls and you execute them. `GoogleProvider` exposes `executeToolCall(userId, functionCall, options?, modifiers?)`, which takes a `{ name, args }` pair and returns the tool result as a JSON string. The constructor takes no options.
67
122 -## Support
68 +## Links
69
124 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
70 +- [Google provider docs](https://docs.composio.dev/docs/providers/google)
71 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/langchain/README.md
+48 -178
@@ -1,207 +1,77 @@
1 # @composio/langchain
2
3 -The LangChain provider for Composio SDK, providing seamless integration with LangChain's ecosystem and tools.
4 -
5 -## Features
6 -
7 -- **LangChain Integration**: Seamless integration with LangChain's ecosystem
8 -- **LCEL Support**: Full support for LangChain Expression Language (LCEL)
9 -- **Streaming Support**: First-class support for streaming responses
10 -- **Tool Execution**: Execute LangChain tools with proper parameter handling
11 -- **Chain Integration**: Work with LangChain chains and agents
12 -- **Type Safety**: Full TypeScript support with proper type definitions
3 +The LangChain provider turns Composio tools into LangChain `DynamicStructuredTool` objects with built-in execution, ready for LangChain and LangGraph agents. In TypeScript, LangGraph is served by this same package.
4
5 ## Installation
6
7 ```bash
17 -npm install @composio/core @composio/langchain @langchain/core @langchain/openai
18 -# or
19 -yarn add @composio/core @composio/langchain @langchain/core @langchain/openai
20 -# or
21 -pnpm add @composio/core @composio/langchain @langchain/core @langchain/openai
8 +npm install @composio/core @composio/langchain @langchain/core @langchain/openai @langchain/langgraph
9 ```
10
24 -## Environment Variables
25 -
26 -Required environment variables:
27 -
28 -- `COMPOSIO_API_KEY`: Your Composio API key
29 -- `OPENAI_API_KEY`: Your OpenAI API key (or other LLM provider's key)
11 +Set `COMPOSIO_API_KEY` with your API key from [the dashboard](https://dashboard.composio.dev/settings), and `OPENAI_API_KEY` (or your LLM provider's key).
12
31 -Optional environment variables:
13 +## Quickstart
14
33 -- `LANGCHAIN_TRACING_V2`: Enable LangChain tracing (set to "true")
34 -- `LANGCHAIN_ENDPOINT`: Custom LangChain API endpoint
35 -- `LANGCHAIN_API_KEY`: Your LangChain API key (for hosted services)
36 -
37 -## Quick Start
15 +Create a session for your user, fetch its tools, and wire them into a LangGraph agent:
16
17 ```typescript
40 -import { Composio } from '@composio/core';
41 -import { LangChainProvider } from '@composio/langchain';
42 -
43 -// Initialize Composio with LangChain provider
44 -const composio = new Composio({
45 - apiKey: 'your-composio-api-key',
46 - provider: new LangChainProvider(),
47 -});
48 -
49 -// Get available tools
50 -const tools = await composio.tools.get('user123', {
51 - toolkits: ['gmail', 'googlecalendar'],
52 - limit: 10,
53 -});
54 -
55 -// Get tools with version control
56 -const versionedTools = await composio.tools.get('user123', {
57 - toolkits: ['gmail'],
58 - toolkitVersions: { gmail: '20250909_00' },
59 -});
60 -
61 -// Get a specific tool
62 -const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');
63 -```
64 -
65 -## Examples
66 -
67 -Check out our complete example implementations:
68 -
69 -- [Basic LangChain Integration](../../examples/langchain/src/index.ts)
70 -- [LCEL Example](../../examples/langchain/src/lcel.ts)
71 -- [RAG Example](../../examples/langchain/src/rag.ts)
72 -- [Streaming Example](../../examples/langchain/src/streaming.ts)
73 -
74 -### Basic Chain with Streaming
75 -
76 -```typescript
77 -import { Composio } from '@composio/core';
78 -import { LangChainProvider } from '@composio/langchain';
79 -import { ChatPromptTemplate } from '@langchain/core/prompts';
80 -import { StringOutputParser } from '@langchain/core/output_parsers';
18 import { ChatOpenAI } from '@langchain/openai';
82 -
83 -const composio = new Composio({
84 - apiKey: process.env.COMPOSIO_API_KEY,
85 - provider: new LangChainProvider(),
86 -});
87 -
88 -// Get tools for the chain
89 -const tools = await composio.tools.get('user123', {
90 - toolkits: ['gmail'],
91 - limit: 10,
92 -});
93 -
94 -const model = new ChatOpenAI({
95 - modelName: 'gpt-4',
96 - streaming: true,
97 -});
98 -
99 -const prompt = ChatPromptTemplate.fromTemplate('Tell me a joke about {topic}');
100 -const parser = new StringOutputParser();
101 -
102 -const chain = prompt.pipe(model).pipe(parser);
103 -
104 -// Stream the response
105 -const stream = await chain.stream({
106 - topic: 'programming',
107 -});
108 -
109 -for await (const chunk of stream) {
110 - console.log(chunk);
111 -}
112 -```
113 -
114 -### Tool Execution with Streaming Events
115 -
116 -```typescript
19 +import { HumanMessage, AIMessage } from '@langchain/core/messages';
20 +import { ToolNode } from '@langchain/langgraph/prebuilt';
21 +import { StateGraph, MessagesAnnotation } from '@langchain/langgraph';
22 import { Composio } from '@composio/core';
118 -import { LangChainProvider } from '@composio/langchain';
119 -import { ChatPromptTemplate } from '@langchain/core/prompts';
120 -import { JsonOutputParser } from '@langchain/core/output_parsers';
121 -import { ChatOpenAI } from '@langchain/openai';
23 +import { LangchainProvider } from '@composio/langchain';
24
25 const composio = new Composio({
124 - apiKey: process.env.COMPOSIO_API_KEY,
125 - provider: new LangChainProvider(),
26 + provider: new LangchainProvider(),
27 });
28
128 -// Get tools for the chain
129 -const tools = await composio.tools.get('user123', {
130 - toolkits: ['gmail'],
131 -});
29 +// Create a session for your user
30 +const session = await composio.create('user_123');
31 +const tools = await session.tools();
32
133 -const model = new ChatOpenAI({
134 - modelName: 'gpt-4',
135 - streaming: true,
136 -});
33 +const toolNode = new ToolNode(tools);
34
138 -const chain = model.pipe(new JsonOutputParser());
139 -const eventStream = await chain.streamEvents(
140 - `Output a list of the countries france, spain and japan and their populations in JSON format.`,
141 - { version: 'v2' }
142 -);
143 -
144 -for await (const event of eventStream) {
145 - const eventType = event.event;
146 - if (eventType === 'on_chat_model_stream') {
147 - console.log(`Chat model chunk: ${event.data.chunk.content}`);
148 - } else if (eventType === 'on_parser_stream') {
149 - console.log(`Parser chunk: ${JSON.stringify(event.data.chunk)}`);
35 +const model = new ChatOpenAI({
36 + model: 'gpt-5.2',
37 + temperature: 0,
38 +}).bindTools(tools);
39 +
40 +function shouldContinue({ messages }: typeof MessagesAnnotation.State) {
41 + const lastMessage = messages[messages.length - 1] as AIMessage;
42 + if (lastMessage.tool_calls?.length) {
43 + return 'tools';
44 }
45 + return '__end__';
46 }
152 -```
47
154 -## Provider Configuration
155 -
156 -The LangChain provider can be configured with various options:
48 +async function callModel(state: typeof MessagesAnnotation.State) {
49 + const response = await model.invoke(state.messages);
50 + return { messages: [response] };
51 +}
52
158 -```typescript
159 -const provider = new LangChainProvider({
160 - // Default model configuration
161 - model: new ChatOpenAI({
162 - modelName: 'gpt-4',
163 - streaming: true,
164 - }),
165 - // Custom execution modifiers
166 - modifiers: {
167 - beforeExecute: params => {
168 - // Transform parameters before execution
169 - return params;
170 - },
171 - afterExecute: response => {
172 - // Transform response after execution
173 - return response;
174 - },
175 - },
176 - // Enable tracing
177 - tracing: true,
53 +const workflow = new StateGraph(MessagesAnnotation)
54 + .addNode('agent', callModel)
55 + .addEdge('__start__', 'agent')
56 + .addNode('tools', toolNode)
57 + .addEdge('tools', 'agent')
58 + .addConditionalEdges('agent', shouldContinue);
59 +
60 +const app = workflow.compile();
61 +
62 +const finalState = await app.invoke({
63 + messages: [
64 + new HumanMessage(
65 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"
66 + ),
67 + ],
68 });
69 +console.log(finalState.messages[finalState.messages.length - 1].content);
70 ```
71
181 -## API Reference
182 -
183 -### LangChainProvider Class
184 -
185 -The `LangChainProvider` class extends `BaseComposioProvider` and provides LangChain-specific functionality.
186 -
187 -#### Methods
188 -
189 -##### `executeToolCall(tool: Tool): Promise<string>`
190 -
191 -Executes a LangChain tool call and returns the result.
192 -
193 -```typescript
194 -const result = await provider.executeToolCall(tool);
195 -```
196 -
197 -## Contributing
198 -
199 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
200 -
201 -## License
202 -
203 -ISC License
72 +Each tool is a standard `DynamicStructuredTool`, so it also works anywhere LangChain accepts tools: chains, LCEL pipelines, and `bindTools` on any chat model.
73
205 -## Support
74 +## Links
75
207 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
76 +- [LangChain provider docs](https://docs.composio.dev/docs/providers/langchain)
77 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/llamaindex/README.md
+17 -212
@@ -1,154 +1,18 @@
1 # @composio/llamaindex
2
3 -Agentic Provider for Llamaindex in Composio SDK.
4 -
5 -## Features
6 -
7 -- **Seamless LlamaIndex Integration**: Tools are automatically compatible with LlamaIndex agents and workflows
8 -- **Full Modifier Support**: Support for both schema and execution modifiers with beforeExecute/afterExecute hooks
9 -- **Streaming Support**: Works with LlamaIndex streaming agents using `agentStreamEvent`
10 -- **Tool Execution**: Execute tools with proper parameter handling and JSON schema validation
11 -- **Type Safety**: Full TypeScript support with proper type definitions
12 -- **Zod Schema Integration**: Automatic conversion from JSON Schema to Zod for LlamaIndex compatibility
3 +The LlamaIndex provider turns Composio tools into LlamaIndex tools that execute themselves, ready to hand to a LlamaIndex agent.
4
5 ## Installation
6
7 ```bash
17 -npm install @composio/llamaindex
18 -# or
19 -yarn add @composio/llamaindex
20 -# or
21 -pnpm add @composio/llamaindex
22 -```
23 -
24 -## Quick Start
25 -
26 -```typescript
27 -import { Composio } from '@composio/core';
28 -import { LlamaindexProvider } from '@composio/llamaindex';
29 -
30 -// Initialize Composio with Llamaindex provider
31 -const composio = new Composio({
32 - apiKey: 'your-composio-api-key',
33 - provider: new LlamaindexProvider(),
34 -});
35 -
36 -// Get available tools
37 -const tools = await composio.tools.get('user123', {
38 - toolkits: ['gmail', 'googlecalendar'],
39 - limit: 10,
40 -});
41 -```
42 -
43 -## Prerequisites
44 -
45 -Before using the LlamaIndex provider, make sure you have:
46 -
47 -1. **Composio API Key**: Get your API key from [Composio Dashboard](https://app.composio.dev)
48 -2. **Environment Setup**: Set up your environment variables
49 -3. **LlamaIndex Dependencies**: Install required LlamaIndex packages
50 -
51 -```bash
52 -# Install LlamaIndex dependencies
53 -npm install @llamaindex/openai @llamaindex/workflow
8 +npm install @composio/core @composio/llamaindex @llamaindex/openai @llamaindex/workflow
9 ```
10
56 -```bash
57 -# Set up environment variables
58 -export COMPOSIO_API_KEY="your-composio-api-key"
59 -export OPENAI_API_KEY="your-openai-api-key" # For LlamaIndex OpenAI integration
60 -```
61 -
62 -## Usage Examples
63 -
64 -### Basic Example
65 -
66 -```typescript
67 -import { Composio } from '@composio/core';
68 -import { LlamaindexProvider } from '@composio/llamaindex';
69 -
70 -// Initialize Composio
71 -const composio = new Composio({
72 - apiKey: process.env.COMPOSIO_API_KEY,
73 - provider: new LlamaindexProvider(),
74 -});
75 -
76 -// Get tools
77 -const tools = await composio.tools.get('default', {
78 - toolkits: ['gmail'],
79 - limit: 10,
80 -});
81 -
82 -console.log(`Found ${tools.length} tools`);
83 -```
84 -
85 -### Complete Agent Example with HackerNews
86 -
87 -```typescript
88 -import { Composio } from '@composio/core';
89 -import { LlamaindexProvider } from '@composio/llamaindex';
90 -import { openai } from '@llamaindex/openai';
91 -import { agent, agentStreamEvent } from '@llamaindex/workflow';
92 -import 'dotenv/config';
93 -
94 -// Initialize Composio with LlamaIndex provider
95 -const composio = new Composio({
96 - apiKey: process.env.COMPOSIO_API_KEY,
97 - provider: new LlamaindexProvider(),
98 -});
99 -
100 -async function main() {
101 - try {
102 - console.log('🚀 Starting LlamaIndex Example...');
103 -
104 - // Get available tools with modifiers
105 - const tools = await composio.tools.get(
106 - 'default',
107 - {
108 - toolkits: ['hackernews'],
109 - limit: 10,
110 - },
111 - {
112 - beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
113 - console.log(`🔄 Executing tool ${toolSlug}/${toolkitSlug} with params:`, { params });
114 - return params;
115 - },
116 - afterExecute: ({ toolSlug, toolkitSlug, result }) => {
117 - console.log(`✅ Executed tool ${toolSlug}/${toolkitSlug} with result:`, { result });
118 - return result;
119 - },
120 - }
121 - );
122 -
123 - console.log(`✅ Found ${tools.length} tools`);
11 +Set `COMPOSIO_API_KEY` with your API key from [the dashboard](https://dashboard.composio.dev/settings), and `OPENAI_API_KEY` (or your LLM provider's key).
12
125 - // Create LlamaIndex agent with Composio tools
126 - const hackernewsAgent = agent({
127 - name: 'Hackernews Agent',
128 - description: 'A helpful hackernews assistant',
129 - llm: openai({ model: 'gpt-4o-mini' }),
130 - systemPrompt:
131 - 'You are a helpful hackernews assistant that helps users with their queries related to hackernews',
132 - tools, // Composio tools are automatically compatible with LlamaIndex
133 - });
13 +## Quickstart
14
135 - // Run the agent with streaming
136 - const stream = await hackernewsAgent.runStream('Summarize the front page of hackernews');
137 -
138 - for await (const event of stream) {
139 - if (agentStreamEvent.include(event)) {
140 - process.stdout.write(event.data.delta);
141 - }
142 - }
143 - } catch (error) {
144 - console.error('❌ Error running example:', error);
145 - }
146 -}
147 -
148 -main().catch(console.error);
149 -```
150 -
151 -### Using Tools with Different Toolkits
15 +Create a session for your user, fetch its tools, and hand them to an agent:
16
17 ```typescript
18 import { Composio } from '@composio/core';
@@ -157,87 +21,28 @@ import { openai } from '@llamaindex/openai';
21 import { agent } from '@llamaindex/workflow';
22
23 const composio = new Composio({
160 - apiKey: process.env.COMPOSIO_API_KEY,
24 provider: new LlamaindexProvider(),
25 });
26
164 -// Get tools from multiple toolkits
165 -const tools = await composio.tools.get('default', {
166 - toolkits: ['gmail', 'googlecalendar', 'slack'],
167 - limit: 20,
168 -});
27 +// Create a session for your user
28 +const session = await composio.create('user_123');
29 +const tools = await session.tools();
30
170 -// Create a multi-purpose agent
171 -const assistantAgent = agent({
172 - name: 'Personal Assistant',
173 - description: 'A helpful personal assistant',
174 - llm: openai({ model: 'gpt-4' }),
175 - systemPrompt:
176 - 'You are a helpful personal assistant that can manage emails, calendar events, and slack messages.',
31 +const myAgent = agent({
32 + llm: openai({ model: 'gpt-5.2' }),
33 tools,
34 });
35
180 -// Use the agent
181 -const response = await assistantAgent.run(
182 - 'Schedule a meeting for tomorrow at 2 PM and send a slack message about it'
36 +const result = await myAgent.run(
37 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"
38 );
184 -console.log(response);
185 -```
186 -
187 -## API Reference
188 -
189 -### LlamaindexProvider Class
190 -
191 -The `LlamaindexProvider` class extends `BaseAgenticProvider` and provides llamaindex-specific functionality.
192 -
193 -#### Methods
39
195 -##### `wrapTool(tool: Tool, executeTool: ExecuteToolFn): LlamaindexTool`
196 -
197 -Wraps a single Composio tool in the LlamaIndex format with proper Zod schema conversion.
198 -
199 -```typescript
200 -const llamaindexTool = provider.wrapTool(composioTool, executeTool);
201 -
202 -// The wrapped tool has LlamaIndex-compatible structure:
203 -// - metadata.name: Tool slug
204 -// - metadata.description: Tool description
205 -// - metadata.parameters: Zod schema for parameters
206 -// - call(): Function to execute the tool
40 +console.log(result.data.result);
41 ```
42
209 -##### `wrapTools(tools: Tool[], executeTool: ExecuteToolFn): LlamaindexTool[]`
210 -
211 -Wraps multiple Composio tools for use with LlamaIndex agents.
212 -
213 -```typescript
214 -const llamaindexTools = provider.wrapTools(composioTools, executeTool);
215 -
216 -// Use directly with LlamaIndex agents
217 -const agent = agent({
218 - name: 'My Agent',
219 - llm: openai({ model: 'gpt-4' }),
220 - tools: llamaindexTools, // Ready to use!
221 -});
222 -```
223 -
224 -##### `wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse`
225 -
226 -Transforms MCP URL responses into the standard format with URL objects.
227 -
228 -```typescript
229 -const mcpServers = provider.wrapMcpServerResponse(urlResponse);
230 -// Returns: [{ url: URL, name: string }, ...]
231 -```
232 -
233 -## Contributing
234 -
235 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
236 -
237 -## License
238 -
239 -ISC License
43 +The provider converts each tool's JSON Schema parameters to Zod and wires execution through Composio, so LlamaIndex can call the tools directly.
44
241 -## Support
45 +## Links
46
243 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
47 +- [LlamaIndex provider docs](https://docs.composio.dev/docs/providers/llamaindex)
48 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/mastra/README.md
+34 -90
@@ -1,121 +1,65 @@
1 # @composio/mastra
2
3 -Agentic Provider for Mastra in Composio SDK.
4 -
5 -## Features
6 -
7 -- **Full Modifier Support**: Support for both schema and execution modifiers
8 -- **Tool Execution**: Execute tools with proper parameter handling
9 -- **Type Safety**: Full TypeScript support with proper type definitions
10 -- **Agentic Capabilities**: Full support for autonomous agent behavior
11 -- **Streaming Support**: First-class support for streaming responses
12 -- **Custom Execution**: Support for custom tool execution strategies
3 +The Mastra provider turns Composio tools into Mastra's tool format with built-in execution, ready to pass to a Mastra `Agent`.
4
5 ## Installation
6
7 ```bash
17 -npm install @composio/core @composio/mastra
18 -# or
19 -yarn add @composio/core @composio/mastra
20 -# or
21 -pnpm add @composio/core @composio/mastra
8 +npm install @composio/core @composio/mastra @mastra/core @ai-sdk/openai
9 ```
10
24 -## Environment Variables
25 -
26 -Required environment variables:
27 -
28 -- `COMPOSIO_API_KEY`: Your Composio API key
29 -- `MASTRA_API_KEY`: Your Mastra API key
11 +Set `COMPOSIO_API_KEY` with your API key from [the dashboard](https://dashboard.composio.dev/settings), and `OPENAI_API_KEY` (or your LLM provider's key).
12
31 -Optional environment variables:
13 +## Quickstart
14
33 -- `MASTRA_API_URL`: Custom API base URL (defaults to Mastra's API)
34 -- `MASTRA_DEBUG`: Enable debug logging (set to "true")
35 -
36 -## Quick Start
15 +Create a session for your user, fetch its tools, and hand them to an agent:
16
17 ```typescript
18 import { Composio } from '@composio/core';
19 import { MastraProvider } from '@composio/mastra';
20 +import { Agent } from '@mastra/core/agent';
21 +import { openai } from '@ai-sdk/openai';
22
42 -// Initialize Composio with Mastra provider
23 const composio = new Composio({
44 - apiKey: process.env.COMPOSIO_API_KEY,
45 - provider: new MastraProvider({
46 - apiKey: process.env.MASTRA_API_KEY,
47 - }),
48 -});
49 -
50 -// Get available tools
51 -const tools = await composio.tools.get('user123', {
52 - toolkits: ['gmail', 'googlecalendar'],
53 - limit: 10,
24 + provider: new MastraProvider(),
25 });
55 -```
26
57 -## Examples
27 +// Create a session for your user
28 +const session = await composio.create('user_123');
29 +const tools = await session.tools();
30
59 -Check out our complete example implementations:
60 -
61 -- [Basic Mastra Integration](../../examples/mastra/src/index.ts)
62 -
63 -## API Reference
64 -
65 -### MastraProvider Class
66 -
67 -The `MastraProvider` class extends `BaseAgenticProvider` and provides Mastra-specific functionality.
68 -
69 -#### Constructor
70 -
71 -```typescript
72 -new MastraProvider(options?: MastraProviderOptions)
73 -```
74 -
75 -Options:
76 -
77 -- `apiKey`: Your Mastra API key
78 -- `apiUrl`: Custom API base URL
79 -- `debug`: Enable debug logging
80 -- `modifiers`: Custom execution modifiers
81 -- `executionStrategy`: Custom tool execution strategy
82 -
83 -#### Methods
84 -
85 -##### `wrapTool(tool: Tool, executeTool: ExecuteToolFn): MastraTool`
31 +const agent = new Agent({
32 + id: 'my-agent',
33 + name: 'My Agent',
34 + instructions: 'You are a helpful assistant.',
35 + model: openai('gpt-5.2'),
36 + tools,
37 +});
38
87 -Wraps a tool in the Mastra format.
39 +const { text } = await agent.generate([
40 + {
41 + role: 'user',
42 + content:
43 + "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
44 + },
45 +]);
46
89 -```typescript
90 -const tool = provider.wrapTool(composioTool, executeTool);
47 +console.log(text);
48 ```
49
93 -##### `wrapTools(tools: Tool[], executeTool: ExecuteToolFn): MastraToolCollection`
50 +Each tool gets both an input and an output schema, so Mastra can validate tool results as well as arguments.
51
95 -Wraps multiple tools in the Mastra format.
52 +## Strict mode
53
97 -```typescript
98 -const tools = provider.wrapTools(composioTools, executeTool);
99 -```
100 -
101 -##### `executeToolCall(userId: string, toolCall: MastraToolCall, options?: ExecuteToolFnOptions): Promise<string>`
102 -
103 -Executes a tool call from Mastra and returns the result.
54 +Pass `strict: true` to drop every non-required property from each tool's input schema before Mastra compiles it:
55
56 ```typescript
106 -const result = await provider.executeToolCall('user123', toolCall, {
107 - connectedAccountId: 'account123',
57 +const composio = new Composio({
58 + provider: new MastraProvider({ strict: true }),
59 });
60 ```
61
111 -## Contributing
112 -
113 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
114 -
115 -## License
116 -
117 -ISC License
118 -
119 -## Support
62 +## Links
63
121 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
64 +- [Mastra provider docs](https://docs.composio.dev/docs/providers/mastra)
65 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/openai-agents/README.md
+29 -51
@@ -1,78 +1,56 @@
1 # @composio/openai-agents
2
3 -The OpenAI Agents API provider for Composio SDK, providing seamless integration with OpenAI's Agents API and tools.
4 -
5 -## Features
6 -
7 -- **OpenAI Agents Integration**: Seamless integration with OpenAI's Agents SDK
8 -- **Tool Integration**: Easy integration of Composio tools with OpenAI Agents
9 -- **Type Safety**: Full TypeScript support with proper type definitions
10 -- **Strict Mode**: Support for strict mode tool parameter validation
3 +Composio provider for the [OpenAI Agents SDK](https://openai.github.io/openai-agents-js/) (`@openai/agents`). It converts Composio tools into the Agents SDK's native tool format so your agents can act across 1000+ apps.
4
5 ## Installation
6
7 ```bash
15 -npm install @composio/openai-agents @openai/agents
16 -# or
17 -yarn add @composio/openai-agents @openai/agents
18 -# or
19 -pnpm add @composio/openai-agents @openai/agents
8 +npm install @composio/core @composio/openai-agents @openai/agents
9 ```
10
22 -## Environment Variables
11 +Set two environment variables:
12
24 -Required environment variables:
13 +- `COMPOSIO_API_KEY` from the [Composio dashboard](https://dashboard.composio.dev/settings)
14 +- `OPENAI_API_KEY` from [OpenAI](https://platform.openai.com/api-keys)
15
26 -- `COMPOSIO_API_KEY`: Your Composio API key
27 -- `OPENAI_API_KEY`: Your OpenAI API key
16 +## Quickstart
17
29 -## Example
18 +Create a session for your user, hand its tools to an agent, and run it:
19
20 ```typescript
32 -import { OpenAIAgentsProvider } from '@composio/openai-agents';
33 -import { Composio } from '@composio/core';
34 -import { Agent, run } from '@openai/agents';
21 +import { Composio } from "@composio/core";
22 +import { OpenAIAgentsProvider } from "@composio/openai-agents";
23 +import { Agent, run } from "@openai/agents";
24
36 -const composio = new Composio({
37 - provider: new OpenAIAgentsProvider(),
38 -});
25 +const composio = new Composio({ provider: new OpenAIAgentsProvider() });
26
40 -// Fetch tools from Composio
41 -const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
42 - beforeExecute: async (toolSlug, toolkitSlug, params) => {
43 - console.log(`🔄 Executing tool ${toolSlug} from toolkit ${toolkitSlug}...`);
44 - return params;
45 - },
46 - afterExecute: async (toolSlug, toolkitSlug, result) => {
47 - console.log(`✅ Tool ${toolSlug} executed`);
48 - return result;
49 - },
50 -});
27 +// Each session is scoped to one of your users
28 +const session = await composio.create("user_123");
29 +const tools = await session.tools();
30
52 -// Create an agent with the tools
31 const agent = new Agent({
54 - name: 'Hackernews assistant',
55 - tools: tools,
32 + name: "Personal Assistant",
33 + instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
34 + model: "gpt-5.2",
35 + tools,
36 });
37
58 -// Run the agent with a query
59 -const result = await run(agent, 'Tell me about the user `pg` in hackernews');
38 +const result = await run(agent, "Summarize my emails from today");
39 +console.log(result.finalOutput);
40 ```
41
62 -## Provider Configuration
42 +For multi-turn conversations, store `session.sessionId` and reuse it with `composio.use(sessionId)` instead of creating a new session each turn.
43
64 -The OpenAI Agents provider can be configured with various options:
44 +## Strict mode
45 +
46 +Pass `strict: true` to enable strict JSON schema validation for tool parameters (see the [Agents SDK options reference](https://openai.github.io/openai-agents-js/guides/tools/#options-reference)):
47
48 ```typescript
67 -const provider = new OpenAIAgentsProvider({
68 - strict: true, // Enable strict mode for tool parameters
69 -});
49 +const provider = new OpenAIAgentsProvider({ strict: true });
50 ```
51
72 -## Documentation
73 -
74 -For more information about OpenAI Agents and how to use them, see:
52 +## Links
53
76 -- [OpenAI Strict Mode](https://openai.github.io/openai-agents-js/guides/tools/#options-reference)
77 -- [OpenAI Agents SDK Documentation](https://openai.github.io/openai-agents-js/)
78 -- [OpenAI Agents SDK GitHub](https://github.com/openai/openai-agents-js)
54 +- [Composio quickstart](https://docs.composio.dev/docs/quickstart)
55 +- [Composio documentation](https://docs.composio.dev)
56 +- [OpenAI Agents SDK documentation](https://openai.github.io/openai-agents-js/)
ts/packages/providers/openai/README.md
+36 -239
@@ -1,276 +1,73 @@
1 # @composio/openai
2
3 -The OpenAI provider for Composio SDK, providing seamless integration with OpenAI's models and function calling capabilities.
4 -
5 -## Features
6 -
7 -- **OpenAI Integration**: Seamless integration with OpenAI's models
8 -- **Streaming Support**: First-class support for streaming responses
9 -- **Function Calling**: Support for OpenAI's function calling feature
10 -- **Tool Execution**: Execute tools with proper parameter handling
11 -- **Type Safety**: Full TypeScript support with proper type definitions
12 -- **Model Support**: Support for all OpenAI models (GPT-4, GPT-3.5-turbo, etc.)
13 -- **Responses API Support**: First-class support for OpenAI's Responses API
3 +Adapts Composio tools to OpenAI function calling, for both the Responses API and the Chat Completions API.
4
5 ## Installation
6
7 ```bash
18 -npm install @composio/openai
19 -# or
20 -yarn add @composio/openai
21 -# or
22 -pnpm add @composio/openai
23 -```
24 -
25 -## Environment Variables
26 -
27 -Required environment variables:
28 -
29 -- `COMPOSIO_API_KEY`: Your Composio API key
30 -- `OPENAI_API_KEY`: Your OpenAI API key
31 -
32 -Optional environment variables:
33 -
34 -- `OPENAI_API_BASE`: Custom API base URL (for Azure OpenAI)
35 -- `OPENAI_ORGANIZATION`: OpenAI organization ID
36 -
37 -## Quick Start
38 -
39 -```typescript
40 -import { Composio } from '@composio/core';
41 -import { OpenAIProvider, OpenAIResponsesProvider } from '@composio/openai';
42 -
43 -// Initialize Composio with OpenAI provider
44 -const composio = new Composio({
45 - apiKey: 'your-composio-api-key',
46 - provider: new OpenAIProvider(), // For Chat Completions API
47 - // OR
48 - provider: new OpenAIResponsesProvider(), // For Responses API
49 -});
50 -
51 -// Get available tools
52 -const tools = await composio.tools.get('user123', {
53 - toolkits: ['gmail', 'googlecalendar'],
54 - limit: 10,
55 -});
56 -
57 -// Get a specific tool
58 -const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');
8 +npm install @composio/core @composio/openai openai
9 ```
10
61 -## Examples
11 +Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `OPENAI_API_KEY` (from https://platform.openai.com/api-keys) in your environment.
12
63 -Check out our complete example implementations:
13 +## Quickstart
14
65 -- [Basic OpenAI Integration](../../examples/openai/src/index.ts)
66 -- [Chat Completions Example](../../examples/openai/src/chat-completions.ts)
67 -- [Assistants Example](../../examples/openai/src/assistants.ts)
68 -- [Tools Example](../../examples/openai/src/tools.ts)
69 -- [Responses API Example](../../examples/openai/src/responses-api/index.ts)
70 -
71 -### Basic Chat Completion with Streaming
15 +Create a session for your user, pass its tools to the Responses API, and run the tool-call loop until the model replies with text. `handleToolCalls` executes the tool calls and returns ready-to-send `function_call_output` items.
16
17 ```typescript
74 -import { Composio } from '@composio/core';
75 -import { OpenAIProvider } from '@composio/openai';
18 import OpenAI from 'openai';
77 -
78 -const composio = new Composio({
79 - apiKey: process.env.COMPOSIO_API_KEY,
80 - provider: new OpenAIProvider(),
81 -});
82 -
83 -// Example API route
84 -export async function POST(req: Request) {
85 - const { messages } = await req.json();
86 - const tools = await composio.tools.get('user123', {
87 - toolkits: ['gmail'],
88 - });
89 -
90 - const stream = await openai.chat.completions.create({
91 - model: 'gpt-4',
92 - messages,
93 - tools,
94 - stream: true,
95 - });
96 -
97 - return new Response(stream, {
98 - headers: {
99 - 'content-type': 'text/event-stream',
100 - },
101 - });
102 -}
103 -```
104 -
105 -### Using the Responses API
106 -
107 -```typescript
19 import { Composio } from '@composio/core';
20 import { OpenAIResponsesProvider } from '@composio/openai';
110 -import OpenAI from 'openai';
21
112 -const openai = new OpenAI();
22 const composio = new Composio({
23 provider: new OpenAIResponsesProvider(),
24 });
25 +const client = new OpenAI();
26
117 -// Get tools from Composio
118 -const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
27 +// Create a session for your user
28 +const session = await composio.create('user_123');
29 +const tools = await session.tools();
30
120 -// Generate initial response from OpenAI
121 -const initialResponse = await openai.responses.create({
122 - model: 'gpt-4.1',
123 - input: 'Tell me about the user `pg` in hackernews',
31 +let response = await client.responses.create({
32 + model: 'gpt-5.2',
33 tools,
125 -});
126 -
127 -// Handle tool calls from response
128 -const modelInputs = await composio.provider.handleResponse(
129 - 'default',
130 - initialResponse,
131 - {},
132 - {
133 - beforeExecute: async (toolSlug, toolkitSlug, params) => {
134 - console.log(`🔄 Executing tool ${toolSlug} from toolkit ${toolkitSlug}...`);
135 - return params;
34 + input: [
35 + {
36 + role: 'user',
37 + content: "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
38 },
137 - afterExecute: async (toolSlug, toolkitSlug, result) => {
138 - console.log(`✅ Tool ${toolSlug} executed`);
139 - return result;
140 - },
141 - }
142 -);
143 -
144 -// Submit tool outputs back to OpenAI
145 -const finalResponse = await openai.responses.create({
146 - model: 'gpt-4.1',
147 - input: [...initialResponse.output, ...modelInputs],
148 - tools,
149 -});
150 -
151 -// Process the final response
152 -const finalContent = finalResponse.output[0];
153 -if (finalContent.type === 'message' && finalContent.content[0].type === 'output_text') {
154 - console.log(finalContent.content[0].text);
155 -}
156 -```
157 -
158 -### Tool Execution with Streaming
159 -
160 -```typescript
161 -import { Composio } from '@composio/core';
162 -import { OpenAIProvider } from '@composio/openai';
163 -import OpenAI from 'openai';
164 -
165 -const composio = new Composio({
166 - apiKey: process.env.COMPOSIO_API_KEY,
167 - provider: new OpenAIProvider(),
39 + ],
40 });
41
170 -// Example API route that handles tool execution
171 -export async function POST(req: Request) {
172 - const { messages } = await req.json();
173 - const tools = await composio.tools.get('user123', {
174 - toolkits: ['gmail', 'googlecalendar'],
175 - });
176 -
177 - const stream = await openai.chat.completions.create({
178 - model: 'gpt-4',
179 - messages,
42 +// Agentic loop: keep executing tool calls until the model responds with text
43 +while (response.output.some(o => o.type === 'function_call')) {
44 + const results = await composio.provider.handleToolCalls('user_123', response.output);
45 + response = await client.responses.create({
46 + model: 'gpt-5.2',
47 tools,
181 - tool_choice: 'auto',
182 - stream: true,
48 + previous_response_id: response.id,
49 + input: results,
50 });
51 +}
52
185 - const chunks = [];
186 - for await (const chunk of stream) {
187 - if (chunk.choices[0]?.delta?.tool_calls) {
188 - const toolCall = chunk.choices[0].delta.tool_calls[0];
189 - const result = await composio.provider.executeToolCall(toolCall);
190 - // Handle tool execution result
191 - chunks.push(result);
192 - } else {
193 - chunks.push(chunk.choices[0]?.delta?.content || '');
194 - }
53 +// Print final response
54 +for (const item of response.output) {
55 + if (item.type === 'message' && item.content[0].type === 'output_text') {
56 + console.log(item.content[0].text);
57 }
196 -
197 - return new Response(chunks.join(''), {
198 - headers: {
199 - 'content-type': 'text/plain',
200 - },
201 - });
58 }
59 ```
60
205 -## Provider Configuration
206 -
207 -The OpenAI providers can be configured with various options:
208 -
209 -```typescript
210 -// For Chat Completions API
211 -const provider = new OpenAIProvider();
212 -
213 -// For Responses API
214 -const responsesProvider = new OpenAIResponsesProvider({
215 - // Whether to enforce strict parameter validation
216 - strict: true, // Default: false
217 -});
218 -```
219 -
220 -## API Reference
221 -
222 -### OpenAIProvider Class
223 -
224 -The `OpenAIProvider` class extends `BaseComposioProvider` and provides OpenAI-specific functionality for the Chat Completions API.
225 -
226 -#### Methods
227 -
228 -##### `executeToolCall(tool: ToolCall): Promise<string>`
229 -
230 -Executes a tool call and returns the result.
231 -
232 -```typescript
233 -const result = await provider.executeToolCall(toolCall);
234 -```
235 -
236 -### OpenAIResponsesProvider Class
237 -
238 -The `OpenAIResponsesProvider` class extends `BaseNonAgenticProvider` and provides OpenAI-specific functionality for the Responses API.
239 -
240 -#### Methods
241 -
242 -##### `handleResponse(userId: string, response: OpenAI.Responses.Response, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]>`
243 -
244 -Handles tool calls from an OpenAI response and returns the tool outputs.
245 -
246 -```typescript
247 -const outputs = await provider.handleResponse('user123', response);
248 -```
249 -
250 -##### `handleToolCalls(userId: string, toolCalls: OpenAI.Responses.ResponseOutputItem[], options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]>`
251 -
252 -Handles specific tool calls from an OpenAI response.
253 -
254 -```typescript
255 -const outputs = await provider.handleToolCalls('user123', toolCalls);
256 -```
257 -
258 -##### `executeToolCall(userId: string, tool: OpenAI.Responses.ResponseFunctionToolCall, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
259 -
260 -Executes a single tool call and returns the result.
261 -
262 -```typescript
263 -const result = await provider.executeToolCall('user123', toolCall);
264 -```
265 -
266 -## Contributing
61 +## Providers in this package
62
268 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
63 +The package exports one provider per API surface:
64
270 -## License
65 +- `OpenAIResponsesProvider` targets the Responses API. `handleToolCalls(userId, response.output)` returns `function_call_output` items keyed by `call_id`; pair it with `previous_response_id` so you only resend new outputs each turn. The constructor accepts `{ strict?: boolean }` to enforce strict function schemas (default `false`).
66 +- `OpenAIProvider` targets the Chat Completions API and is the Composio SDK default, so `new Composio()` with no provider uses it. `handleToolCalls(userId, chatCompletion)` returns ready-to-append `tool` messages; you keep the full message list yourself.
67
272 -ISC License
68 +Use the Responses provider for new agentic flows; reach for Chat Completions when extending an existing Chat Completions codebase. See the [docs page](https://docs.composio.dev/docs/providers/openai) for the Chat Completions loop.
69
274 -## Support
70 +## Links
71
276 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
72 +- [OpenAI provider docs](https://docs.composio.dev/docs/providers/openai)
73 +- [Composio documentation](https://docs.composio.dev)
ts/packages/providers/vercel/README.md
+30 -216
@@ -1,244 +1,58 @@
1 # @composio/vercel
2
3 -The Vercel AI SDK provider for Composio SDK, providing seamless integration with Vercel's AI SDK and tools.
4 -
5 -## Features
6 -
7 -- **Vercel AI SDK Integration**: Seamless integration with Vercel's AI SDK
8 -- **Streaming Support**: First-class support for streaming responses
9 -- **Model Agnostic**: Works with any model supported by Vercel AI SDK (OpenAI, Anthropic, etc.)
10 -- **UI Components**: Integration with Vercel's React components for chat interfaces
11 -- **Tool Execution**: Execute tools with proper parameter handling and streaming
12 -- **Type Safety**: Full TypeScript support with proper type definitions
3 +Composio provider for the [Vercel AI SDK](https://sdk.vercel.ai) (`ai`). It converts Composio tools into the AI SDK's tool format with built-in execution: each wrapped tool carries its own `execute` function, so the AI SDK runs tool calls for you without a manual agentic loop.
4
5 ## Installation
6
7 ```bash
17 -npm install @composio/vercel ai
18 -# or
19 -yarn add @composio/vercel ai
20 -# or
21 -pnpm add @composio/vercel ai
22 -```
23 -
24 -## Environment Variables
25 -
26 -Required environment variables:
27 -
28 -- `COMPOSIO_API_KEY`: Your Composio API key
29 -
30 -Optional environment variables (based on model choice):
31 -
32 -- `OPENAI_API_KEY`: Your OpenAI API key (if using OpenAI)
33 -- `ANTHROPIC_API_KEY`: Your Anthropic API key (if using Anthropic)
34 -- `GEMINI_API_KEY`: Your Google AI API key (if using Gemini)
35 -
36 -## Quick Start
37 -
38 -```typescript
39 -import { Composio } from '@composio/core';
40 -import { VercelProvider } from '@composio/vercel';
41 -
42 -// Initialize Composio with Vercel provider
43 -const composio = new Composio({
44 - apiKey: 'your-composio-api-key',
45 - provider: new VercelProvider(),
46 -});
47 -
48 -// Get available tools
49 -const tools = await composio.tools.get('user123', {
50 - toolkits: ['gmail', 'googlecalendar'],
51 - limit: 10,
52 -});
53 -
54 -// Get tools with version control
55 -const versionedTools = await composio.tools.get('user123', {
56 - toolkits: ['gmail'],
57 - toolkitVersions: { gmail: '20250909_00' },
58 -});
59 -
60 -// Get a specific tool
61 -const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');
62 -```
63 -
64 -## Examples
65 -
66 -Check out our complete example implementations:
67 -
68 -- [Basic Vercel Integration](../../examples/vercel/src/index.ts)
69 -
70 -### Basic Chat Completion with Streaming
71 -
72 -```typescript
73 -import { Composio } from '@composio/core';
74 -import { VercelProvider } from '@composio/vercel';
75 -import { useChat } from 'ai/react';
76 -
77 -// Initialize Composio with Vercel provider
78 -const composio = new Composio({
79 - apiKey: process.env.COMPOSIO_API_KEY,
80 - provider: new VercelProvider()
81 -});
82 -
83 -// In your React component
84 -function ChatComponent() {
85 - const { messages, input, handleInputChange, handleSubmit } = useChat({
86 - api: '/api/chat',
87 - });
88 -
89 - return (
90 - <div>
91 - {messages.map(m => (
92 - <div key={m.id}>
93 - {m.role === 'user' ? 'User: ' : 'AI: '}
94 - {m.content}
95 - </div>
96 - ))}
97 -
98 - <form onSubmit={handleSubmit}>
99 - <input
100 - value={input}
101 - onChange={handleInputChange}
102 - placeholder="Say something..."
103 - />
104 - <button type="submit">Send</button>
105 - </form>
106 - </div>
107 - );
108 -}
109 -
110 -// In your API route (e.g. app/api/chat/route.ts)
111 -import { streamText } from 'ai';
112 -import { openai } from '@ai-sdk/openai';
113 -
114 -export async function POST(req: Request) {
115 - const { messages } = await req.json();
116 - const tools = await composio.tools.get('user123', {
117 - toolkits: ['gmail'],
118 - });
119 -
120 - const result = streamText({
121 - model: openai('gpt-4'),
122 - messages,
123 - tools,
124 - });
125 -
126 - return result.toDataStreamResponse();
127 -}
8 +npm install @composio/core @composio/vercel ai @ai-sdk/anthropic
9 ```
10
130 -### Tool Execution with Streaming
11 +`@ai-sdk/anthropic` powers the example below; swap in any AI SDK model package.
12
132 -```typescript
133 -import { Composio } from '@composio/core';
134 -import { VercelProvider } from '@composio/vercel';
135 -import { streamText } from 'ai';
136 -
137 -const composio = new Composio({
138 - apiKey: process.env.COMPOSIO_API_KEY,
139 - provider: new VercelProvider(),
140 -});
13 +Set two environment variables:
14
142 -// Example API route that handles tool execution
143 -export async function POST(req: Request) {
144 - const { messages } = await req.json();
145 - const tools = await composio.tools.get('user123', {
146 - toolkits: ['gmail', 'googlecalendar'],
147 - });
148 -
149 - const stream = streamText({
150 - model: openai('gpt-4'),
151 - messages,
152 - tools,
153 - callbacks: {
154 - onToolCall: async tool => {
155 - // Execute the tool and return result
156 - return await composio.provider.executeToolCall(tool);
157 - },
158 - },
159 - });
160 -
161 - return stream.toDataStreamResponse();
162 -}
163 -```
15 +- `COMPOSIO_API_KEY` from the [Composio dashboard](https://dashboard.composio.dev/settings)
16 +- `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys) (or the key for your chosen model provider)
17
165 -## Provider Configuration
18 +## Quickstart
19
167 -The Vercel provider can be configured with various options:
20 +Create a session for your user, pass its tools to the AI SDK, and cap the run with `stopWhen`:
21
22 ```typescript
170 -const provider = new VercelProvider({
171 - // Default model configuration
172 - model: openai('gpt-4'),
173 - // Custom execution modifiers
174 - modifiers: {
175 - beforeExecute: params => {
176 - // Transform parameters before execution
177 - return params;
178 - },
179 - afterExecute: response => {
180 - // Transform response after execution
181 - return response;
182 - },
183 - },
184 -});
185 -```
23 +import { anthropic } from "@ai-sdk/anthropic";
24 +import { Composio } from "@composio/core";
25 +import { VercelProvider } from "@composio/vercel";
26 +import { generateText, stepCountIs } from "ai";
27
187 -### Strict Mode
28 +const composio = new Composio({ provider: new VercelProvider() });
29
189 -When using tools with Vercel AI SDK, you might need to ensure that all tool parameters are marked as required. This is because Vercel AI SDK's function calling implementation requires all fields to be marked as required. You can enable strict mode when fetching tools to automatically remove all non-required properties from both input and output parameters:
30 +// Each session is scoped to one of your users
31 +const session = await composio.create("user_123");
32 +const tools = await session.tools();
33
191 -```typescript
192 -// Get tools with strict mode enabled
193 -const tools = await composio.tools.get('user123', {
194 - toolkits: ['gmail', 'googlecalendar'],
195 - strict: true, // This will remove all non-required properties from tool parameters
34 +const { text } = await generateText({
35 + model: anthropic("claude-sonnet-4-6"),
36 + tools,
37 + prompt: "Summarize my emails from today",
38 + stopWhen: stepCountIs(10),
39 });
40
198 -// Use these tools with Vercel AI SDK
199 -const stream = streamText({
200 - model: openai('gpt-4'),
201 - messages,
202 - tools, // These tools will only have required parameters
203 -});
41 +console.log(text);
42 ```
43
206 -For more information about strict mode in function calling, see [OpenAI's documentation](https://platform.openai.com/docs/guides/function-calling#strict-mode).
207 -
208 -## API Reference
44 +For multi-turn conversations, store `session.sessionId` and reuse it with `composio.use(sessionId)` instead of creating a new session each turn.
45
210 -### VercelProvider Class
46 +## Strict mode
47
212 -The `VercelProvider` class extends `BaseComposioProvider` and provides Vercel AI SDK-specific functionality.
213 -
214 -#### Methods
215 -
216 -##### `executeToolCall(tool: ToolCall): Promise<string>`
217 -
218 -Executes a tool call and returns the result.
219 -
220 -```typescript
221 -const result = await provider.executeToolCall(toolCall);
222 -```
223 -
224 -##### `handleToolCalls(stream: AIStream): AsyncGenerator<AIStreamEvent>`
225 -
226 -Handles tool calls from a stream and yields events.
48 +Some models reject tool schemas that contain optional parameters. Pass `strict: true` to drop every non-required property from each tool's input schema before it reaches the AI SDK:
49
50 ```typescript
229 -for await (const event of provider.handleToolCalls(stream)) {
230 - // Handle events
231 -}
51 +const composio = new Composio({ provider: new VercelProvider({ strict: true }) });
52 ```
53
234 -## Contributing
235 -
236 -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
237 -
238 -## License
239 -
240 -ISC License
241 -
242 -## Support
54 +## Links
55
244 -For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
56 +- [Vercel AI SDK provider docs](https://docs.composio.dev/docs/providers/vercel)
57 +- [Composio quickstart](https://docs.composio.dev/docs/quickstart)
58 +- [Composio documentation](https://docs.composio.dev)
ts/packages/slim/README.md
+2 -2
@@ -2,7 +2,7 @@
2
3 Slim build of the Composio TypeScript core SDK.
4
5 -`@composio/core` intentionally publishes SDK docs and TypeScript source for users who want an inspectable/debuggable package. `@composio/slim` publishes the same built runtime/type artifacts without the packaged `docs/` or `src/` trees.
5 +`@composio/core` intentionally ships its TypeScript source and SDK docs inside the npm package so coding agents (and humans) can inspect and debug the SDK straight from `node_modules`. That inspectability costs install size. `@composio/slim` publishes the same built runtime and type artifacts without the packaged `src/` and `docs/` trees, so it installs smaller while behaving identically.
6
7 ```bash
8 pnpm add @composio/slim
@@ -14,4 +14,4 @@ import { Composio } from '@composio/slim';
14 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
15 ```
16
17 -The API mirrors `@composio/core` for consumers that prefer a smaller installed package.
17 +The API mirrors `@composio/core` for consumers that prefer a smaller installed package. See the [`@composio/core` README](https://github.com/ComposioHQ/composio/tree/next/ts/packages/core) for usage.