1
-
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)