Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
docs: rewrite supabase SQL agent cookbook to use sessions and include regions
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sushmitha Mallesh committed
Feb 25, 2026 at 18:50 UTC
3f456d5275d9861125492696e0e6c085665b4dab
3 files changed
+134
-222
docs/content/cookbooks/slack-summariser.mdx
+1
-1
@@ -1,6 +1,6 @@
1
---
2
title: Slack Summarizer
3
-description: Build a Python script that connects to Slack and summarizes channel messages using Composio and the OpenAI Agents SDK
3
+description: Build an agent that summarizes Slack channel messages using Composio
4
---
5
6
[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/slack-summariser)
docs/content/cookbooks/supabase-sql-agent.mdx
+49
-221
@@ -3,252 +3,80 @@ title: Supabase SQL Agent
3
description: Build an agent that executes SQL queries on Supabase using natural language
4
---
5
6
-With Composio's managed authentication and tool calling, it's easy to build
7
-AI agents that interact with the real world while reducing boilerplate for
8
-setup and authentication management. This guide will walk you through using
9
-the Supabase CLI agent built with `Composio` and `LlamaIndex`.
6
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/supabase-sql-agent)
7
8
+This cookbook builds a CLI agent that connects to your Supabase account and lets you query your databases using natural language. The agent translates plain English into SQL, runs it against your project, and explains the results. We'll use **scoped sessions** to limit the agent to Supabase tools only.
9
12
-## Requirements
10
+## Prerequisites
11
12
* Python 3.10+
15
-* [UV](https://docs.astral.sh/uv/getting-started/installation/) (recommended) or pip
16
-* Composio API key
17
-* OpenAI API key
18
-* Understanding of building AI agents (Preferably with LlamaIndex)
19
-
20
-## Build an agent to perform Supabase tasks
21
-
22
-```python
23
-from composio import Composio
24
-from composio_llamaindex import LlamaIndexProvider
25
-
26
-from llama_index.llms.openai import OpenAI
27
-from llama_index.core.agent.workflow import FunctionAgent
28
-from llama_index.core.workflow import Context
29
-
30
-
31
-def create_agent(user_id: str, composio_client: Composio[LlamaIndexProvider]):
32
- """
33
- Create a function agent that can perform Supabase tasks.
34
- """
35
-
36
- # Setup client
37
- llm = OpenAI(model="gpt-5")
38
-
39
- # Get All the tools
40
- tools = composio_client.tools.get(
41
- user_id=user_id,
42
- tools=[
43
- "SUPABASE_LIST_ALL_PROJECTS",
44
- "SUPABASE_BETA_RUN_SQL_QUERY",
45
- ],
46
- )
47
-
48
- agent = FunctionAgent(
49
- tools=tools,
50
- llm=llm,
51
- system_prompt=(
52
- "You are a helpful assistant that can help with supabase queries."
53
- ),
54
- )
55
-
56
- # Since this is a continuosly running agent, we need to maintain state across
57
- # different user messages
58
- ctx = Context(workflow=agent)
59
- return agent, ctx
13
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
14
+* [Composio API key](https://platform.composio.dev/settings)
15
+* [OpenAI API key](https://platform.openai.com/api-keys)
16
+
17
+## Project setup
18
+
19
+Create a new project and install dependencies:
20
+
21
+```bash
22
+mkdir composio-supabase-agent && cd composio-supabase-agent
23
+uv init && uv add composio composio-openai-agents openai-agents
24
```
25
62
-This agent can convert your natural language queries to SQL queries and execute
63
-them on supabase for you. For you agent to be able to execute queries, you need
64
-to authenticate the agent for supabase.
26
+Add your API keys to a `.env` file:
27
28
+```bash title=".env"
29
+COMPOSIO_API_KEY=your_composio_api_key
30
+OPENAI_API_KEY=your_openai_api_key
31
+```
32
67
-## Authenticating users
33
+## Setting up the client
34
69
-To authenticate your users with Composio you need an auth config for the given
70
-app, In this case you need one for supabase. You can create and manage auth configs
71
-from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=supabase).
72
-Composio platform provides composio managed authentication for some apps to help
73
-you fast-track your development, `supabase` being one of them. You can use these
74
-default auth configs for development, but for production you should always use
75
-your own oauth app configuration.
35
+`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects.
36
77
-Using dashboard is the preferred way of managing authentication configs, but if
78
-you want to do it manually you can follow the guide below
37
+<include>../../examples/supabase-sql-agent/main.py#setup</include>
38
80
-<details>
39
+## Connecting to Supabase
40
82
-<summary>Click to expand</summary>
41
+Before running queries, the user needs to connect their Supabase account. The `connect` function creates a scoped session with `toolkits=["supabase"]` and checks the connection status via `session.toolkits()`. If Supabase is not connected, `session.authorize("supabase")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
42
84
----
43
+<include>../../examples/supabase-sql-agent/main.py#connect</include>
44
86
-To create an authentication config for `supabase` you need `client_id` and `client_secret`
87
-from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
88
-Once you have the required credentials you can use the following piece of
89
-code to set up authentication for `supabase`.
90
-
91
-```python
92
-from composio import Composio
93
-from composio_langchain import LangchainProvider
94
-
95
-def create_auth_config(composio_client: Composio[OpenAIProvider]):
96
- """
97
- Create a auth config for the supabase toolkit.
98
- """
99
- client_id = os.getenv("SUPABASE_CLIENT_ID")
100
- client_secret = os.getenv("SUPABASE_CLIENT_SECRET")
101
- if not client_id or not client_secret:
102
- raise ValueError("SUPABASE_CLIENT_ID and SUPABASE_CLIENT_SECRET must be set")
103
-
104
- return composio_client.auth_configs.create(
105
- toolkit="supabase",
106
- options={
107
- "name": "default_supabase_auth_config",
108
- "type": "use_custom_auth",
109
- "auth_scheme": "OAUTH2",
110
- "credentials": {
111
- "client_id": client_id,
112
- "client_secret": client_secret,
113
- },
114
- },
115
- )
116
-```
45
+## Querying with natural language
46
118
-This will create an authentication config for `supabase` which you can use to
119
-authenticate your users for your app. Ideally you should just create one
120
-authentication object per project, so check for an existing auth config
121
-before you create a new one.
122
-
123
-```python
124
-def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
125
- """
126
- Fetch the auth config for a given user id.
127
- """
128
- auth_configs = composio_client.auth_configs.list()
129
- for auth_config in auth_configs.items:
130
- if auth_config.toolkit == "supabase":
131
- return auth_config
132
-
133
- return None
134
-```
135
-</details>
136
-
137
-Once you have authentication management in place, we can start with connecting
138
-your users to your `supabase` app. Let's implement a function to connect the users
139
-to your `supabase` app via composio.
140
-
141
-```python
142
-# Function to initiate a connected account
143
-def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
144
- """
145
- Create a connection for a given user id and auth config id.
146
- """
147
- # Fetch or create the auth config for the supabase toolkit
148
- auth_config = fetch_auth_config(composio_client=composio_client)
149
- if not auth_config:
150
- auth_config = create_auth_config(composio_client=composio_client)
151
-
152
- # Create a connection for the user
153
- return composio_client.connected_accounts.initiate(
154
- user_id=user_id,
155
- auth_config_id=auth_config.id,
156
- )
157
-```
47
+With Supabase connected, the `query` function creates a session scoped to `toolkits=["supabase"]` and grabs the tools. We hand them to an agent and run an interactive loop where the user types questions and the agent translates them into SQL.
48
159
-Now, when creating tools for your agent always check if the user already has a
160
-connected account before creating a new one.
161
-
162
-```python
163
-def check_connected_account_exists(
164
- composio_client: Composio[LangchainProvider],
165
- user_id: str,
166
-):
167
- """
168
- Check if a connected account exists for a given user id.
169
- """
170
- # Fetch all connected accounts for the user
171
- connected_accounts = composio_client.connected_accounts.list(
172
- user_ids=[user_id],
173
- toolkit_slugs=["SUPABASE"],
174
- )
175
-
176
- # Check if there's an active connected account
177
- for account in connected_accounts.items:
178
- if account.status == "ACTIVE":
179
- return True
180
-
181
- # Ideally you should not have inactive accounts, but if you do, you should delete them
182
- print(f"[warning] inactive account {account.id} found for user id: {user_id}")
183
- return False
184
-```
49
+<include>../../examples/supabase-sql-agent/main.py#query</include>
50
51
+## Complete script
52
187
-## Create a chat loop
188
-
189
-```python
190
-async def run_loop(user_id: str):
191
- # Initialize composio client.
192
- composio_client = Composio(provider=LlamaIndexProvider())
193
-
194
- # Setup connection if required
195
- if not check_connected_account_exists(
196
- composio_client=composio_client,
197
- user_id=user_id,
198
- ):
199
- connection_request = create_connection(
200
- composio_client=composio_client,
201
- user_id=user_id,
202
- )
203
- print(
204
- f"Authenticate with the following link: {connection_request.redirect_url}"
205
- )
206
-
207
- # Create agent
208
- agent, ctx = create_agent(
209
- user_id=user_id,
210
- composio_client=composio_client,
211
- )
212
-
213
- # Run a simple REPL loop
214
- while True:
215
- user_input = input("user > ")
216
- if user_input.lower() == "exit":
217
- break
218
-
219
- result = await agent.run(user_msg=user_input, ctx=ctx)
220
- print("agent > ", result)
221
- print("Exiting...")
222
-```
53
+Here is everything together:
54
224
-## Using Composio for managed auth and tools
55
+<include>../../examples/supabase-sql-agent/main.py</include>
56
226
-Composio reduces a lot of boilerplate for building AI agents with ability access
227
-and use a wide variety of apps. For example in this cookbook, to build `supabase`
228
-integration without composio you would have to write code to
57
+## Running the script
58
230
-- manage `supabase` oauth app
231
-- manage user connections
232
-- tools for your agents to interact with `supabase`
59
+First, connect your Supabase account:
60
234
-Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
61
+```bash
62
+uv run --env-file .env python main.py connect default
63
+```
64
236
-## Best practices
65
+If Supabase is not connected yet, you'll get an OAuth URL. Open it in your browser and authorize the app.
66
238
-**🔒 User Management**:
67
+Then start the interactive query agent:
68
240
-- Use unique, consistent `user_id` values for each person
241
-- Each user maintains their own supabase connection
242
-- User IDs can be email addresses, usernames, or any unique identifier
69
+```bash
70
+uv run --env-file .env python main.py query default
71
+```
72
244
-## Troubleshooting
73
+Try asking things like:
74
246
-**Connection Issues**:
247
-- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
248
-- Check that the user has completed `supabase` authorization
249
-- Verify the user_id matches exactly between requests
75
+```
76
+you > List all my Supabase projects
77
+you > Show me all tables in my default project
78
+you > How many users signed up this week?
79
+you > What are the top 10 most recent orders?
80
+```
81
251
-**API Errors**:
252
-- Check the server logs for detailed error messages
253
-- Ensure request payloads match the expected format
254
-- Visit `/docs` endpoint for API schema validation
82
+Type `exit` to quit.
docs/examples/supabase-sql-agent/main.py
new
+84
@@ -0,0 +1,84 @@
1
+import sys
2
+
3
+# region setup
4
+from agents import Agent, Runner
5
+from composio import Composio
6
+from composio_openai_agents import OpenAIAgentsProvider
7
+
8
+composio = Composio(provider=OpenAIAgentsProvider())
9
+# endregion setup
10
+
11
+
12
+# region connect
13
+def connect(user_id: str):
14
+ """Check if Supabase is connected. If not, start OAuth and wait."""
15
+ session = composio.create(user_id=user_id, toolkits=["supabase"])
16
+ toolkits = session.toolkits()
17
+
18
+ for t in toolkits.items:
19
+ if t.slug == "supabase" and t.connection and t.connection.is_active:
20
+ print("Supabase is already connected.")
21
+ return
22
+
23
+ connection_request = session.authorize("supabase")
24
+ print(f"Open this URL to connect Supabase:\n{connection_request.redirect_url}")
25
+ connection_request.wait_for_connection()
26
+ print("Connected.")
27
+# endregion connect
28
+
29
+
30
+# region query
31
+def query(user_id: str):
32
+ """Interactive loop: ask questions in natural language, get SQL results."""
33
+ session = composio.create(user_id=user_id, toolkits=["supabase"])
34
+ tools = session.tools()
35
+
36
+ agent = Agent(
37
+ name="Supabase SQL Agent",
38
+ instructions=(
39
+ "You are a Supabase SQL assistant. You help users query their Supabase "
40
+ "databases using natural language. First list the user's projects to find "
41
+ "the right database, then translate their questions into SQL queries and "
42
+ "run them. Always explain the results clearly."
43
+ ),
44
+ tools=tools,
45
+ )
46
+
47
+ print("Supabase SQL Agent (type 'exit' to quit)")
48
+ print("-" * 45)
49
+
50
+ last_response_id = None
51
+ while True:
52
+ user_input = input("you > ")
53
+ if user_input.strip().lower() == "exit":
54
+ break
55
+
56
+ result = Runner.run_sync(
57
+ starting_agent=agent,
58
+ input=user_input,
59
+ previous_response_id=last_response_id,
60
+ )
61
+ last_response_id = result.last_response_id
62
+ print(f"agent > {result.final_output}\n")
63
+# endregion query
64
+
65
+
66
+if __name__ == "__main__":
67
+ if len(sys.argv) < 2:
68
+ print("Usage:")
69
+ print(" python main.py connect <user_id>")
70
+ print(" python main.py query <user_id>")
71
+ sys.exit(1)
72
+
73
+ command = sys.argv[1]
74
+
75
+ if command == "connect":
76
+ user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
77
+ connect(user_id)
78
+ elif command == "query":
79
+ user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
80
+ query(user_id)
81
+ else:
82
+ print(f"Unknown command: {command}")
83
+ print("Use 'connect' or 'query'.")
84
+ sys.exit(1)