1
+"""
2
+Custom Tools v2 — local tools + proxy execute with tool router sessions.
3
+
4
+Shows how to create custom tools that run in-process alongside
5
+remote Composio tools. Equivalent of ts/examples/tool-router/src/custom-tools.ts.
6
+
7
+Usage:
8
+ COMPOSIO_API_KEY=... python examples/custom_tools_v2.py
9
+"""
10
+
11
+import base64
12
+import sys
13
+
14
+from pydantic import BaseModel, Field
15
+
16
+from composio import Composio, experimental_create_tool, experimental_create_toolkit
17
+
18
+
19
+# ── Custom tools ────────────────────────────────────────────────
20
+
21
+
22
+class UserLookupInput(BaseModel):
23
+ user_id: str = Field(description="User ID (e.g. user-1)")
24
+
25
+
26
+USERS = {
27
+ "user-1": {"name": "Alice Johnson", "email": "alice@acme.com", "role": "admin"},
28
+ "user-2": {"name": "Bob Smith", "email": "bob@acme.com", "role": "developer"},
29
+}
30
+
31
+
32
+def get_user_fn(input: UserLookupInput, ctx):
33
+ """Look up an internal user by ID."""
34
+ user = USERS.get(input.user_id)
35
+ if not user:
36
+ raise ValueError(f'User "{input.user_id}" not found')
37
+ return user
38
+
39
+
40
+get_user = experimental_create_tool(
41
+ "GET_USER",
42
+ name="Get user",
43
+ description="Look up an internal user by ID",
44
+ input_params=UserLookupInput,
45
+ execute=get_user_fn,
46
+)
47
+
48
+
49
+class DraftInput(BaseModel):
50
+ to: str = Field(description="Recipient email address")
51
+ subject: str = Field(description="Email subject")
52
+ body: str = Field(description="Email body (plain text)")
53
+
54
+
55
+def create_draft_fn(input: DraftInput, ctx):
56
+ """Create a real Gmail draft via the Gmail API."""
57
+ raw_message = (
58
+ f"To: {input.to}\r\n"
59
+ f"Subject: {input.subject}\r\n"
60
+ f"Content-Type: text/plain; charset=UTF-8\r\n"
61
+ f"\r\n"
62
+ f"{input.body}"
63
+ )
64
+ raw = (
65
+ base64.urlsafe_b64encode(raw_message.encode("utf-8"))
66
+ .decode("ascii")
67
+ .rstrip("=")
68
+ )
69
+
70
+ res = ctx.proxy_execute(
71
+ toolkit="gmail",
72
+ endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",
73
+ method="POST",
74
+ body={"message": {"raw": raw}},
75
+ )
76
+
77
+ if res["status"] != 200:
78
+ raise RuntimeError(f"Gmail API error {res['status']}: {res.get('data')}")
79
+ data = res["data"]
80
+ return {
81
+ "draft_id": data["id"],
82
+ "message_id": data["message"]["id"],
83
+ "to": input.to,
84
+ "subject": input.subject,
85
+ }
86
+
87
+
88
+create_draft = experimental_create_tool(
89
+ "CREATE_DRAFT",
90
+ name="Create Gmail draft",
91
+ description="Create a real Gmail draft via the Gmail API. Appears in the user's drafts folder.",
92
+ extends_toolkit="gmail",
93
+ input_params=DraftInput,
94
+ execute=create_draft_fn,
95
+)
96
+
97
+
98
+class SetRoleInput(BaseModel):
99
+ user_id: str = Field(description="User ID")
100
+ role: str = Field(description="New role (admin, developer, viewer)")
101
+
102
+
103
+role_manager = experimental_create_toolkit(
104
+ "ROLE_MANAGER",
105
+ name="Role Manager",
106
+ description="Manage user roles",
107
+ tools=[
108
+ experimental_create_tool(
109
+ "SET_ROLE",
110
+ name="Set role",
111
+ description="Set a user's role",
112
+ input_params=SetRoleInput,
113
+ execute=lambda input, ctx: {
114
+ "user_id": input.user_id,
115
+ "role": input.role,
116
+ "updated": True,
117
+ },
118
+ ),
119
+ ],
120
+)
121
+
122
+
123
+# ── Session ─────────────────────────────────────────────────────
124
+
125
+
126
+def main():
127
+ composio = Composio()
128
+
129
+ print("Creating session with custom tools...")
130
+ session = composio.create(
131
+ user_id="default",
132
+ toolkits=["gmail"],
133
+ experimental={
134
+ "custom_tools": [get_user, create_draft],
135
+ "custom_toolkits": [role_manager],
136
+ },
137
+ )
138
+ print(f"Session ID: {session.session_id}")
139
+
140
+ # List registered custom tools
141
+ print("\n── Registered custom tools ──")
142
+ for tool in session.custom_tools():
143
+ print(f" {tool.slug} ({tool.toolkit or 'standalone'})")
144
+
145
+ print("\n── Registered custom toolkits ──")
146
+ for tk in session.custom_toolkits():
147
+ print(f" {tk.slug}: {[t.slug for t in tk.tools]}")
148
+
149
+ # Test 1: Execute standalone custom tool (local, no network)
150
+ print("\n── Test 1: Execute GET_USER (standalone, local) ──")
151
+ result = session.execute("GET_USER", arguments={"user_id": "user-1"})
152
+ print(f" Result: {result}")
153
+ assert result["data"]["name"] == "Alice Johnson", "GET_USER failed!"
154
+ assert result["error"] is None
155
+ print(" ✓ Passed")
156
+
157
+ # Test 2: Execute by final slug
158
+ print("\n── Test 2: Execute LOCAL_GET_USER (by final slug) ──")
159
+ result = session.execute("LOCAL_GET_USER", arguments={"user_id": "user-2"})
160
+ print(f" Result: {result}")
161
+ assert result["data"]["name"] == "Bob Smith", "LOCAL_GET_USER failed!"
162
+ print(" ✓ Passed")
163
+
164
+ # Test 3: Execute toolkit tool
165
+ print("\n── Test 3: Execute SET_ROLE (toolkit tool) ──")
166
+ result = session.execute(
167
+ "SET_ROLE", arguments={"user_id": "user-1", "role": "viewer"}
168
+ )
169
+ print(f" Result: {result}")
170
+ assert result["data"]["updated"] is True, "SET_ROLE failed!"
171
+ print(" ✓ Passed")
172
+
173
+ # Test 4: Validation error
174
+ print("\n── Test 4: Validation error (missing required field) ──")
175
+ result = session.execute("GET_USER", arguments={})
176
+ print(f" Result: error={result['error'][:80]}...")
177
+ assert result["error"] is not None, "Should have validation error!"
178
+ print(" ✓ Passed")
179
+
180
+ # Test 5: Execute error
181
+ print("\n── Test 5: Execute error (user not found) ──")
182
+ result = session.execute("GET_USER", arguments={"user_id": "nonexistent"})
183
+ print(f" Result: error={result['error']}")
184
+ assert result["error"] is not None, "Should have execution error!"
185
+ print(" ✓ Passed")
186
+
187
+ # Test 6: Pydantic defaults applied
188
+ print("\n── Test 6: Get tools (provider-wrapped) ──")
189
+ tools = session.tools()
190
+ print(f" Got {len(tools)} tools")
191
+ print(" ✓ Passed")
192
+
193
+ # Test 7: Proxy execute (if Gmail is connected)
194
+ if "--with-gmail" in sys.argv:
195
+ print("\n── Test 7: CREATE_DRAFT via proxy_execute ──")
196
+ result = session.execute(
197
+ "CREATE_DRAFT",
198
+ arguments={
199
+ "to": "test@example.com",
200
+ "subject": "Test from Python custom tools",
201
+ "body": "Hello from the Python SDK custom tools e2e test!",
202
+ },
203
+ )
204
+ print(f" Result: {result}")
205
+ if result["error"]:
206
+ print(f" ⚠ Gmail draft failed (may need connection): {result['error']}")
207
+ else:
208
+ print(f" ✓ Draft created: {result['data']}")
209
+
210
+ print("\n══ All tests passed! ══")
211
+
212
+
213
+if __name__ == "__main__":
214
+ main()