Supabase SQL Agent

With Composio’s managed authentication and tool calling, it’s easy to build AI agents that interact with the real world while reducing boilerplate for setup and authentication management. This guide will walk you through using the Supabase CLI agent built with Composio and LlamaIndex.

Requirements

  • Python 3.9+
  • UV (recommended) or pip
  • Composio API key
  • OpenAI API key
  • Understanding of building AI agents (Preferably with LlamaIndex)

Build an agent to perform Supabase tasks

1from composio import Composio
2from composio_llamaindex import LlamaIndexProvider
3
4from llama_index.llms.openai import OpenAI
5from llama_index.core.agent.workflow import FunctionAgent
6from llama_index.core.workflow import Context
7
8
9def create_agent(user_id: str, composio_client: Composio[LlamaIndexProvider]):
10 """
11 Create a function agent that can perform Supabase tasks.
12 """
13
14 # Setup client
15 llm = OpenAI(model="gpt-4-turbo")
16
17 # Get All the tools
18 tools = composio_client.tools.get(
19 user_id=user_id,
20 tools=[
21 "SUPABASE_LIST_ALL_PROJECTS",
22 "SUPABASE_BETA_RUN_SQL_QUERY",
23 ],
24 )
25
26 agent = FunctionAgent(
27 tools=tools,
28 llm=llm,
29 system_prompt=(
30 "You are a helpful assistant that can help with supabase queries."
31 ),
32 )
33
34 # Since this is a continuosly running agent, we need to maintain state across
35 # different user messages
36 ctx = Context(workflow=agent)
37 return agent, ctx

This agent can convert your natural language queries to SQL queries and execute them on supabase for you. For you agent to be able to execute queries, you need to authenticate the agent for supabase.

Authenticating users

To authenticate your users with Composio you need an auth config for the given app, In this case you need one for supabase. You can create and manage auth configs from the dashboard. Composio platform provides composio managed authentication for some apps to help you fast-track your development, supabase being one of them. You can use these default auth configs for development, but for production you should always use your own oauth app configuration.

Using dashboard is the preferred way of managing authentication configs, but if you want to do it manually you can follow the guide below

Click to expand

To create an authentication config for supabase you need client_id and client_secret from your from your Google OAuth Console. Once you have the required credentials you can use the following piece of code to set up authentication for supabase.

1from composio import Composio
2from composio_langchain import LangchainProvider
3
4def create_auth_config(composio_client: Composio[OpenAIProvider]):
5 """
6 Create a auth config for the supabase toolkit.
7 """
8 client_id = os.getenv("SUPABASE_CLIENT_ID")
9 client_secret = os.getenv("SUPABASE_CLIENT_SECRET")
10 if not client_id or not client_secret:
11 raise ValueError("SUPABASE_CLIENT_ID and SUPABASE_CLIENT_SECRET must be set")
12
13 return composio_client.auth_configs.create(
14 toolkit="supabase",
15 options={
16 "name": "default_supabase_auth_config",
17 "type": "use_custom_auth",
18 "auth_scheme": "OAUTH2",
19 "credentials": {
20 "client_id": client_id,
21 "client_secret": client_secret,
22 },
23 },
24 )

This will create an authentication config for supabase which you can use to authenticate your users for your app. Ideally you should just create one authentication object per project, so check for an existing auth config before you create a new one.

1def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
2 """
3 Fetch the auth config for a given user id.
4 """
5 auth_configs = composio_client.auth_configs.list()
6 for auth_config in auth_configs.items:
7 if auth_config.toolkit == "supabase":
8 return auth_config
9
10 return None

Once you have authentication management in place, we can start with connecting your users to your supabase app. Let’s implement a function to connect the users to your supabase app via composio.

1# Function to initiate a connected account
2def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
3 """
4 Create a connection for a given user id and auth config id.
5 """
6 # Fetch or create the auth config for the supabase toolkit
7 auth_config = fetch_auth_config(composio_client=composio_client)
8 if not auth_config:
9 auth_config = create_auth_config(composio_client=composio_client)
10
11 # Create a connection for the user
12 return composio_client.connected_accounts.initiate(
13 user_id=user_id,
14 auth_config_id=auth_config.id,
15 )

Now, when creating tools for your agent always check if the user already has a connected account before creating a new one.

1def check_connected_account_exists(
2 composio_client: Composio[LangchainProvider],
3 user_id: str,
4):
5 """
6 Check if a connected account exists for a given user id.
7 """
8 # Fetch all connected accounts for the user
9 connected_accounts = composio_client.connected_accounts.list(
10 user_ids=[user_id],
11 toolkit_slugs=["SUPABASE"],
12 )
13
14 # Check if there's an active connected account
15 for account in connected_accounts.items:
16 if account.status == "ACTIVE":
17 return True
18
19 # Ideally you should not have inactive accounts, but if you do, you should delete them
20 print(f"[warning] inactive account {account.id} found for user id: {user_id}")
21 return False

Create a chat loop

1async def run_loop(user_id: str):
2 # Initialize composio client.
3 composio_client = Composio(provider=LlamaIndexProvider())
4
5 # Setup connection if required
6 if not check_connected_account_exists(
7 composio_client=composio_client,
8 user_id=user_id,
9 ):
10 connection_request = create_connection(
11 composio_client=composio_client,
12 user_id=user_id,
13 )
14 print(
15 f"Authenticate with the following link: {connection_request.redirect_url}"
16 )
17
18 # Create agent
19 agent, ctx = create_agent(
20 user_id=user_id,
21 composio_client=composio_client,
22 )
23
24 # Run a simple REPL loop
25 while True:
26 user_input = input("user > ")
27 if user_input.lower() == "exit":
28 break
29
30 result = await agent.run(user_msg=user_input, ctx=ctx)
31 print("agent > ", result)
32 print("Exiting...")

Using Composio for managed auth and tools

Composio reduces a lot of boilerplate for building AI agents with ability access and use a wide variety of apps. For example in this cookbook, to build supabase integration without composio you would have to write code to

  • manage supabase oauth app
  • manage user connections
  • tools for your agents to interact with supabase

Using composio simplifies all of the above to a few lines of code as we’ve seen the cookbook.

Best practices

🔒 User Management:

  • Use unique, consistent user_id values for each person
  • Each user maintains their own supabase connection
  • User IDs can be email addresses, usernames, or any unique identifier

Troubleshooting

Connection Issues:

  • Ensure your .env file has valid COMPOSIO_API_KEY and OPENAI_API_KEY
  • Check that the user has completed supabase authorization
  • Verify the user_id matches exactly between requests

API Errors:

  • Check the server logs for detailed error messages
  • Ensure request payloads match the expected format
  • Visit /docs endpoint for API schema validation