1
+"""Tests for custom tools in tool router sessions.
2
+
3
+Covers:
4
+- Factory function validation (slug rules, required fields, Pydantic model check)
5
+- Slug prefixing and collision detection
6
+- Serialization to API format
7
+- Custom tool execution (validation, defaults, errors)
8
+- Routing map building and lookup
9
+- SessionContextImpl sibling routing
10
+- ToolRouterSession integration (execute routing, custom_tools(), custom_toolkits())
11
+- Multi-execute routing (all-local, all-remote, mixed, parallel)
12
+"""
13
+
14
+from unittest.mock import MagicMock, patch
15
+
16
+import pytest
17
+from pydantic import BaseModel, Field
18
+
19
+from composio import experimental_create_tool, experimental_create_toolkit
20
+from composio.core.models.custom_tool import (
21
+ build_custom_tools_map,
22
+ build_custom_tools_map_from_response,
23
+ serialize_custom_tools,
24
+ serialize_custom_toolkits,
25
+)
26
+from composio.core.models.custom_tool_execution import (
27
+ execute_custom_tool,
28
+ find_custom_tool,
29
+)
30
+from composio.core.models.custom_tool_types import (
31
+ CustomToolsMap,
32
+ CustomToolsMapEntry,
33
+ RegisteredCustomTool,
34
+ RegisteredCustomToolkit,
35
+)
36
+from composio.core.models.session_context import SessionContextImpl
37
+from composio.core.models.tool_router_session import ToolRouterSession
38
+from composio.exceptions import ValidationError
39
+
40
+
41
+# ────────────────────────────────────────────────────────────────
42
+# Fixtures
43
+# ────────────────────────────────────────────────────────────────
44
+
45
+
46
+class GrepInput(BaseModel):
47
+ pattern: str = Field(description="Pattern to search for")
48
+ path: str = Field(default=".", description="File path")
49
+
50
+
51
+class EmailInput(BaseModel):
52
+ to: str = Field(description="Recipient email")
53
+ subject: str = Field(description="Subject")
54
+
55
+
56
+class SetRoleInput(BaseModel):
57
+ user_id: str = Field(description="User ID")
58
+ role: str = Field(default="viewer", description="New role")
59
+
60
+
61
+@pytest.fixture
62
+def grep_tool():
63
+ return experimental_create_tool(
64
+ "GREP",
65
+ name="Grep Search",
66
+ description="Search for patterns in files",
67
+ input_params=GrepInput,
68
+ execute=lambda input, ctx: {"matches": [input.pattern], "path": input.path},
69
+ )
70
+
71
+
72
+@pytest.fixture
73
+def email_tool():
74
+ return experimental_create_tool(
75
+ "GET_EMAILS",
76
+ name="Get Emails",
77
+ description="Get emails from Gmail",
78
+ input_params=EmailInput,
79
+ execute=lambda input, ctx: {"emails": []},
80
+ extends_toolkit="gmail",
81
+ )
82
+
83
+
84
+@pytest.fixture
85
+def set_role_tool():
86
+ return experimental_create_tool(
87
+ "SET_ROLE",
88
+ name="Set role",
89
+ description="Set a user's role",
90
+ input_params=SetRoleInput,
91
+ execute=lambda input, ctx: {
92
+ "user_id": input.user_id,
93
+ "role": input.role,
94
+ "updated": True,
95
+ },
96
+ )
97
+
98
+
99
+@pytest.fixture
100
+def role_toolkit(set_role_tool):
101
+ return experimental_create_toolkit(
102
+ "ROLE_MANAGER",
103
+ name="Role Manager",
104
+ description="Manage user roles",
105
+ tools=[set_role_tool],
106
+ )
107
+
108
+
109
+class MockSessionContext:
110
+ user_id = "test-user"
111
+
112
+ def execute(self, tool_slug, arguments):
113
+ return {"data": {}, "error": None, "successful": True}
114
+
115
+ def proxy_execute(self, **kwargs):
116
+ return {"status": 200, "data": {}, "headers": {}}
117
+
118
+
119
+# ────────────────────────────────────────────────────────────────
120
+# Factory validation tests
121
+# ────────────────────────────────────────────────────────────────
122
+
123
+
124
+class TestCreateCustomTool:
125
+ def test_creates_tool_with_valid_params(self, grep_tool):
126
+ assert grep_tool.slug == "GREP"
127
+ assert grep_tool.name == "Grep Search"
128
+ assert grep_tool.description == "Search for patterns in files"
129
+ assert grep_tool.extends_toolkit is None
130
+ assert grep_tool.input_schema["type"] == "object"
131
+ assert "pattern" in grep_tool.input_schema["properties"]
132
+ assert grep_tool.output_schema is None
133
+
134
+ def test_creates_extension_tool(self, email_tool):
135
+ assert email_tool.slug == "GET_EMAILS"
136
+ assert email_tool.extends_toolkit == "gmail"
137
+
138
+ def test_slug_empty(self):
139
+ with pytest.raises(ValidationError, match="slug is required"):
140
+ experimental_create_tool(
141
+ "",
142
+ name="Bad",
143
+ description="Bad",
144
+ input_params=GrepInput,
145
+ execute=lambda i, c: {},
146
+ )
147
+
148
+ def test_slug_invalid_chars(self):
149
+ with pytest.raises(ValidationError, match="alphanumeric"):
150
+ experimental_create_tool(
151
+ "BAD SLUG!",
152
+ name="Bad",
153
+ description="Bad",
154
+ input_params=GrepInput,
155
+ execute=lambda i, c: {},
156
+ )
157
+
158
+ def test_slug_local_prefix(self):
159
+ with pytest.raises(ValidationError, match="LOCAL_"):
160
+ experimental_create_tool(
161
+ "LOCAL_BAD",
162
+ name="Bad",
163
+ description="Bad",
164
+ input_params=GrepInput,
165
+ execute=lambda i, c: {},
166
+ )
167
+
168
+ def test_slug_composio_prefix(self):
169
+ with pytest.raises(ValidationError, match="COMPOSIO_"):
170
+ experimental_create_tool(
171
+ "COMPOSIO_BAD",
172
+ name="Bad",
173
+ description="Bad",
174
+ input_params=GrepInput,
175
+ execute=lambda i, c: {},
176
+ )
177
+
178
+ def test_name_required(self):
179
+ with pytest.raises(ValidationError, match="name is required"):
180
+ experimental_create_tool(
181
+ "GOOD",
182
+ name="",
183
+ description="Desc",
184
+ input_params=GrepInput,
185
+ execute=lambda i, c: {},
186
+ )
187
+
188
+ def test_description_required(self):
189
+ with pytest.raises(ValidationError, match="description is required"):
190
+ experimental_create_tool(
191
+ "GOOD",
192
+ name="Name",
193
+ description="",
194
+ input_params=GrepInput,
195
+ execute=lambda i, c: {},
196
+ )
197
+
198
+ def test_input_params_must_be_basemodel_subclass(self):
199
+ with pytest.raises(ValidationError, match="BaseModel subclass"):
200
+ experimental_create_tool(
201
+ "GOOD",
202
+ name="Name",
203
+ description="Desc",
204
+ input_params=dict, # type: ignore
205
+ execute=lambda i, c: {},
206
+ )
207
+
208
+ def test_input_params_must_not_be_instance(self):
209
+ with pytest.raises(ValidationError, match="BaseModel subclass"):
210
+ experimental_create_tool(
211
+ "GOOD",
212
+ name="Name",
213
+ description="Desc",
214
+ input_params=GrepInput(pattern="x"), # type: ignore
215
+ execute=lambda i, c: {},
216
+ )
217
+
218
+ def test_execute_must_be_callable(self):
219
+ with pytest.raises(ValidationError, match="callable"):
220
+ experimental_create_tool(
221
+ "GOOD",
222
+ name="Name",
223
+ description="Desc",
224
+ input_params=GrepInput,
225
+ execute="not a function", # type: ignore
226
+ )
227
+
228
+ def test_slug_length_validation_standalone(self):
229
+ # LOCAL_ + 55 chars = 61 > 60
230
+ with pytest.raises(ValidationError, match="too long"):
231
+ experimental_create_tool(
232
+ "A" * 55,
233
+ name="Name",
234
+ description="Desc",
235
+ input_params=GrepInput,
236
+ execute=lambda i, c: {},
237
+ )
238
+
239
+ def test_slug_length_validation_extension(self):
240
+ # LOCAL_ + GMAIL_ + slug must be <= 60
241
+ with pytest.raises(ValidationError, match="too long"):
242
+ experimental_create_tool(
243
+ "A" * 50,
244
+ name="Name",
245
+ description="Desc",
246
+ input_params=GrepInput,
247
+ execute=lambda i, c: {},
248
+ extends_toolkit="gmail",
249
+ )
250
+
251
+ def test_output_params(self):
252
+ class OutputSchema(BaseModel):
253
+ matches: int
254
+
255
+ tool = experimental_create_tool(
256
+ "TOOL",
257
+ name="Tool",
258
+ description="Desc",
259
+ input_params=GrepInput,
260
+ execute=lambda i, c: {},
261
+ output_params=OutputSchema,
262
+ )
263
+ assert tool.output_schema is not None
264
+ assert "properties" in tool.output_schema
265
+
266
+ def test_input_schema_includes_defaults(self, grep_tool):
267
+ # path has default="." - Pydantic won't include it in required
268
+ assert "pattern" in grep_tool.input_schema.get("required", [])
269
+ assert "path" not in grep_tool.input_schema.get("required", [])
270
+
271
+ def test_frozen_dataclass(self, grep_tool):
272
+ with pytest.raises(AttributeError):
273
+ grep_tool.slug = "NEW" # type: ignore
274
+
275
+
276
+class TestCreateCustomToolkit:
277
+ def test_creates_toolkit(self, role_toolkit, set_role_tool):
278
+ assert role_toolkit.slug == "ROLE_MANAGER"
279
+ assert role_toolkit.name == "Role Manager"
280
+ assert len(role_toolkit.tools) == 1
281
+ assert role_toolkit.tools[0].slug == "SET_ROLE"
282
+
283
+ def test_rejects_empty_tools(self):
284
+ with pytest.raises(ValidationError, match="at least one tool"):
285
+ experimental_create_toolkit(
286
+ "TK",
287
+ name="TK",
288
+ description="Desc",
289
+ tools=[],
290
+ )
291
+
292
+ def test_rejects_extends_toolkit_in_tools(self, email_tool):
293
+ with pytest.raises(ValidationError, match="extends_toolkit"):
294
+ experimental_create_toolkit(
295
+ "TK",
296
+ name="TK",
297
+ description="Desc",
298
+ tools=[email_tool],
299
+ )
300
+
301
+ def test_slug_length_validation(self):
302
+ tool = experimental_create_tool(
303
+ "A" * 45,
304
+ name="Name",
305
+ description="Desc",
306
+ input_params=GrepInput,
307
+ execute=lambda i, c: {},
308
+ )
309
+ # LOCAL_ + LONG_TOOLKIT_ + AAAA... would exceed 60
310
+ with pytest.raises(ValidationError, match="too long"):
311
+ experimental_create_toolkit(
312
+ "LONG_TOOLKIT",
313
+ name="TK",
314
+ description="Desc",
315
+ tools=[tool],
316
+ )
317
+
318
+ def test_slug_validation(self):
319
+ with pytest.raises(ValidationError, match="LOCAL_"):
320
+ experimental_create_toolkit(
321
+ "LOCAL_BAD",
322
+ name="TK",
323
+ description="Desc",
324
+ tools=[
325
+ experimental_create_tool(
326
+ "T",
327
+ name="T",
328
+ description="D",
329
+ input_params=GrepInput,
330
+ execute=lambda i, c: {},
331
+ )
332
+ ],
333
+ )
334
+
335
+
336
+# ────────────────────────────────────────────────────────────────
337
+# Serialization tests
338
+# ────────────────────────────────────────────────────────────────
339
+
340
+
341
+class TestSerialization:
342
+ def test_serialize_standalone_tool(self, grep_tool):
343
+ result = serialize_custom_tools([grep_tool])
344
+ assert len(result) == 1
345
+ assert result[0]["slug"] == "GREP"
346
+ assert result[0]["name"] == "Grep Search"
347
+ assert result[0]["input_schema"]["type"] == "object"
348
+ assert "extends_toolkit" not in result[0]
349
+
350
+ def test_serialize_extension_tool(self, email_tool):
351
+ result = serialize_custom_tools([email_tool])
352
+ assert result[0]["extends_toolkit"] == "gmail"
353
+
354
+ def test_serialize_toolkit(self, role_toolkit):
355
+ result = serialize_custom_toolkits([role_toolkit])
356
+ assert len(result) == 1
357
+ assert result[0]["slug"] == "ROLE_MANAGER"
358
+ assert len(result[0]["tools"]) == 1
359
+ assert result[0]["tools"][0]["slug"] == "SET_ROLE"
360
+
361
+
362
+# ────────────────────────────────────────────────────────────────
363
+# Routing map tests
364
+# ────────────────────────────────────────────────────────────────
365
+
366
+
367
+class TestCustomToolsMap:
368
+ def test_build_map_standalone(self, grep_tool):
369
+ m = build_custom_tools_map([grep_tool])
370
+ assert "LOCAL_GREP" in m.by_final_slug
371
+ assert "GREP" in m.by_original_slug
372
+
373
+ def test_build_map_extension(self, email_tool):
374
+ m = build_custom_tools_map([email_tool])
375
+ assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug
376
+ assert "GET_EMAILS" in m.by_original_slug
377
+
378
+ def test_build_map_toolkit(self, set_role_tool, role_toolkit):
379
+ m = build_custom_tools_map([], [role_toolkit])
380
+ assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug
381
+ assert "SET_ROLE" in m.by_original_slug
382
+
383
+ def test_build_map_mixed(self, grep_tool, email_tool, role_toolkit):
384
+ m = build_custom_tools_map([grep_tool, email_tool], [role_toolkit])
385
+ assert len(m.by_final_slug) == 3
386
+ assert len(m.by_original_slug) == 3
387
+
388
+ def test_collision_detection_final_slug(self, grep_tool):
389
+ with pytest.raises(ValidationError, match="collision"):
390
+ build_custom_tools_map([grep_tool, grep_tool])
391
+
392
+ def test_collision_detection_original_slug(self):
393
+ tool1 = experimental_create_tool(
394
+ "FOO",
395
+ name="Foo",
396
+ description="Desc",
397
+ input_params=GrepInput,
398
+ execute=lambda i, c: {},
399
+ )
400
+ # Same slug in a toolkit produces different final slug but same original
401
+ # This would collide on original slug
402
+ toolkit = experimental_create_toolkit(
403
+ "TK",
404
+ name="TK",
405
+ description="D",
406
+ tools=[
407
+ experimental_create_tool(
408
+ "FOO",
409
+ name="Foo2",
410
+ description="Desc2",
411
+ input_params=GrepInput,
412
+ execute=lambda i, c: {},
413
+ )
414
+ ],
415
+ )
416
+ with pytest.raises(ValidationError, match="collision"):
417
+ build_custom_tools_map([tool1], [toolkit])
418
+
419
+
420
+class TestFindCustomTool:
421
+ def test_find_by_final_slug(self, grep_tool):
422
+ m = build_custom_tools_map([grep_tool])
423
+ entry = find_custom_tool(m, "LOCAL_GREP")
424
+ assert entry is not None
425
+ assert entry.final_slug == "LOCAL_GREP"
426
+
427
+ def test_find_by_original_slug(self, grep_tool):
428
+ m = build_custom_tools_map([grep_tool])
429
+ entry = find_custom_tool(m, "GREP")
430
+ assert entry is not None
431
+ assert entry.final_slug == "LOCAL_GREP"
432
+
433
+ def test_find_case_insensitive(self, grep_tool):
434
+ m = build_custom_tools_map([grep_tool])
435
+ entry = find_custom_tool(m, "grep")
436
+ assert entry is not None
437
+ assert entry.final_slug == "LOCAL_GREP"
438
+
439
+ def test_find_nonexistent(self, grep_tool):
440
+ m = build_custom_tools_map([grep_tool])
441
+ assert find_custom_tool(m, "NONEXISTENT") is None
442
+
443
+ def test_find_none_map(self):
444
+ assert find_custom_tool(None, "GREP") is None
445
+
446
+
447
+class TestBuildMapFromResponse:
448
+ def test_builds_from_response(self, grep_tool, email_tool, role_toolkit):
449
+ # Mock response experimental
450
+ mock_exp = MagicMock()
451
+
452
+ mock_ct1 = MagicMock()
453
+ mock_ct1.slug = "LOCAL_GREP"
454
+ mock_ct1.original_slug = "GREP"
455
+ mock_ct1.extends_toolkit = None
456
+
457
+ mock_ct2 = MagicMock()
458
+ mock_ct2.slug = "LOCAL_GMAIL_GET_EMAILS"
459
+ mock_ct2.original_slug = "GET_EMAILS"
460
+ mock_ct2.extends_toolkit = "gmail"
461
+
462
+ mock_exp.custom_tools = [mock_ct1, mock_ct2]
463
+
464
+ mock_ctk = MagicMock()
465
+ mock_ctk.slug = "ROLE_MANAGER"
466
+ mock_ctk_tool = MagicMock()
467
+ mock_ctk_tool.slug = "LOCAL_ROLE_MANAGER_SET_ROLE"
468
+ mock_ctk_tool.original_slug = "SET_ROLE"
469
+ mock_ctk.tools = [mock_ctk_tool]
470
+ mock_exp.custom_toolkits = [mock_ctk]
471
+
472
+ set_role = role_toolkit.tools[0]
473
+ m = build_custom_tools_map_from_response(
474
+ [grep_tool, email_tool],
475
+ [role_toolkit],
476
+ mock_exp,
477
+ )
478
+
479
+ assert "LOCAL_GREP" in m.by_final_slug
480
+ assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug
481
+ assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug
482
+ assert m.by_final_slug["LOCAL_GMAIL_GET_EMAILS"].toolkit == "gmail"
483
+
484
+
485
+# ────────────────────────────────────────────────────────────────
486
+# Custom tool execution tests
487
+# ────────────────────────────────────────────────────────────────
488
+
489
+
490
+class TestExecuteCustomTool:
491
+ def test_successful_execution(self, grep_tool):
492
+ m = build_custom_tools_map([grep_tool])
493
+ entry = find_custom_tool(m, "GREP")
494
+ result = execute_custom_tool(entry, {"pattern": "hello"}, MockSessionContext()) # type: ignore
495
+ assert result["successful"] is True
496
+ assert result["data"]["matches"] == ["hello"]
497
+ assert result["data"]["path"] == "." # default value
498
+ assert result["error"] is None
499
+
500
+ def test_applies_pydantic_defaults(self, grep_tool):
501
+ m = build_custom_tools_map([grep_tool])
502
+ entry = find_custom_tool(m, "GREP")
503
+ result = execute_custom_tool(entry, {"pattern": "test"}, MockSessionContext()) # type: ignore
504
+ assert result["data"]["path"] == "." # default applied
505
+
506
+ def test_validation_failure(self, grep_tool):
507
+ m = build_custom_tools_map([grep_tool])
508
+ entry = find_custom_tool(m, "GREP")
509
+ result = execute_custom_tool(entry, {}, MockSessionContext()) # type: ignore # missing required "pattern"
510
+ assert result["successful"] is False
511
+ assert "validation" in result["error"].lower()
512
+
513
+ def test_execute_function_error(self):
514
+ def bad_execute(input, ctx):
515
+ raise RuntimeError("Something went wrong")
516
+
517
+ tool = experimental_create_tool(
518
+ "BAD",
519
+ name="Bad",
520
+ description="Desc",
521
+ input_params=GrepInput,
522
+ execute=bad_execute,
523
+ )
524
+ m = build_custom_tools_map([tool])
525
+ entry = find_custom_tool(m, "BAD")
526
+ result = execute_custom_tool(entry, {"pattern": "x"}, MockSessionContext()) # type: ignore
527
+ assert result["successful"] is False
528
+ assert "Something went wrong" in result["error"]
529
+
530
+ def test_execute_returns_none(self):
531
+ tool = experimental_create_tool(
532
+ "NOOP",
533
+ name="Noop",
534
+ description="Returns None",
535
+ input_params=GrepInput,
536
+ execute=lambda i, c: None, # type: ignore
537
+ )
538
+ m = build_custom_tools_map([tool])
539
+ entry = find_custom_tool(m, "NOOP")
540
+ result = execute_custom_tool(entry, {"pattern": "x"}, MockSessionContext()) # type: ignore
541
+ assert result["successful"] is True
542
+ assert result["data"] == {}
543
+
544
+
545
+# ────────────────────────────────────────────────────────────────
546
+# SessionContextImpl tests
547
+# ────────────────────────────────────────────────────────────────
548
+
549
+
550
+class TestSessionContextImpl:
551
+ def test_user_id(self):
552
+ ctx = SessionContextImpl(
553
+ client=MagicMock(),
554
+ user_id="user-1",
555
+ session_id="sess-1",
556
+ )
557
+ assert ctx.user_id == "user-1"
558
+
559
+ def test_execute_routes_to_sibling(self, grep_tool):
560
+ m = build_custom_tools_map([grep_tool])
561
+ ctx = SessionContextImpl(
562
+ client=MagicMock(),
563
+ user_id="user-1",
564
+ session_id="sess-1",
565
+ custom_tools_map=m,
566
+ )
567
+ result = ctx.execute("GREP", {"pattern": "test"})
568
+ assert result["successful"] is True
569
+ assert result["data"]["matches"] == ["test"]
570
+
571
+ def test_execute_falls_back_to_remote(self, grep_tool):
572
+ m = build_custom_tools_map([grep_tool])
573
+ mock_client = MagicMock()
574
+ mock_response = MagicMock()
575
+ mock_response.data = {"remote": True}
576
+ mock_response.error = None
577
+ mock_client.tool_router.session.execute.return_value = mock_response
578
+
579
+ ctx = SessionContextImpl(
580
+ client=mock_client,
581
+ user_id="user-1",
582
+ session_id="sess-1",
583
+ custom_tools_map=m,
584
+ )
585
+ result = ctx.execute("NONEXISTENT_TOOL", {"arg": "val"})
586
+ mock_client.tool_router.session.execute.assert_called_once()
587
+ assert result["data"] == {"remote": True}
588
+
589
+ def test_proxy_execute(self):
590
+ mock_client = MagicMock()
591
+ mock_response = MagicMock()
592
+ mock_response.status = 200
593
+ mock_response.data = {"result": "ok"}
594
+ mock_response.headers = {"Content-Type": "application/json"}
595
+ mock_response.binary_data = None
596
+ mock_client.tool_router.session.proxy_execute.return_value = mock_response
597
+
598
+ ctx = SessionContextImpl(
599
+ client=mock_client,
600
+ user_id="user-1",
601
+ session_id="sess-1",
602
+ )
603
+ result = ctx.proxy_execute(
604
+ toolkit="gmail",
605
+ endpoint="https://gmail.googleapis.com/test",
606
+ method="GET",
607
+ )
608
+ assert result["status"] == 200
609
+ assert result["data"] == {"result": "ok"}
610
+ mock_client.tool_router.session.proxy_execute.assert_called_once()
611
+
612
+
613
+# ────────────────────────────────────────────────────────────────
614
+# ToolRouterSession integration tests
615
+# ────────────────────────────────────────────────────────────────
616
+
617
+
618
+@pytest.fixture
619
+def mock_session_deps(grep_tool, email_tool, role_toolkit):
620
+ """Create mock dependencies for ToolRouterSession with custom tools."""
621
+ client = MagicMock()
622
+ provider = MagicMock()
623
+ experimental = MagicMock()
624
+ experimental.files = MagicMock()
625
+ experimental.assistive_prompt = None
626
+
627
+ # Build tools map
628
+ tools_map = build_custom_tools_map([grep_tool, email_tool], [role_toolkit])
629
+
630
+ return {
631
+ "client": client,
632
+ "provider": provider,
633
+ "experimental": experimental,
634
+ "tools_map": tools_map,
635
+ }
636
+
637
+
638
+class TestToolRouterSessionCustomTools:
639
+ def test_execute_routes_to_local(self, mock_session_deps, grep_tool):
640
+ session = ToolRouterSession(
641
+ client=mock_session_deps["client"],
642
+ provider=mock_session_deps["provider"],
643
+ auto_upload_download_files=True,
644
+ session_id="sess-1",
645
+ mcp=MagicMock(),
646
+ experimental=mock_session_deps["experimental"],
647
+ custom_tools_map=mock_session_deps["tools_map"],
648
+ user_id="user-1",
649
+ )
650
+ result = session.execute("GREP", arguments={"pattern": "test"})
651
+ assert result["successful"] is True
652
+ assert result["data"]["matches"] == ["test"]
653
+ # Should NOT have called the backend
654
+ mock_session_deps["client"].tool_router.session.execute.assert_not_called()
655
+
656
+ def test_execute_routes_to_local_by_final_slug(self, mock_session_deps):
657
+ session = ToolRouterSession(
658
+ client=mock_session_deps["client"],
659
+ provider=mock_session_deps["provider"],
660
+ auto_upload_download_files=True,
661
+ session_id="sess-1",
662
+ mcp=MagicMock(),
663
+ experimental=mock_session_deps["experimental"],
664
+ custom_tools_map=mock_session_deps["tools_map"],
665
+ user_id="user-1",
666
+ )
667
+ result = session.execute("LOCAL_GREP", arguments={"pattern": "test"})
668
+ assert result["successful"] is True
669
+
670
+ def test_execute_case_insensitive(self, mock_session_deps):
671
+ session = ToolRouterSession(
672
+ client=mock_session_deps["client"],
673
+ provider=mock_session_deps["provider"],
674
+ auto_upload_download_files=True,
675
+ session_id="sess-1",
676
+ mcp=MagicMock(),
677
+ experimental=mock_session_deps["experimental"],
678
+ custom_tools_map=mock_session_deps["tools_map"],
679
+ user_id="user-1",
680
+ )
681
+ result = session.execute("grep", arguments={"pattern": "test"})
682
+ assert result["successful"] is True
683
+
684
+ def test_execute_routes_to_remote(self, mock_session_deps):
685
+ mock_response = MagicMock()
686
+ mock_session_deps["client"].tool_router.session.execute.return_value = (
687
+ mock_response
688
+ )
689
+
690
+ session = ToolRouterSession(
691
+ client=mock_session_deps["client"],
692
+ provider=mock_session_deps["provider"],
693
+ auto_upload_download_files=True,
694
+ session_id="sess-1",
695
+ mcp=MagicMock(),
696
+ experimental=mock_session_deps["experimental"],
697
+ custom_tools_map=mock_session_deps["tools_map"],
698
+ user_id="user-1",
699
+ )
700
+ session.execute("GMAIL_SEND_EMAIL", arguments={"to": "alice@example.com"})
701
+ mock_session_deps["client"].tool_router.session.execute.assert_called_once()
702
+
703
+ def test_custom_tools_list(self, mock_session_deps):
704
+ session = ToolRouterSession(
705
+ client=mock_session_deps["client"],
706
+ provider=mock_session_deps["provider"],
707
+ auto_upload_download_files=True,
708
+ session_id="sess-1",
709
+ mcp=MagicMock(),
710
+ experimental=mock_session_deps["experimental"],
711
+ custom_tools_map=mock_session_deps["tools_map"],
712
+ user_id="user-1",
713
+ )
714
+ tools = session.custom_tools()
715
+ assert len(tools) == 3
716
+ slugs = {t.slug for t in tools}
717
+ assert "LOCAL_GREP" in slugs
718
+ assert "LOCAL_GMAIL_GET_EMAILS" in slugs
719
+ assert "LOCAL_ROLE_MANAGER_SET_ROLE" in slugs
720
+
721
+ def test_custom_tools_filter_by_toolkit(self, mock_session_deps):
722
+ session = ToolRouterSession(
723
+ client=mock_session_deps["client"],
724
+ provider=mock_session_deps["provider"],
725
+ auto_upload_download_files=True,
726
+ session_id="sess-1",
727
+ mcp=MagicMock(),
728
+ experimental=mock_session_deps["experimental"],
729
+ custom_tools_map=mock_session_deps["tools_map"],
730
+ user_id="user-1",
731
+ )
732
+ gmail_tools = session.custom_tools(toolkit="gmail")
733
+ assert len(gmail_tools) == 1
734
+ assert gmail_tools[0].slug == "LOCAL_GMAIL_GET_EMAILS"
735
+
736
+ def test_custom_toolkits_list(self, mock_session_deps):
737
+ session = ToolRouterSession(
738
+ client=mock_session_deps["client"],
739
+ provider=mock_session_deps["provider"],
740
+ auto_upload_download_files=True,
741
+ session_id="sess-1",
742
+ mcp=MagicMock(),
743
+ experimental=mock_session_deps["experimental"],
744
+ custom_tools_map=mock_session_deps["tools_map"],
745
+ user_id="user-1",
746
+ )
747
+ toolkits = session.custom_toolkits()
748
+ assert len(toolkits) == 1
749
+ assert toolkits[0].slug == "ROLE_MANAGER"
750
+ assert len(toolkits[0].tools) == 1
751
+ assert toolkits[0].tools[0].slug == "LOCAL_ROLE_MANAGER_SET_ROLE"
752
+
753
+ def test_custom_tools_empty_when_no_map(self):
754
+ session = ToolRouterSession(
755
+ client=MagicMock(),
756
+ provider=MagicMock(),
757
+ auto_upload_download_files=True,
758
+ session_id="sess-1",
759
+ mcp=MagicMock(),
760
+ experimental=MagicMock(),
761
+ )
762
+ assert session.custom_tools() == []
763
+ assert session.custom_toolkits() == []
764
+
765
+ def test_proxy_execute(self, mock_session_deps):
766
+ mock_response = MagicMock()
767
+ mock_response.status = 200
768
+ mock_response.data = {"result": "ok"}
769
+ mock_response.headers = {"Content-Type": "application/json"}
770
+ mock_response.binary_data = None
771
+ mock_session_deps[
772
+ "client"
773
+ ].tool_router.session.proxy_execute.return_value = mock_response
774
+
775
+ session = ToolRouterSession(
776
+ client=mock_session_deps["client"],
777
+ provider=mock_session_deps["provider"],
778
+ auto_upload_download_files=True,
779
+ session_id="sess-1",
780
+ mcp=MagicMock(),
781
+ experimental=mock_session_deps["experimental"],
782
+ )
783
+ result = session.proxy_execute(
784
+ toolkit="gmail",
785
+ endpoint="https://gmail.googleapis.com/test",
786
+ method="GET",
787
+ )
788
+ assert result["status"] == 200
789
+ mock_session_deps[
790
+ "client"
791
+ ].tool_router.session.proxy_execute.assert_called_once()
792
+
793
+
794
+# ────────────────────────────────────────────────────────────────
795
+# Multi-execute routing tests
796
+# ────────────────────────────────────────────────────────────────
797
+
798
+
799
+class TestMultiExecuteRouting:
800
+ def _make_session(self, grep_tool, mock_client=None):
801
+ m = build_custom_tools_map([grep_tool])
802
+ client = mock_client or MagicMock()
803
+ session = ToolRouterSession(
804
+ client=client,
805
+ provider=MagicMock(),
806
+ auto_upload_download_files=True,
807
+ session_id="sess-1",
808
+ mcp=MagicMock(),
809
+ experimental=MagicMock(),
810
+ custom_tools_map=m,
811
+ user_id="user-1",
812
+ )
813
+ return session
814
+
815
+ def test_route_all_local(self, grep_tool):
816
+ session = self._make_session(grep_tool)
817
+ mock_tools_model = MagicMock()
818
+
819
+ result = session._route_multi_execute(
820
+ {"tools": [{"tool_slug": "GREP", "arguments": {"pattern": "test"}}]},
821
+ mock_tools_model,
822
+ None,
823
+ )
824
+ # Single local tool returns unwrapped
825
+ assert result["successful"] is True
826
+ assert result["data"]["matches"] == ["test"]
827
+
828
+ def test_route_all_remote(self, grep_tool):
829
+ session = self._make_session(grep_tool)
830
+ mock_tools_model = MagicMock()
831
+
832
+ remote_response = {
833
+ "data": {"results": [{"tool_slug": "GMAIL_SEND", "response": {"successful": True}}]},
834
+ "error": None,
835
+ "successful": True,
836
+ }
837
+ mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (
838
+ lambda slug, args: remote_response
839
+ )
840
+
841
+ result = session._route_multi_execute(
842
+ {
843
+ "tools": [
844
+ {"tool_slug": "GMAIL_SEND", "arguments": {"to": "alice@x.com"}}
845
+ ]
846
+ },
847
+ mock_tools_model,
848
+ None,
849
+ )
850
+ assert result == remote_response
851
+
852
+ def test_route_mixed_local_and_remote(self, grep_tool):
853
+ session = self._make_session(grep_tool)
854
+ mock_tools_model = MagicMock()
855
+
856
+ remote_response = {
857
+ "data": {
858
+ "results": [
859
+ {
860
+ "tool_slug": "GMAIL_SEND",
861
+ "response": {"successful": True, "data": {"sent": True}},
862
+ }
863
+ ]
864
+ },
865
+ "error": None,
866
+ "successful": True,
867
+ }
868
+ mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (
869
+ lambda slug, args: remote_response
870
+ )
871
+
872
+ result = session._route_multi_execute(
873
+ {
874
+ "tools": [
875
+ {"tool_slug": "GREP", "arguments": {"pattern": "test"}},
876
+ {"tool_slug": "GMAIL_SEND", "arguments": {"to": "alice@x.com"}},
877
+ ]
878
+ },
879
+ mock_tools_model,
880
+ None,
881
+ )
882
+ # Should have merged results
883
+ assert result["successful"] is True
884
+ results = result["data"]["results"]
885
+ assert len(results) == 2
886
+ # First should be the local GREP result
887
+ assert results[0]["tool_slug"] == "GREP"
888
+ assert results[0]["response"]["successful"] is True
889
+ # Second should be the remote result
890
+ assert results[1]["tool_slug"] == "GMAIL_SEND"
891
+
892
+ def test_route_empty_tools(self, grep_tool):
893
+ session = self._make_session(grep_tool)
894
+ mock_tools_model = MagicMock()
895
+ fallback_result = {"data": {}, "error": None, "successful": True}
896
+ mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (
897
+ lambda slug, args: fallback_result
898
+ )
899
+
900
+ result = session._route_multi_execute(
901
+ {"tools": []}, mock_tools_model, None
902
+ )
903
+ # Should fall back to remote
904
+ assert result == fallback_result
905
+
906
+ def test_route_multiple_local_tools(self):
907
+ tool1 = experimental_create_tool(
908
+ "TOOL_A",
909
+ name="A",
910
+ description="D",
911
+ input_params=GrepInput,
912
+ execute=lambda i, c: {"tool": "A", "pattern": i.pattern},
913
+ )
914
+ tool2 = experimental_create_tool(
915
+ "TOOL_B",
916
+ name="B",
917
+ description="D",
918
+ input_params=GrepInput,
919
+ execute=lambda i, c: {"tool": "B", "pattern": i.pattern},
920
+ )
921
+ m = build_custom_tools_map([tool1, tool2])
922
+ session = ToolRouterSession(
923
+ client=MagicMock(),
924
+ provider=MagicMock(),
925
+ auto_upload_download_files=True,
926
+ session_id="sess-1",
927
+ mcp=MagicMock(),
928
+ experimental=MagicMock(),
929
+ custom_tools_map=m,
930
+ user_id="user-1",
931
+ )
932
+ result = session._route_multi_execute(
933
+ {
934
+ "tools": [
935
+ {"tool_slug": "TOOL_A", "arguments": {"pattern": "x"}},
936
+ {"tool_slug": "TOOL_B", "arguments": {"pattern": "y"}},
937
+ ]
938
+ },
939
+ MagicMock(),
940
+ None,
941
+ )
942
+ assert result["successful"] is True
943
+ results = result["data"]["results"]
944
+ assert len(results) == 2
945
+ assert results[0]["response"]["data"]["tool"] == "A"
946
+ assert results[1]["response"]["data"]["tool"] == "B"