@devries-cameron20 / composio-1 / commits / ad627c795
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.

docs: rewrite gmail labeler cookbook with session paradigm and Claude Agent SDK

Replace the old LangChain-based cookbook with the session paradigm (composio.create, session.tools, session.authorize) using the Claude Agent SDK provider and Composio triggers. Follows the same include-region pattern as the slack summariser and FastAPI cookbooks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Sushmitha Mallesh committed Feb 25, 2026 at 18:41 UTC ad627c7955f1bdb447b03e9064265740815d3012
2 files changed +196 -354
docs/content/cookbooks/gmail-labeler.mdx
+72 -354
@@ -1,381 +1,99 @@
1 ---
2 title: Gmail Labeler
3 -description: Build an agent that automatically labels incoming Gmail messages using triggers
3 +description: Build a Python script that listens for new Gmail messages and labels them using Composio and the Claude Agent SDK
4 ---
5
6 -With Composio's managed authentication, tool calling and triggers, it's easy to
7 -build the AI agents that can interact and react the real world events reducing
8 -the boilerplate required to setup and manage the authentication. This cookbook
9 -will walk you through the process of building agents using `Composio`, `LangChain`.
6 +[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/gmail-labeler)
7 +
8 +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.
9
10 ## Prerequisites
11
13 -* Python3.x
12 +* Python 3.10+
13 * [UV](https://docs.astral.sh/uv/getting-started/installation/)
15 -* Composio API key
16 -* OpenAI API key
17 -* Understanding of building AI agents (Preferably with LangChain)
18 -
19 -## Build gmail agent to label your messages
20 -
21 -```python
22 -from composio import Composio
23 -from composio_langchain import LangchainProvider
24 -
25 -from langchain import hub
26 -from langchain.agents import AgentExecutor, create_openai_functions_agent
27 -from langchain_openai import ChatOpenAI
28 -
29 -
30 -def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
31 - """
32 - Create an agent for a given user id.
33 - """
34 - # Step 1: Get all the tools
35 - tools = composio_client.tools.get(
36 - user_id=user_id,
37 - tools=[
38 - "GMAIL_LIST_LABELS",
39 - "GMAIL_ADD_LABEL_TO_EMAIL",
40 - "GMAIL_CREATE_LABEL",
41 - ],
42 - )
43 -
44 - # Step 2: Pull relevant agent prompt.
45 - prompt = hub.pull("hwchase17/openai-functions-agent")
46 -
47 - # Step 3: Initialize chat model.
48 - openai_client = ChatOpenAI(model="gpt-5")
49 -
50 - # Step 4: Define agent
51 - return AgentExecutor(
52 - agent=create_openai_functions_agent(
53 - openai_client,
54 - tools,
55 - prompt,
56 - ),
57 - tools=tools,
58 - verbose=False,
59 - )
60 -```
14 +* [Composio API key](https://platform.composio.dev/settings)
15 +* [Anthropic API key](https://console.anthropic.com/settings/keys)
16
62 -## Authenticating users
63 -
64 -To authenticate your users with Composio you need an auth config for the given
65 -app, In this case you need one for gmail. You can create and manage auth configs
66 -from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=gmail).
67 -Composio platform provides composio managed authentication for some apps to help
68 -you fast-track your development, `gmail` being one of them. You can use these
69 -default auth configs for development, but for production you should always use
70 -your own oauth app configuration.
71 -
72 -Using dashboard is the preferred way of managing authentication configs, but if
73 -you want to do it manually you can follow the guide below
74 -
75 -<details>
76 -
77 -<summary>Click to expand</summary>
78 -
79 -To create an authentication config for `gmail` you need `client_id` and `client_secret`
80 -from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
81 -Once you have the required credentials you can use the following piece of
82 -code to set up authentication for `gmail`.
83 -
84 -```python
85 -from composio import Composio
86 -from composio_langchain import LangchainProvider
87 -
88 -def create_auth_config(composio_client: Composio[OpenAIProvider]):
89 - """
90 - Create a auth config for the gmail toolkit.
91 - """
92 - client_id = os.getenv("GMAIL_CLIENT_ID")
93 - client_secret = os.getenv("GMAIL_CLIENT_SECRET")
94 - if not client_id or not client_secret:
95 - raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
96 -
97 - return composio_client.auth_configs.create(
98 - toolkit="gmail",
99 - options={
100 - "name": "default_gmail_auth_config",
101 - "type": "use_custom_auth",
102 - "auth_scheme": "OAUTH2",
103 - "credentials": {
104 - "client_id": client_id,
105 - "client_secret": client_secret,
106 - },
107 - },
108 - )
109 -```
17 +## Project setup
18
111 -This will create an authentication config for `gmail` which you can use to
112 -authenticate your users for your app. Ideally you should just create one
113 -authentication object per project, so check for an existing auth config
114 -before you create a new one.
115 -
116 -```python
117 -def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
118 - """
119 - Fetch the auth config for a given user id.
120 - """
121 - auth_configs = composio_client.auth_configs.list()
122 - for auth_config in auth_configs.items:
123 - if auth_config.toolkit == "gmail":
124 - return auth_config
125 -
126 - return None
127 -```
128 -</details>
129 -
130 -Once you have authentication management in place, we can start with connecting
131 -your users to your `gmail` app. Let's implement a function to connect the users
132 -to your `gmail` app via composio.
133 -
134 -```python
135 -# Function to initiate a connected account
136 -def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
137 - """
138 - Create a connection for a given user id and auth config id.
139 - """
140 - # Fetch or create the auth config for the gmail toolkit
141 - auth_config = fetch_auth_config(composio_client=composio_client)
142 - if not auth_config:
143 - auth_config = create_auth_config(composio_client=composio_client)
144 -
145 - # Create a connection for the user
146 - return composio_client.connected_accounts.initiate(
147 - user_id=user_id,
148 - auth_config_id=auth_config.id,
149 - )
150 -```
19 +Create a new project and install dependencies:
20
152 -Now, when creating tools for your agent always check if the user already has a
153 -connected account before creating a new one.
154 -
155 -```python
156 -def check_connected_account_exists(
157 - composio_client: Composio[LangchainProvider],
158 - user_id: str,
159 -):
160 - """
161 - Check if a connected account exists for a given user id.
162 - """
163 - # Fetch all connected accounts for the user
164 - connected_accounts = composio_client.connected_accounts.list(
165 - user_ids=[user_id],
166 - toolkit_slugs=["GMAIL"],
167 - )
168 -
169 - # Check if there's an active connected account
170 - for account in connected_accounts.items:
171 - if account.status == "ACTIVE":
172 - return True
173 -
174 - # Ideally you should not have inactive accounts, but if you do, you should delete them
175 - print(f"[warning] inactive account {account.id} found for user id: {user_id}")
176 - return False
21 +```bash
22 +mkdir composio-gmail-labeler && cd composio-gmail-labeler
23 +uv init && uv add composio composio-claude-agent-sdk claude-agent-sdk
24 ```
25
26 +Add your API keys to a `.env` file:
27
180 -## Creating Triggers
181 -
182 -You can use triggers to make your agents react to real world events. In this example,
183 -we will use triggers to invoke your agent everytime there's a new message in your
184 -gmail inbox.
185 -
186 -```python
187 -# Create a new trigger
188 -def create_trigger(
189 - composio_client: Composio[LangchainProvider],
190 - connected_account_id: str,
191 -) -> str:
192 - """
193 - Create a trigger.
194 - """
195 - response = composio_client.triggers.create(
196 - slug="GMAIL_NEW_GMAIL_MESSAGE",
197 - connected_account_id=connected_account_id,
198 - trigger_config={},
199 - )
200 - return response.trigger_id
28 +```bash title=".env"
29 +COMPOSIO_API_KEY=your_composio_api_key
30 +ANTHROPIC_API_KEY=your_anthropic_api_key
31 ```
32
203 -When creating triggers, make sure there are no duplicate triggers. Use following
204 -code as reference for checking if trigger for given connected account exists or not.
205 -
206 -```python
207 -def check_trigger_exists(
208 - composio_client: Composio[LangchainProvider],
209 - connected_account_id: str,
210 -) -> t.Optional[str]:
211 - """
212 - Check if a trigger exists.
213 - """
214 - triggers = composio_client.triggers.list_active(
215 - trigger_names=["GMAIL_NEW_GMAIL_MESSAGE"],
216 - connected_account_ids=[connected_account_id],
217 - )
218 - for trigger in triggers.items:
219 - return trigger.id
220 - return None
221 -```
33 +## Setting up the client
34 +
35 +`Composio` takes a `ClaudeAgentSDKProvider` so that tools come back in the format the Claude Agent SDK expects.
36 +
37 +<include>../../examples/gmail-labeler/main.py#setup</include>
38 +
39 +## Connecting to Gmail
40 +
41 +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.
42 +
43 +<include>../../examples/gmail-labeler/main.py#connect</include>
44 +
45 +## Creating a trigger
46 +
47 +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.
48
49 +<include>../../examples/gmail-labeler/main.py#trigger</include>
50
224 -Once trigger is created, you can listen to events using a trigger subscription.
51 +<Callout>
52 +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.
53 +</Callout>
54
226 -```python
227 -# Create subscription object
228 -trigger_subscription = composio_client.triggers.subscribe()
55 +## Labeling with Claude
56
230 -# Register event handler
231 -@trigger_subscription.handle(
232 - trigger_id="<TRIGGER_ID>", # Filter out events that does not belong this trigger id
233 - trigger_slug="GMAIL_NEW_GMAIL_MESSAGE",
234 -)
235 -def handle_event(event: TriggerEvent):
236 - print("> Received email with subject: ", event["payload"]["subject"])
57 +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.
58
238 -# Wait for events
239 -trigger_subscription.wait_forever()
59 +<include>../../examples/gmail-labeler/main.py#label</include>
60 +
61 +## Listening for emails
62 +
63 +`composio.triggers.subscribe()` opens a WebSocket connection. When a new email arrives, the handler calls `label_email` to classify and label it.
64 +
65 +<include>../../examples/gmail-labeler/main.py#listen</include>
66 +
67 +<Callout>
68 +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.
69 +</Callout>
70 +
71 +## Complete script
72 +
73 +Here is everything together:
74 +
75 +<include>../../examples/gmail-labeler/main.py</include>
76 +
77 +## Running the script
78 +
79 +First, connect your Gmail account:
80 +
81 +```bash
82 +uv run --env-file .env python main.py connect default
83 ```
84
242 -## Putting everything together
243 -
244 -Let's put together everything by making the agent react to new messages in your
245 -inbox.
246 -
247 -```python
248 -# Create a trigger subscription factory
249 -
250 -def create_trigger_subscription(
251 - composio_client: Composio[LangchainProvider],
252 - trigger_slug: str,
253 - trigger_id: str,
254 - agent: AgentExecutor,
255 -):
256 - """
257 - Create a trigger subscription for the given agent.
258 - """
259 - trigger_subscription = composio_client.triggers.subscribe()
260 -
261 - @trigger_subscription.handle(
262 - trigger_slug=trigger_slug,
263 - trigger_id=trigger_id,
264 - )
265 - def handle_event(event: TriggerEvent):
266 - print("> Received email with subject: ", event["payload"]["subject"])
267 - result = agent.invoke(
268 - input={
269 - "input": APPLY_NEW_LABEL.format( # Check `gmail_labeler/prompt.py`
270 - message_id=event["payload"]["id"],
271 - message_subject=event["payload"]["subject"],
272 - message_text=event["payload"]["message_text"],
273 - )
274 - }
275 - )
276 - print("> Result: ", result["output"])
277 -
278 - return trigger_subscription
85 +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."
86 +
87 +Next, create a trigger:
88 +
89 +```bash
90 +uv run --env-file .env python main.py trigger default
91 ```
92
281 -Package everything as a single entry point.
282 -
283 -```python
284 -def run_agent(user_id: str):
285 - # Create composio client
286 - composio_client = Composio(provider=LangchainProvider())
287 -
288 - # Validate conected account
289 - connected_account_id = check_connected_account_exists(composio_client, user_id)
290 - if connected_account_id is None:
291 - connection_request = create_connection(composio_client, user_id)
292 - print(
293 - f"Authenticate with the following link: {connection_request.redirect_url}"
294 - )
295 - connection_request.wait_for_connection()
296 - connected_account_id = connection_request.id
297 -
298 - # Check if trigger exists, create if not
299 - trigger_id = check_trigger_exists(
300 - composio_client=composio_client,
301 - connected_account_id=connected_account_id,
302 - )
303 - if trigger_id is None:
304 - trigger_id = create_trigger(
305 - composio_client=composio_client,
306 - connected_account_id=connected_account_id,
307 - )
308 -
309 - # Create agent
310 - agent = create_agent(user_id=user_id, composio_client=composio_client)
311 -
312 - # Create trigger subscription
313 - trigger_subscription = create_trigger_subscription(
314 - composio_client=composio_client,
315 - trigger_slug=GMAIL_NEW_GMAIL_MESSAGE_TRIGGER,
316 - trigger_id=trigger_id,
317 - agent=agent,
318 - )
319 -
320 - # Wait forever
321 - print("Waiting for events...")
322 - trigger_subscription.wait_forever()
93 +Then start the listener with the trigger ID from the previous step:
94 +
95 +```bash
96 +uv run --env-file .env python main.py listen default <trigger_id>
97 ```
98
325 -To test the above function as CLI, follow the steps below
326 -
327 -1. Clone the repository
328 - ```bash
329 - git clone git@github.com:composiohq/gmail-labeler
330 - cd gmail-labeler/
331 - ```
332 -2. Setup environment
333 - ```bash
334 - cp .env.example .env
335 - ```
336 -
337 - Fill the api keys
338 - ```dotenv
339 - COMPOSIO_API_KEY=
340 - OPENAI_API_KEY=
341 - ```
342 -
343 - Create the virtual env
344 - ```bash
345 - make env
346 - source .venv/bin/activate
347 - ```
348 -3. Run the agent
349 - ```bash
350 - python gmail_labeler --user-id "default"
351 - ```
352 -
353 -## Using Composio for managed auth and tools
354 -
355 -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
356 -- manage `gmail` oauth app
357 -- manage user connections
358 -- tools for your agents to interact with `gmail`
359 -- Infra for listening to changes in your gmail inbox
360 -
361 -Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
362 -
363 -## Best practices
364 -
365 -**🔒 User Management**:
366 -
367 -- Use unique, consistent `user_id` values for each person
368 -- Each user maintains their own gmail connection
369 -- User IDs can be email addresses, usernames, or any unique identifier
370 -
371 -## Troubleshooting
372 -
373 -**Connection Issues**:
374 -- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
375 -- Check that the user has completed `gmail` authorization
376 -- Verify the user_id matches exactly between requests
377 -
378 -**API Errors**:
379 -- Check the server logs for detailed error messages
380 -- Ensure request payloads match the expected format
381 -- Visit `/docs` endpoint for API schema validation
99 +Send yourself an email and watch the terminal — the agent will receive the event, inspect the email, and apply an appropriate label.
docs/examples/gmail-labeler/main.py new
+124
@@ -0,0 +1,124 @@
1 +import sys
2 +
3 +# region setup
4 +import asyncio
5 +
6 +from composio import Composio
7 +from composio_claude_agent_sdk import ClaudeAgentSDKProvider
8 +from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, create_sdk_mcp_server
9 +
10 +composio = Composio(provider=ClaudeAgentSDKProvider())
11 +# endregion setup
12 +
13 +
14 +# region connect
15 +def connect(user_id: str):
16 + """Check if Gmail is connected. If not, start OAuth and wait."""
17 + session = composio.create(user_id=user_id, toolkits=["gmail"])
18 + toolkits = session.toolkits()
19 +
20 + for t in toolkits.items:
21 + if t.slug == "gmail" and t.connection and t.connection.is_active:
22 + print("Gmail is already connected.")
23 + return
24 +
25 + connection_request = session.authorize("gmail")
26 + print(f"Open this URL to connect Gmail:\n{connection_request.redirect_url}")
27 + connection_request.wait_for_connection()
28 + print("Connected.")
29 +# endregion connect
30 +
31 +
32 +# region trigger
33 +def create_trigger(user_id: str):
34 + """Create a trigger for new Gmail messages."""
35 + trigger = composio.triggers.create(
36 + slug="GMAIL_NEW_GMAIL_MESSAGE",
37 + user_id=user_id,
38 + trigger_config={},
39 + )
40 + print(f"Trigger created: {trigger.trigger_id}")
41 + return trigger.trigger_id
42 +# endregion trigger
43 +
44 +
45 +# region label
46 +async def label_email(session, message_id: str, subject: str, body: str):
47 + """Use Claude to label an incoming email."""
48 + tools = session.tools()
49 + tool_server = create_sdk_mcp_server(name="composio", version="1.0.0", tools=tools)
50 +
51 + prompt = f"""You received a new email. Analyze it and apply an appropriate label.
52 +
53 +Message ID: {message_id}
54 +Subject: {subject}
55 +Body: {body}
56 +
57 +Steps:
58 +1. List the existing Gmail labels.
59 +2. Decide which label fits best, or create a new label if none fit.
60 +3. Apply the label to this email using its message ID."""
61 +
62 + options = ClaudeAgentOptions(
63 + system_prompt="You are an email organizer. Label incoming emails with the most appropriate Gmail label.",
64 + permission_mode="bypassPermissions",
65 + mcp_servers={"composio": tool_server},
66 + )
67 +
68 + async with ClaudeSDKClient(options=options) as client:
69 + await client.query(prompt)
70 + async for msg in client.receive_response():
71 + print(msg)
72 +# endregion label
73 +
74 +
75 +# region listen
76 +def listen(user_id: str, trigger_id: str):
77 + """Subscribe to trigger events and label incoming emails."""
78 + session = composio.create(user_id=user_id, toolkits=["gmail"])
79 + subscription = composio.triggers.subscribe()
80 +
81 + @subscription.handle(trigger_id=trigger_id)
82 + def handle_event(data):
83 + print(f"New email: {data.get('subject', 'No subject')}")
84 + asyncio.run(
85 + label_email(
86 + session,
87 + message_id=data.get("id", ""),
88 + subject=data.get("subject", ""),
89 + body=data.get("message_text", ""),
90 + )
91 + )
92 +
93 + print("Listening for new emails...")
94 + subscription.wait_forever()
95 +# endregion listen
96 +
97 +
98 +if __name__ == "__main__":
99 + if len(sys.argv) < 2:
100 + print("Usage:")
101 + print(" python main.py connect <user_id>")
102 + print(" python main.py trigger <user_id>")
103 + print(" python main.py listen <user_id> <trigger_id>")
104 + sys.exit(1)
105 +
106 + command = sys.argv[1]
107 +
108 + if command == "connect":
109 + uid = sys.argv[2] if len(sys.argv) > 2 else "default"
110 + connect(uid)
111 + elif command == "trigger":
112 + uid = sys.argv[2] if len(sys.argv) > 2 else "default"
113 + create_trigger(uid)
114 + elif command == "listen":
115 + uid = sys.argv[2] if len(sys.argv) > 2 else "default"
116 + tid = sys.argv[3] if len(sys.argv) > 3 else None
117 + if not tid:
118 + print("Error: trigger_id is required. Run 'python main.py trigger <user_id>' first.")
119 + sys.exit(1)
120 + listen(uid, tid)
121 + else:
122 + print(f"Unknown command: {command}")
123 + print("Use 'connect', 'trigger', or 'listen'.")
124 + sys.exit(1)