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: fix gmail labeler code quality issues
- Replace asyncio.run() with shared event loop (run_until_complete) - Merge trigger+listen into single listen command (2 commands total) - Add error handling in event handler to prevent listener crashes - Remove separate trigger command, matching slack summariser pattern Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sushmitha Mallesh committed
Feb 25, 2026 at 18:49 UTC
9f8df7a42ae989da9b78498cc94c8ae36e59c852
2 files changed
+28
-53
docs/content/cookbooks/gmail-labeler.mdx
+3
-19
@@ -42,16 +42,6 @@ Before labeling, we need to make sure the user has connected their Gmail account
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
-
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
-
45
## Labeling with Claude
46
47
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.
@@ -60,7 +50,7 @@ For each incoming email, `label_email` gets Gmail tools from `session.tools()`,
50
51
## Listening for emails
52
63
-`composio.triggers.subscribe()` opens a WebSocket connection. When a new email arrives, the handler calls `label_email` to classify and label it.
53
+The `listen` function creates a trigger for new Gmail messages and subscribes to events via WebSocket. When a new email arrives, the handler calls `label_email` to classify and label it.
54
55
<include>../../examples/gmail-labeler/main.py#listen</include>
56
@@ -84,16 +74,10 @@ uv run --env-file .env python main.py connect default
74
75
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."
76
87
-Next, create a trigger:
88
-
89
-```bash
90
-uv run --env-file .env python main.py trigger default
91
-```
92
-
93
-Then start the listener with the trigger ID from the previous step:
77
+Then start the listener:
78
79
```bash
96
-uv run --env-file .env python main.py listen default <trigger_id>
80
+uv run --env-file .env python main.py listen default
81
```
82
83
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
+25
-34
@@ -29,19 +29,6 @@ def connect(user_id: str):
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
-
32
# region label
33
async def label_email(session, message_id: str, subject: str, body: str):
34
"""Use Claude to label an incoming email."""
@@ -73,22 +60,34 @@ Steps:
60
61
62
# region listen
76
-def listen(user_id: str, trigger_id: str):
77
- """Subscribe to trigger events and label incoming emails."""
63
+def listen(user_id: str):
64
+ """Create a trigger, subscribe to events, and label incoming emails."""
65
session = composio.create(user_id=user_id, toolkits=["gmail"])
66
+
67
+ trigger = composio.triggers.create(
68
+ slug="GMAIL_NEW_GMAIL_MESSAGE",
69
+ user_id=user_id,
70
+ trigger_config={},
71
+ )
72
+ print(f"Trigger created: {trigger.trigger_id}")
73
+
74
+ loop = asyncio.new_event_loop()
75
subscription = composio.triggers.subscribe()
76
81
- @subscription.handle(trigger_id=trigger_id)
77
+ @subscription.handle(trigger_id=trigger.trigger_id)
78
def handle_event(data):
79
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", ""),
80
+ try:
81
+ loop.run_until_complete(
82
+ label_email(
83
+ session,
84
+ message_id=data.get("id", ""),
85
+ subject=data.get("subject", ""),
86
+ body=data.get("message_text", ""),
87
+ )
88
)
91
- )
89
+ except Exception as e:
90
+ print(f"Error labeling email: {e}")
91
92
print("Listening for new emails...")
93
subscription.wait_forever()
@@ -99,8 +98,7 @@ if __name__ == "__main__":
98
if len(sys.argv) < 2:
99
print("Usage:")
100
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>")
101
+ print(" python main.py listen <user_id>")
102
sys.exit(1)
103
104
command = sys.argv[1]
@@ -108,17 +106,10 @@ if __name__ == "__main__":
106
if command == "connect":
107
uid = sys.argv[2] if len(sys.argv) > 2 else "default"
108
connect(uid)
111
- elif command == "trigger":
112
- uid = sys.argv[2] if len(sys.argv) > 2 else "default"
113
- create_trigger(uid)
109
elif command == "listen":
110
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)
111
+ listen(uid)
112
else:
113
print(f"Unknown command: {command}")
123
- print("Use 'connect', 'trigger', or 'listen'.")
114
+ print("Use 'connect' or 'listen'.")
115
sys.exit(1)