Skip to content

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 gmail labeler cookbook with session paradigm and Claude Agent SDK

Sushmitha Malleshad627c7955f1
diff --git a/docs/content/cookbooks/gmail-labeler.mdx b/docs/content/cookbooks/gmail-labeler.mdx
index 61d8e3360..ee4ffe549 100644
--- a/docs/content/cookbooks/gmail-labeler.mdx
+++ b/docs/content/cookbooks/gmail-labeler.mdx
@@ -1,381 +1,99 @@
---
title: Gmail Labeler
-description: Build an agent that automatically labels incoming Gmail messages using triggers
+description: Build a Python script that listens for new Gmail messages and labels them using Composio and the Claude Agent SDK
---
-With Composio's managed authentication, tool calling and triggers, it's easy to
-build the AI agents that can interact and react the real world events reducing
-the boilerplate required to setup and manage the authentication. This cookbook
-will walk you through the process of building agents using `Composio`, `LangChain`.
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/gmail-labeler)
+
+This cookbook builds a standalone Python script that connects to Gmail, listens for incoming messages via Composio triggers, and uses Claude to automatically label each email. We'll use **scoped sessions** to limit the agent to Gmail tools only.
## Prerequisites
-* Python3.x
+* Python 3.10+
* [UV](https://docs.astral.sh/uv/getting-started/installation/)
-* Composio API key
-* OpenAI API key
-* Understanding of building AI agents (Preferably with LangChain)
-
-## Build gmail agent to label your messages
-
-```python
-from composio import Composio
-from composio_langchain import LangchainProvider
-
-from langchain import hub
-from langchain.agents import AgentExecutor, create_openai_functions_agent
-from langchain_openai import ChatOpenAI
-
-
-def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
- """
- Create an agent for a given user id.
- """
- # Step 1: Get all the tools
- tools = composio_client.tools.get(
- user_id=user_id,
- tools=[
- "GMAIL_LIST_LABELS",
- "GMAIL_ADD_LABEL_TO_EMAIL",
- "GMAIL_CREATE_LABEL",
- ],
- )
-
- # Step 2: Pull relevant agent prompt.
- prompt = hub.pull("hwchase17/openai-functions-agent")
-
- # Step 3: Initialize chat model.
- openai_client = ChatOpenAI(model="gpt-5")
-
- # Step 4: Define agent
- return AgentExecutor(
- agent=create_openai_functions_agent(
- openai_client,
- tools,
- prompt,
- ),
- tools=tools,
- verbose=False,
- )
-```
+* [Composio API key](https://platform.composio.dev/settings)
+* [Anthropic API key](https://console.anthropic.com/settings/keys)
-## Authenticating users
-
-To authenticate your users with Composio you need an auth config for the given
-app, In this case you need one for gmail. You can create and manage auth configs
-from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=gmail).
-Composio platform provides composio managed authentication for some apps to help
-you fast-track your development, `gmail` 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
-
-<details>
-
-<summary>Click to expand</summary>
-
-To create an authentication config for `gmail` you need `client_id` and `client_secret`
-from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
-Once you have the required credentials you can use the following piece of
-code to set up authentication for `gmail`.
-
-```python
-from composio import Composio
-from composio_langchain import LangchainProvider
-
-def create_auth_config(composio_client: Composio[OpenAIProvider]):
- """
- Create a auth config for the gmail toolkit.
- """
- client_id = os.getenv("GMAIL_CLIENT_ID")
- client_secret = os.getenv("GMAIL_CLIENT_SECRET")
- if not client_id or not client_secret:
- raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
-
- return composio_client.auth_configs.create(
- toolkit="gmail",
- options={
- "name": "default_gmail_auth_config",
- "type": "use_custom_auth",
- "auth_scheme": "OAUTH2",
- "credentials": {
- "client_id": client_id,
- "client_secret": client_secret,
- },
- },
- )
-```
+## Project setup
-This will create an authentication config for `gmail` 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.
-
-```python
-def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
- """
- Fetch the auth config for a given user id.
- """
- auth_configs = composio_client.auth_configs.list()
- for auth_config in auth_configs.items:
- if auth_config.toolkit == "gmail":
- return auth_config
-
- return None
-```
-</details>
-
-Once you have authentication management in place, we can start with connecting
-your users to your `gmail` app. Let's implement a function to connect the users
-to your `gmail` app via composio.
-
-```python
-# Function to initiate a connected account
-def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
- """
- Create a connection for a given user id and auth config id.
- """
- # Fetch or create the auth config for the gmail toolkit
- auth_config = fetch_auth_config(composio_client=composio_client)
- if not auth_config:
- auth_config = create_auth_config(composio_client=composio_client)
-
- # Create a connection for the user
- return composio_client.connected_accounts.initiate(
- user_id=user_id,
- auth_config_id=auth_config.id,
- )
-```
+Create a new project and install dependencies:
-Now, when creating tools for your agent always check if the user already has a
-connected account before creating a new one.
-
-```python
-def check_connected_account_exists(
- composio_client: Composio[LangchainProvider],
- user_id: str,
-):
- """
- Check if a connected account exists for a given user id.
- """
- # Fetch all connected accounts for the user
- connected_accounts = composio_client.connected_accounts.list(
- user_ids=[user_id],
- toolkit_slugs=["GMAIL"],
- )
-
- # Check if there's an active connected account
- for account in connected_accounts.items:
- if account.status == "ACTIVE":
- return True
-
- # Ideally you should not have inactive accounts, but if you do, you should delete them
- print(f"[warning] inactive account {account.id} found for user id: {user_id}")
- return False
+```bash
+mkdir composio-gmail-labeler && cd composio-gmail-labeler
+uv init && uv add composio composio-claude-agent-sdk claude-agent-sdk
```
+Add your API keys to a `.env` file:
-## Creating Triggers
-
-You can use triggers to make your agents react to real world events. In this example,
-we will use triggers to invoke your agent everytime there's a new message in your
-gmail inbox.
-
-```python
-# Create a new trigger
-def create_trigger(
- composio_client: Composio[LangchainProvider],
- connected_account_id: str,
-) -> str:
- """
- Create a trigger.
- """
- response = composio_client.triggers.create(
- slug="GMAIL_NEW_GMAIL_MESSAGE",
- connected_account_id=connected_account_id,
- trigger_config={},
- )
- return response.trigger_id
+```bash title=".env"
+COMPOSIO_API_KEY=your_composio_api_key
+ANTHROPIC_API_KEY=your_anthropic_api_key
```
-When creating triggers, make sure there are no duplicate triggers. Use following
-code as reference for checking if trigger for given connected account exists or not.
-
-```python
-def check_trigger_exists(
- composio_client: Composio[LangchainProvider],
- connected_account_id: str,
-) -> t.Optional[str]:
- """
- Check if a trigger exists.
- """
- triggers = composio_client.triggers.list_active(
- trigger_names=["GMAIL_NEW_GMAIL_MESSAGE"],
- connected_account_ids=[connected_account_id],
- )
- for trigger in triggers.items:
- return trigger.id
- return None
-```
+## Setting up the client
+
+`Composio` takes a `ClaudeAgentSDKProvider` so that tools come back in the format the Claude Agent SDK expects.
+
+<include>../../examples/gmail-labeler/main.py#setup</include>
+
+## Connecting to Gmail
+
+Before labeling, we need to make sure the user has connected their Gmail account. The `connect` function creates a scoped session with `toolkits=["gmail"]` and checks the connection status via `session.toolkits()`. If Gmail is not connected, `session.authorize("gmail")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
+
+<include>../../examples/gmail-labeler/main.py#connect</include>
+
+## Creating a trigger
+
+The `create_trigger` function sets up a `GMAIL_NEW_GMAIL_MESSAGE` trigger that fires whenever a new email arrives. It prints the trigger ID you'll need for the listener.
+<include>../../examples/gmail-labeler/main.py#trigger</include>
-Once trigger is created, you can listen to events using a trigger subscription.
+<Callout>
+When you pass a `user_id`, the SDK automatically resolves the user's connected account for Gmail. You can also pass a `connected_account_id` directly for more control.
+</Callout>
-```python
-# Create subscription object
-trigger_subscription = composio_client.triggers.subscribe()
+## Labeling with Claude
-# Register event handler
-@trigger_subscription.handle(
- trigger_id="<TRIGGER_ID>", # Filter out events that does not belong this trigger id
- trigger_slug="GMAIL_NEW_GMAIL_MESSAGE",
-)
-def handle_event(event: TriggerEvent):
- print("> Received email with subject: ", event["payload"]["subject"])
+For each incoming email, `label_email` gets Gmail tools from `session.tools()`, wraps them in an MCP server with `create_sdk_mcp_server()`, and hands them to a Claude agent. The agent lists existing labels, picks the best fit (or creates a new one), and applies it.
-# Wait for events
-trigger_subscription.wait_forever()
+<include>../../examples/gmail-labeler/main.py#label</include>
+
+## Listening for emails
+
+`composio.triggers.subscribe()` opens a WebSocket connection. When a new email arrives, the handler calls `label_email` to classify and label it.
+
+<include>../../examples/gmail-labeler/main.py#listen</include>
+
+<Callout>
+SDK subscriptions are ideal for local development and testing. For production, use [webhooks](/docs/setting-up-triggers/subscribing-to-events) to receive trigger events at a URL endpoint.
+</Callout>
+
+## Complete script
+
+Here is everything together:
+
+<include>../../examples/gmail-labeler/main.py</include>
+
+## Running the script
+
+First, connect your Gmail account:
+
+```bash
+uv run --env-file .env python main.py connect default
```
-## Putting everything together
-
-Let's put together everything by making the agent react to new messages in your
-inbox.
-
-```python
-# Create a trigger subscription factory
-
-def create_trigger_subscription(
- composio_client: Composio[LangchainProvider],
- trigger_slug: str,
- trigger_id: str,
- agent: AgentExecutor,
-):
- """
- Create a trigger subscription for the given agent.
- """
- trigger_subscription = composio_client.triggers.subscribe()
-
- @trigger_subscription.handle(
- trigger_slug=trigger_slug,
- trigger_id=trigger_id,
- )
- def handle_event(event: TriggerEvent):
- print("> Received email with subject: ", event["payload"]["subject"])
- result = agent.invoke(
- input={
- "input": APPLY_NEW_LABEL.format( # Check `gmail_labeler/prompt.py`
- message_id=event["payload"]["id"],
- message_subject=event["payload"]["subject"],
- message_text=event["payload"]["message_text"],
- )
- }
- )
- print("> Result: ", result["output"])
-
- return trigger_subscription
+If Gmail is not connected yet, you'll get an OAuth URL. Open it in your browser and authorize the app. If you've already connected, the script will print "Gmail is already connected."
+
+Next, create a trigger:
+
+```bash
+uv run --env-file .env python main.py trigger default
```
-Package everything as a single entry point.
-
-```python
-def run_agent(user_id: str):
- # Create composio client
- composio_client = Composio(provider=LangchainProvider())
-
- # Validate conected account
- connected_account_id = check_connected_account_exists(composio_client, user_id)
- if connected_account_id is None:
- connection_request = create_connection(composio_client, user_id)
- print(
- f"Authenticate with the following link: {connection_request.redirect_url}"
- )
- connection_request.wait_for_connection()
- connected_account_id = connection_request.id
-
- # Check if trigger exists, create if not
- trigger_id = check_trigger_exists(
- composio_client=composio_client,
- connected_account_id=connected_account_id,
- )
- if trigger_id is None:
- trigger_id = create_trigger(
- composio_client=composio_client,
- connected_account_id=connected_account_id,
- )
-
- # Create agent
- agent = create_agent(user_id=user_id, composio_client=composio_client)
-
- # Create trigger subscription
- trigger_subscription = create_trigger_subscription(
- composio_client=composio_client,
- trigger_slug=GMAIL_NEW_GMAIL_MESSAGE_TRIGGER,
- trigger_id=trigger_id,
- agent=agent,
- )
-
- # Wait forever
- print("Waiting for events...")
- trigger_subscription.wait_forever()
+Then start the listener with the trigger ID from the previous step:
+
+```bash
+uv run --env-file .env python main.py listen default <trigger_id>
```
-To test the above function as CLI, follow the steps below
-
-1. Clone the repository
- ```bash
- git clone [email protected]:composiohq/gmail-labeler
- cd gmail-labeler/
- ```
-2. Setup environment
- ```bash
- cp .env.example .env
- ```
-
- Fill the api keys
- ```dotenv
- COMPOSIO_API_KEY=
- OPENAI_API_KEY=
- ```
-
- Create the virtual env
- ```bash
- make env
- source .venv/bin/activate
- ```
-3. Run the agent
- ```bash
- python gmail_labeler --user-id "default"
- ```
-
-## 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 `gmail` integration without composio you would have to write code to
-- manage `gmail` oauth app
-- manage user connections
-- tools for your agents to interact with `gmail`
-- Infra for listening to changes in your gmail inbox
-
-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 gmail 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 `gmail` 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
+Send yourself an email and watch the terminal — the agent will receive the event, inspect the email, and apply an appropriate label.
diff --git a/docs/examples/gmail-labeler/main.py b/docs/examples/gmail-labeler/main.py
new file mode 100644
index 000000000..4f9c48bd8
--- /dev/null
+++ b/docs/examples/gmail-labeler/main.py
@@ -0,0 +1,124 @@
+import sys
+
+# region setup
+import asyncio
+
+from composio import Composio
+from composio_claude_agent_sdk import ClaudeAgentSDKProvider
+from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, create_sdk_mcp_server
+
+composio = Composio(provider=ClaudeAgentSDKProvider())
+# endregion setup
+
+
+# region connect
+def connect(user_id: str):
+ """Check if Gmail is connected. If not, start OAuth and wait."""
+ session = composio.create(user_id=user_id, toolkits=["gmail"])
+ toolkits = session.toolkits()
+
+ for t in toolkits.items:
+ if t.slug == "gmail" and t.connection and t.connection.is_active:
+ print("Gmail is already connected.")
+ return
+
+ connection_request = session.authorize("gmail")
+ print(f"Open this URL to connect Gmail:\n{connection_request.redirect_url}")
+ connection_request.wait_for_connection()
+ print("Connected.")
+# endregion connect
+
+
+# region trigger
+def create_trigger(user_id: str):
+ """Create a trigger for new Gmail messages."""
+ trigger = composio.triggers.create(
+ slug="GMAIL_NEW_GMAIL_MESSAGE",
+ user_id=user_id,
+ trigger_config={},
+ )
+ print(f"Trigger created: {trigger.trigger_id}")
+ return trigger.trigger_id
+# endregion trigger
+
+
+# region label
+async def label_email(session, message_id: str, subject: str, body: str):
+ """Use Claude to label an incoming email."""
+ tools = session.tools()
+ tool_server = create_sdk_mcp_server(name="composio", version="1.0.0", tools=tools)
+
+ prompt = f"""You received a new email. Analyze it and apply an appropriate label.
+
+Message ID: {message_id}
+Subject: {subject}
+Body: {body}
+
+Steps:
+1. List the existing Gmail labels.
+2. Decide which label fits best, or create a new label if none fit.
+3. Apply the label to this email using its message ID."""
+
+ options = ClaudeAgentOptions(
+ system_prompt="You are an email organizer. Label incoming emails with the most appropriate Gmail label.",
+ permission_mode="bypassPermissions",
+ mcp_servers={"composio": tool_server},
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query(prompt)
+ async for msg in client.receive_response():
+ print(msg)
+# endregion label
+
+
+# region listen
+def listen(user_id: str, trigger_id: str):
+ """Subscribe to trigger events and label incoming emails."""
+ session = composio.create(user_id=user_id, toolkits=["gmail"])
+ subscription = composio.triggers.subscribe()
+
+ @subscription.handle(trigger_id=trigger_id)
+ def handle_event(data):
+ print(f"New email: {data.get('subject', 'No subject')}")
+ asyncio.run(
+ label_email(
+ session,
+ message_id=data.get("id", ""),
+ subject=data.get("subject", ""),
+ body=data.get("message_text", ""),
+ )
+ )
+
+ print("Listening for new emails...")
+ subscription.wait_forever()
+# endregion listen
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Usage:")
+ print(" python main.py connect <user_id>")
+ print(" python main.py trigger <user_id>")
+ print(" python main.py listen <user_id> <trigger_id>")
+ sys.exit(1)
+
+ command = sys.argv[1]
+
+ if command == "connect":
+ uid = sys.argv[2] if len(sys.argv) > 2 else "default"
+ connect(uid)
+ elif command == "trigger":
+ uid = sys.argv[2] if len(sys.argv) > 2 else "default"
+ create_trigger(uid)
+ elif command == "listen":
+ uid = sys.argv[2] if len(sys.argv) > 2 else "default"
+ tid = sys.argv[3] if len(sys.argv) > 3 else None
+ if not tid:
+ print("Error: trigger_id is required. Run 'python main.py trigger <user_id>' first.")
+ sys.exit(1)
+ listen(uid, tid)
+ else:
+ print(f"Unknown command: {command}")
+ print("Use 'connect', 'trigger', or 'listen'.")
+ sys.exit(1)