Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 948 lines 34.1 KB
Raw
1 """Custom tools and toolkits for tool router sessions.
2
3 Decorator API for defining custom tools that run in-process alongside
4 remote Composio tools. Accessed via ``composio.experimental``.
5
6 Usage::
7
8 from pydantic import BaseModel, Field
9 from composio import Composio
10
11 composio = Composio()
12
13 class GrepInput(BaseModel):
14 pattern: str = Field(description="Pattern to search for")
15
16 @composio.experimental.tool()
17 def grep(input: GrepInput, ctx):
18 \"\"\"Search for a pattern in local files.\"\"\"
19 return {"matches": []}
20
21 dev_tools = composio.experimental.Toolkit(
22 slug="DEV_TOOLS",
23 name="Dev Tools",
24 description="Local dev utilities",
25 )
26
27 @dev_tools.tool()
28 def search_code(input: GrepInput, ctx):
29 \"\"\"Search developer resources.\"\"\"
30 return {"results": []}
31
32 session = composio.create(
33 user_id="default",
34 experimental={
35 "local_tools": [grep],
36 "local_toolkits": [dev_tools],
37 },
38 )
39 """
40
41 from __future__ import annotations
42
43 import inspect
44 import sys
45 import typing as t
46
47 from pydantic import BaseModel
48
49 from composio.exceptions import ValidationError
50
51 from .custom_tool_types import (
52 LOCAL_TOOL_PREFIX,
53 MAX_SLUG_LENGTH,
54 SLUG_REGEX,
55 CustomTool,
56 CustomToolExecuteFn,
57 CustomToolkitWireDefinition,
58 CustomToolsMap,
59 CustomToolsMapEntry,
60 CustomToolWireDefinition,
61 )
62 from .tool_router_constants import PRELOAD_TOOLS_ALL
63
64 if t.TYPE_CHECKING:
65 from composio_client.types.tool_router.session_attach_response import (
66 Experimental as SessionAttachResponseExperimental,
67 )
68 from composio_client.types.tool_router.session_create_response import (
69 Experimental as SessionCreateResponseExperimental,
70 )
71 from composio_client.types.tool_router.session_retrieve_response import (
72 Experimental as SessionRetrieveResponseExperimental,
73 )
74
75
76 # ────────────────────────────────────────────────────────────────
77 # Slug validation helpers
78 # ────────────────────────────────────────────────────────────────
79
80
81 def _validate_slug(slug: str, context: str) -> str:
82 """Validate a custom tool or toolkit slug."""
83 if not slug:
84 raise ValidationError(f"{context}: slug is required")
85
86 if not SLUG_REGEX.match(slug):
87 raise ValidationError(
88 f"{context}: slug must only contain alphanumeric characters, "
89 f"underscores, and hyphens"
90 )
91
92 upper = slug.upper()
93 if upper.startswith("LOCAL_"):
94 raise ValidationError(
95 f'{context}: slug must not start with "LOCAL_" — '
96 f"this prefix is reserved for internal routing."
97 )
98 if upper.startswith("COMPOSIO_"):
99 raise ValidationError(
100 f'{context}: slug must not start with "COMPOSIO_" — '
101 f"this prefix is reserved for Composio meta tools."
102 )
103
104 return slug
105
106
107 def _compute_final_slug_length(tool_slug: str, toolkit_slug: t.Optional[str]) -> int:
108 """Compute the final slug length: LOCAL_[TOOLKIT_]SLUG."""
109 length = len(LOCAL_TOOL_PREFIX) + len(tool_slug)
110 if toolkit_slug:
111 length += len(toolkit_slug) + 1 # +1 for underscore separator
112 return length
113
114
115 def _validate_slug_length(
116 tool_slug: str, toolkit_slug: t.Optional[str], context: str
117 ) -> None:
118 """Validate that the final slug won't exceed the max length."""
119 final_length = _compute_final_slug_length(tool_slug, toolkit_slug)
120 if final_length > MAX_SLUG_LENGTH:
121 prefix = LOCAL_TOOL_PREFIX + (
122 f"{toolkit_slug.upper()}_" if toolkit_slug else ""
123 )
124 available = MAX_SLUG_LENGTH - len(prefix)
125 raise ValidationError(
126 f'{context}: slug "{tool_slug}" is too long. '
127 f'With prefix "{prefix}", the final slug would be {final_length} '
128 f"characters (max {MAX_SLUG_LENGTH}). "
129 f"Shorten the slug to at most {available} characters."
130 )
131
132
133 def _build_final_slug(tool_slug: str, toolkit_slug: t.Optional[str] = None) -> str:
134 """Build the final slug: LOCAL_[TOOLKIT_]SLUG."""
135 upper = tool_slug.upper()
136 if toolkit_slug:
137 return f"{LOCAL_TOOL_PREFIX}{toolkit_slug.upper()}_{upper}"
138 return f"{LOCAL_TOOL_PREFIX}{upper}"
139
140
141 def _qualified_original_slug_key(toolkit: t.Optional[str], original_slug: str) -> str:
142 return f"{toolkit.upper() if toolkit else ''}::{original_slug.upper()}"
143
144
145 def _can_share_original_slug(
146 existing: CustomToolsMapEntry, next_entry: CustomToolsMapEntry
147 ) -> bool:
148 return (
149 existing.toolkit is not None
150 and next_entry.toolkit is not None
151 and existing.toolkit.lower() != next_entry.toolkit.lower()
152 )
153
154
155 def _add_original_slug_alias(
156 *,
157 by_original_slug: t.Dict[str, CustomToolsMapEntry],
158 ambiguous_original_slugs: t.Set[str],
159 original_slug: str,
160 entry: CustomToolsMapEntry,
161 ) -> None:
162 original_slug_key = original_slug.upper()
163 if original_slug_key in ambiguous_original_slugs:
164 return
165
166 existing = by_original_slug.get(original_slug_key)
167 if existing is None:
168 by_original_slug[original_slug_key] = entry
169 return
170
171 if existing.final_slug.upper() == entry.final_slug.upper():
172 return
173
174 if _can_share_original_slug(existing, entry):
175 del by_original_slug[original_slug_key]
176 ambiguous_original_slugs.add(original_slug_key)
177 return
178
179 raise ValidationError(
180 f'Custom tool slug collision: original slug "{original_slug}" '
181 f'maps to multiple final slugs. "{existing.final_slug}" and '
182 f'"{entry.final_slug}" both resolve from "{original_slug_key}".'
183 )
184
185
186 def _get_input_json_schema(model: t.Type[BaseModel]) -> t.Dict[str, t.Any]:
187 """Convert a Pydantic model class to a JSON Schema dict suitable for the backend."""
188 full_schema = model.model_json_schema()
189 schema: t.Dict[str, t.Any] = {"type": "object"}
190 if "properties" in full_schema:
191 schema["properties"] = full_schema["properties"]
192 if "required" in full_schema:
193 schema["required"] = full_schema["required"]
194 if "$defs" in full_schema:
195 schema["$defs"] = full_schema["$defs"]
196 return schema
197
198
199 # ────────────────────────────────────────────────────────────────
200 # Internal tool creation (used by decorator API)
201 # ────────────────────────────────────────────────────────────────
202
203
204 def _create_tool(
205 slug: str,
206 *,
207 name: str,
208 description: str,
209 input_params: t.Type[BaseModel],
210 execute: CustomToolExecuteFn,
211 extends_toolkit: t.Optional[str] = None,
212 output_params: t.Optional[t.Type[BaseModel]] = None,
213 preload: t.Optional[bool] = None,
214 ) -> CustomTool:
215 """Internal: create and validate a CustomTool."""
216 context = "experimental.tool"
217
218 _validate_slug(slug, context)
219
220 if not name:
221 raise ValidationError(f"{context}: name is required")
222 if not description:
223 raise ValidationError(f"{context}: description is required")
224
225 if not isinstance(input_params, type) or not issubclass(input_params, BaseModel):
226 raise ValidationError(
227 f"{context}: input_params must be a Pydantic BaseModel subclass. "
228 f"Tool input parameters are always an object with named properties."
229 )
230
231 try:
232 from pydantic import RootModel
233
234 if issubclass(input_params, RootModel):
235 raise ValidationError(
236 f"{context}: input_params must be a regular BaseModel with named fields, "
237 f"not a RootModel. Tool input parameters are always an object with "
238 f"named properties."
239 )
240 except ImportError:
241 pass
242
243 if not callable(execute):
244 raise ValidationError(f"{context}: execute must be a callable")
245
246 if inspect.iscoroutinefunction(execute):
247 raise ValidationError(
248 f"{context}: execute must be a synchronous function, not async. "
249 f"The Composio Python SDK is synchronous — use a regular "
250 f"'def fn(input, ctx)' instead of 'async def'."
251 )
252
253 _validate_slug_length(slug, extends_toolkit, context)
254
255 input_schema = _get_input_json_schema(input_params)
256
257 output_schema: t.Optional[t.Dict[str, t.Any]] = None
258 if output_params is not None:
259 if not isinstance(output_params, type) or not issubclass(
260 output_params, BaseModel
261 ):
262 raise ValidationError(
263 f"{context}: output_params must be a Pydantic BaseModel subclass"
264 )
265 output_schema = output_params.model_json_schema()
266
267 return CustomTool(
268 slug=slug,
269 name=name,
270 description=description,
271 extends_toolkit=extends_toolkit,
272 input_schema=input_schema,
273 output_schema=output_schema,
274 input_params=input_params,
275 execute=execute,
276 preload=preload,
277 )
278
279
280 def _get_caller_locals(depth: int = 2) -> t.Optional[t.Mapping[str, t.Any]]:
281 """Best-effort lookup of a caller frame's locals."""
282 frame = inspect.currentframe()
283 try:
284 caller = frame
285 for _ in range(depth):
286 caller = caller.f_back if caller is not None else None
287 return caller.f_locals if caller is not None else None
288 finally:
289 del frame
290
291
292 def _signature(fn: t.Callable[..., t.Any]) -> inspect.Signature:
293 """Read a signature without evaluating annotations that may not resolve yet."""
294 if sys.version_info >= (3, 14):
295 import annotationlib
296
297 # Python 3.14 evaluates annotations lazily; the default VALUE format
298 # raises NameError for names defined later or only under TYPE_CHECKING.
299 return inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
300 return inspect.signature(fn)
301
302
303 def _resolve_input_annotation(
304 fn: t.Callable[..., t.Any],
305 param: inspect.Parameter,
306 *,
307 localns: t.Optional[t.Mapping[str, t.Any]] = None,
308 ) -> t.Any:
309 """Resolve the input parameter's annotation, including string annotations.
310
311 Only this one annotation is resolved, so an unresolvable ``ctx`` or return
312 annotation (for example one imported under ``TYPE_CHECKING``) does not fail.
313 """
314 annotation = param.annotation
315 if isinstance(annotation, t.ForwardRef):
316 annotation = annotation.__forward_arg__
317 if not isinstance(annotation, str):
318 return annotation
319
320 def holder() -> None: ...
321
322 holder.__annotations__ = {param.name: annotation}
323 try:
324 return t.get_type_hints(
325 holder,
326 globalns=getattr(fn, "__globals__", {}),
327 localns=dict(localns) if localns is not None else None,
328 include_extras=True,
329 )[param.name]
330 except Exception as exc:
331 missing = exc.name if isinstance(exc, NameError) and exc.name else annotation
332 raise ValidationError(
333 f"experimental.tool: could not resolve the annotation {annotation!r} of "
334 f'the first parameter of "{fn.__name__}" '
335 f"({type(exc).__name__}: {exc}). Define {missing} before the tool, and "
336 f"import it at runtime rather than under `if TYPE_CHECKING:`."
337 ) from exc
338
339
340 def _infer_tool_from_function(
341 fn: t.Callable[..., t.Any],
342 *,
343 slug: t.Optional[str] = None,
344 name: t.Optional[str] = None,
345 description: t.Optional[str] = None,
346 extends_toolkit: t.Optional[str] = None,
347 output_params: t.Optional[t.Type[BaseModel]] = None,
348 preload: t.Optional[bool] = None,
349 annotation_locals: t.Optional[t.Mapping[str, t.Any]] = None,
350 ) -> CustomTool:
351 """Create a CustomTool by inferring metadata from a decorated function.
352
353 - slug: from ``fn.__name__.upper()``
354 - name: from ``fn.__name__`` humanized
355 - description: from ``fn.__doc__``
356 - input_params: from the first parameter with a BaseModel type annotation
357 """
358 # Infer slug
359 actual_slug = slug or fn.__name__.upper()
360 actual_name = name or fn.__name__.replace("_", " ").title()
361 actual_description = description or inspect.cleandoc(fn.__doc__ or "")
362
363 if not actual_description:
364 raise ValidationError(
365 f"experimental.tool: description is required. "
366 f'Add a docstring to "{fn.__name__}" or pass description=...'
367 )
368
369 # Validate and infer function signature.
370 # Accepted shapes (consistent with TS CustomToolExecuteFn):
371 # (input: BaseModel) — no session context needed
372 # (input: BaseModel, ctx) — with session context
373 # The first param MUST be annotated with a BaseModel subclass.
374 # Reject async before wrapping (wrapper would hide it from _create_tool)
375 if inspect.iscoroutinefunction(fn):
376 raise ValidationError(
377 f'experimental.tool: "{fn.__name__}" is async. '
378 f"The Composio Python SDK is synchronous — use a regular "
379 f"'def {fn.__name__}(input, ctx)' instead of 'async def'."
380 )
381
382 params = list(_signature(fn).parameters.values())
383
384 if not params:
385 raise ValidationError(
386 f'experimental.tool: "{fn.__name__}" must accept at least one parameter '
387 f"annotated with a Pydantic BaseModel subclass, e.g. "
388 f"def {fn.__name__}(input: MyInput, ctx): ..."
389 )
390
391 if len(params) > 2:
392 raise ValidationError(
393 f'experimental.tool: "{fn.__name__}" accepts {len(params)} parameters, '
394 f"but custom tools accept at most 2: (input: BaseModel, ctx). "
395 f"Extra parameters will not be populated at runtime."
396 )
397
398 # First param must be the input model
399 first = params[0]
400 first_annotation = _resolve_input_annotation(fn, first, localns=annotation_locals)
401 if first_annotation is inspect.Parameter.empty or not (
402 isinstance(first_annotation, type) and issubclass(first_annotation, BaseModel)
403 ):
404 raise ValidationError(
405 f'experimental.tool: first parameter of "{fn.__name__}" must be annotated '
406 f"with a Pydantic BaseModel subclass. Got: {first_annotation!r}. "
407 f"Expected: def {fn.__name__}(input: MyInput, ctx): ..."
408 )
409 input_params: t.Type[BaseModel] = first_annotation
410
411 # Wrap function to match CustomToolExecuteFn: (input, ctx) -> dict
412 if len(params) == 1:
413
414 def execute(input: t.Any, ctx: t.Any) -> t.Dict[str, t.Any]:
415 return fn(input)
416 else:
417 execute = fn
418
419 return _create_tool(
420 slug=actual_slug,
421 name=actual_name,
422 description=actual_description,
423 input_params=input_params,
424 execute=execute,
425 extends_toolkit=extends_toolkit,
426 output_params=output_params,
427 preload=preload,
428 )
429
430
431 # ────────────────────────────────────────────────────────────────
432 # ExperimentalToolkit — custom toolkit with .tool() decorator
433 # ────────────────────────────────────────────────────────────────
434
435
436 class ExperimentalToolkit:
437 """Custom toolkit that groups related tools under one namespace.
438
439 Use ``@toolkit.tool()`` to add tools. Pass the toolkit to
440 ``composio.create(experimental={"local_toolkits": [toolkit]})``.
441
442 Tools added to a toolkit must NOT use ``extends_toolkit`` — they
443 inherit the toolkit identity instead.
444
445 Example::
446
447 dev_tools = composio.experimental.Toolkit(
448 slug="DEV_TOOLS",
449 name="Dev Tools",
450 description="Local dev utilities",
451 )
452
453 @dev_tools.tool()
454 def search_code(input: SearchInput, ctx):
455 \"\"\"Search developer resources.\"\"\"
456 return {"results": []}
457 """
458
459 def __init__(
460 self,
461 *,
462 slug: str,
463 name: str,
464 description: str,
465 preload: t.Optional[bool] = None,
466 ) -> None:
467 context = "experimental.Toolkit"
468 _validate_slug(slug, context)
469 if not name:
470 raise ValidationError(f"{context}: name is required")
471 if not description:
472 raise ValidationError(f"{context}: description is required")
473
474 self.slug = slug
475 self.name = name
476 self.description = description
477 self.preload = preload
478 self._tools: t.List[CustomTool] = []
479
480 @property
481 def tools(self) -> t.Tuple[CustomTool, ...]:
482 return tuple(self._tools)
483
484 @t.overload
485 def tool(self, fn: t.Callable[..., t.Any], /) -> CustomTool: ...
486
487 @t.overload
488 def tool(
489 self,
490 *,
491 slug: t.Optional[str] = None,
492 name: t.Optional[str] = None,
493 description: t.Optional[str] = None,
494 output_params: t.Optional[t.Type[BaseModel]] = None,
495 preload: t.Optional[bool] = None,
496 ) -> t.Callable[[t.Callable[..., t.Any]], CustomTool]: ...
497
498 def tool(
499 self,
500 fn: t.Optional[t.Callable[..., t.Any]] = None,
501 *,
502 slug: t.Optional[str] = None,
503 name: t.Optional[str] = None,
504 description: t.Optional[str] = None,
505 output_params: t.Optional[t.Type[BaseModel]] = None,
506 preload: t.Optional[bool] = None,
507 ) -> t.Union[CustomTool, t.Callable[[t.Callable[..., t.Any]], CustomTool]]:
508 """Decorator to add a tool to this toolkit.
509
510 Infers slug, name, description, and input_params from the function
511 if not explicitly provided.
512 """
513
514 def decorator(f: t.Callable[..., t.Any]) -> CustomTool:
515 annotation_locals = _get_caller_locals()
516 custom_tool = _infer_tool_from_function(
517 f,
518 slug=slug,
519 name=name,
520 description=description,
521 output_params=output_params,
522 preload=preload,
523 annotation_locals=annotation_locals,
524 # No extends_toolkit for toolkit tools
525 )
526 _validate_slug_length(
527 custom_tool.slug, self.slug, f'experimental.Toolkit("{self.slug}").tool'
528 )
529 self._tools.append(custom_tool)
530 return custom_tool
531
532 if fn is not None:
533 custom_tool = _infer_tool_from_function(
534 fn,
535 slug=slug,
536 name=name,
537 description=description,
538 output_params=output_params,
539 preload=preload,
540 annotation_locals=_get_caller_locals(),
541 )
542 _validate_slug_length(
543 custom_tool.slug,
544 self.slug,
545 f'experimental.Toolkit("{self.slug}").tool',
546 )
547 self._tools.append(custom_tool)
548 return custom_tool
549 return decorator
550
551
552 LocalToolkit = ExperimentalToolkit
553 """Toolkit that groups local tools, created with ``composio.experimental.Toolkit()``."""
554
555
556 # ────────────────────────────────────────────────────────────────
557 # Serialization (for backend API payload)
558 # ────────────────────────────────────────────────────────────────
559
560
561 def _serialized_preload_value(
562 preload: t.Optional[bool],
563 inherited_preload: t.Optional[bool],
564 default_preload: bool,
565 ) -> t.Optional[bool]:
566 inherited_or_default = (
567 inherited_preload if inherited_preload is not None else default_preload
568 )
569 if preload is not None:
570 return preload if preload or inherited_or_default else None
571 if inherited_preload is not None:
572 return inherited_preload if inherited_preload or default_preload else None
573 return True if default_preload else None
574
575
576 def serialize_custom_tools(
577 tools: t.List[CustomTool],
578 *,
579 default_preload: bool = False,
580 ) -> t.List[CustomToolWireDefinition]:
581 """Serialize custom tools into the format expected by the backend."""
582 result: t.List[CustomToolWireDefinition] = []
583 for tool in tools:
584 entry: CustomToolWireDefinition = {
585 "slug": tool.slug,
586 "name": tool.name,
587 "description": tool.description,
588 "input_schema": tool.input_schema,
589 }
590 if tool.output_schema:
591 entry["output_schema"] = tool.output_schema
592 if tool.extends_toolkit:
593 entry["extends_toolkit"] = tool.extends_toolkit
594 preload = _serialized_preload_value(
595 tool.preload, inherited_preload=None, default_preload=default_preload
596 )
597 if preload is not None:
598 entry["preload"] = preload
599 result.append(entry)
600 return result
601
602
603 def serialize_custom_toolkits(
604 toolkits: t.Sequence[ExperimentalToolkit],
605 *,
606 default_preload: bool = False,
607 ) -> t.List[CustomToolkitWireDefinition]:
608 """Serialize custom toolkits into the format expected by the backend."""
609 result: t.List[CustomToolkitWireDefinition] = []
610 for tk in toolkits:
611 toolkit_tools: t.List[CustomToolWireDefinition] = []
612 for tool in tk.tools:
613 entry: CustomToolWireDefinition = {
614 "slug": tool.slug,
615 "name": tool.name,
616 "description": tool.description,
617 "input_schema": tool.input_schema,
618 }
619 if tool.output_schema:
620 entry["output_schema"] = tool.output_schema
621 preload = _serialized_preload_value(
622 tool.preload,
623 inherited_preload=tk.preload,
624 default_preload=default_preload,
625 )
626 if preload is not None:
627 entry["preload"] = preload
628 toolkit_tools.append(entry)
629 toolkit_entry: CustomToolkitWireDefinition = {
630 "slug": tk.slug,
631 "name": tk.name,
632 "description": tk.description,
633 "tools": toolkit_tools,
634 }
635 preload = _serialized_preload_value(
636 tk.preload, inherited_preload=None, default_preload=default_preload
637 )
638 if preload is not None:
639 toolkit_entry["preload"] = preload
640 result.append(toolkit_entry)
641 return result
642
643
644 # ────────────────────────────────────────────────────────────────
645 # Routing map builders
646 # ────────────────────────────────────────────────────────────────
647
648
649 def build_custom_tools_map(
650 tools: t.List[CustomTool],
651 toolkits: t.Optional[t.List[ExperimentalToolkit]] = None,
652 ) -> CustomToolsMap:
653 """Build a CustomToolsMap from custom tools and toolkits."""
654 by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}
655 by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
656 by_toolkit_and_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
657 ambiguous_original_slugs: t.Set[str] = set()
658
659 def add_entry(
660 handle: CustomTool, final_slug: str, toolkit: t.Optional[str]
661 ) -> None:
662 original_slug = handle.slug.upper()
663 # Custom tool slugs are matched case-insensitively across local and response maps.
664 final_slug_key = final_slug.upper()
665
666 if len(final_slug) > MAX_SLUG_LENGTH:
667 raise ValidationError(
668 f'Custom tool slug "{handle.slug}" produces final slug '
669 f'"{final_slug}" which exceeds {MAX_SLUG_LENGTH} characters.'
670 )
671
672 if final_slug_key in by_final_slug:
673 raise ValidationError(
674 f'Custom tool slug collision: "{final_slug}" is already registered.'
675 )
676
677 qualified_key = _qualified_original_slug_key(toolkit, original_slug)
678 if qualified_key in by_toolkit_and_original_slug:
679 raise ValidationError(
680 f'Custom tool slug collision: original slug "{handle.slug}" '
681 f'is already registered for toolkit "{toolkit or "custom"}".'
682 )
683
684 entry = CustomToolsMapEntry(
685 handle=handle, final_slug=final_slug, toolkit=toolkit
686 )
687 by_final_slug[final_slug_key] = entry
688 by_toolkit_and_original_slug[qualified_key] = entry
689 _add_original_slug_alias(
690 by_original_slug=by_original_slug,
691 ambiguous_original_slugs=ambiguous_original_slugs,
692 original_slug=original_slug,
693 entry=entry,
694 )
695
696 # Process standalone tools
697 for handle in tools:
698 add_entry(
699 handle,
700 _build_final_slug(handle.slug, handle.extends_toolkit),
701 handle.extends_toolkit,
702 )
703
704 # Process toolkit tools
705 if toolkits:
706 for tk in toolkits:
707 for handle in tk.tools:
708 add_entry(handle, _build_final_slug(handle.slug, tk.slug), tk.slug)
709
710 return CustomToolsMap(
711 by_final_slug=by_final_slug,
712 by_original_slug=by_original_slug,
713 by_toolkit_and_original_slug=by_toolkit_and_original_slug,
714 ambiguous_original_slugs=ambiguous_original_slugs,
715 toolkits=list(toolkits) if toolkits else None,
716 tools=list(tools) if tools else None,
717 )
718
719
720 def build_custom_tools_map_from_response(
721 tools: t.List[CustomTool],
722 toolkits: t.Optional[t.List[ExperimentalToolkit]],
723 experimental: t.Optional[
724 t.Union[
725 "SessionAttachResponseExperimental",
726 "SessionCreateResponseExperimental",
727 "SessionRetrieveResponseExperimental",
728 ]
729 ],
730 ) -> CustomToolsMap:
731 """Build a CustomToolsMap using the slug/original_slug mapping from the backend response."""
732 by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}
733 by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
734 by_toolkit_and_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
735 ambiguous_original_slugs: t.Set[str] = set()
736
737 # Build lookups from toolkit + original slug and from original slug -> matches.
738 handles_by_qualified_original: t.Dict[
739 str, t.Tuple[CustomTool, t.Optional[str]]
740 ] = {}
741 handles_by_original: t.Dict[str, t.List[t.Tuple[CustomTool, t.Optional[str]]]] = {}
742
743 def register_handle(handle: CustomTool, toolkit: t.Optional[str]) -> None:
744 original_slug = handle.slug.upper()
745 match = (handle, toolkit)
746 handles_by_qualified_original[
747 _qualified_original_slug_key(toolkit, original_slug)
748 ] = match
749 handles_by_original.setdefault(original_slug, []).append(match)
750
751 for handle in tools:
752 register_handle(handle, handle.extends_toolkit)
753 if toolkits:
754 for tk in toolkits:
755 for handle in tk.tools:
756 register_handle(handle, tk.slug)
757
758 def find_handle(
759 final_slug: str, original_slug: str, toolkit: t.Optional[str]
760 ) -> t.Optional[t.Tuple[CustomTool, t.Optional[str]]]:
761 original_slug_key = original_slug.upper()
762 qualified_match = handles_by_qualified_original.get(
763 _qualified_original_slug_key(toolkit, original_slug_key)
764 )
765 if qualified_match is not None:
766 return qualified_match
767
768 bare_matches = handles_by_original.get(original_slug_key, [])
769 if not bare_matches:
770 # Response tool not defined locally; nothing to route in-process.
771 return None
772 # A bare match may only stand in when the response carries no toolkit
773 # identity. Binding a toolkit child to another toolkit's handler would
774 # silently execute the wrong implementation.
775 if toolkit is None and len(bare_matches) == 1:
776 return bare_matches[0]
777
778 registered = sorted(
779 {(match_toolkit or "custom").upper() for _, match_toolkit in bare_matches}
780 )
781 raise ValidationError(
782 f'Cannot map custom tool "{final_slug}": original slug '
783 f'"{original_slug}" for toolkit "{toolkit or "custom"}" has no exact '
784 f"local match. Registered for toolkits: {', '.join(registered)}."
785 )
786
787 def add_entry(
788 final_slug: str, original_slug: str, toolkit: t.Optional[str]
789 ) -> None:
790 resolved_toolkit = toolkit
791 match = find_handle(final_slug, original_slug, resolved_toolkit)
792 if not match:
793 return
794 handle, default_toolkit = match
795 if resolved_toolkit is None:
796 resolved_toolkit = default_toolkit
797
798 final_slug_key = final_slug.upper()
799 if final_slug_key in by_final_slug:
800 raise ValidationError(
801 f'Custom tool slug collision: "{final_slug}" is already registered.'
802 )
803
804 qualified_key = _qualified_original_slug_key(resolved_toolkit, original_slug)
805 if qualified_key in by_toolkit_and_original_slug:
806 raise ValidationError(
807 f'Custom tool slug collision: original slug "{handle.slug}" '
808 f'is already registered for toolkit "{resolved_toolkit or "custom"}".'
809 )
810
811 entry = CustomToolsMapEntry(
812 handle=handle, final_slug=final_slug, toolkit=resolved_toolkit
813 )
814 by_final_slug[final_slug_key] = entry
815 by_toolkit_and_original_slug[qualified_key] = entry
816 _add_original_slug_alias(
817 by_original_slug=by_original_slug,
818 ambiguous_original_slugs=ambiguous_original_slugs,
819 original_slug=original_slug,
820 entry=entry,
821 )
822
823 if experimental and experimental.custom_tools:
824 for ct in experimental.custom_tools:
825 add_entry(ct.slug, ct.original_slug, ct.extends_toolkit)
826
827 if experimental and experimental.custom_toolkits:
828 for ctk in experimental.custom_toolkits:
829 for ctk_tool in ctk.tools:
830 add_entry(ctk_tool.slug, ctk_tool.original_slug, ctk.slug)
831
832 # Ambiguity follows the local definitions, not whichever subset the
833 # response happened to include: a shared child slug must never become
834 # callable by its bare name just because a sibling was omitted.
835 for original_slug_key, matches in handles_by_original.items():
836 if len(matches) > 1:
837 by_original_slug.pop(original_slug_key, None)
838 ambiguous_original_slugs.add(original_slug_key)
839
840 return CustomToolsMap(
841 by_final_slug=by_final_slug,
842 by_original_slug=by_original_slug,
843 by_toolkit_and_original_slug=by_toolkit_and_original_slug,
844 ambiguous_original_slugs=ambiguous_original_slugs,
845 toolkits=list(toolkits) if toolkits else None,
846 tools=list(tools) if tools else None,
847 )
848
849
850 def find_custom_tool_map_entry_by_final_slug(
851 custom_tools_map: t.Optional[CustomToolsMap],
852 slug: str,
853 ) -> t.Optional[CustomToolsMapEntry]:
854 """Find a custom tool entry by final slug only."""
855 if custom_tools_map is None:
856 return None
857 return custom_tools_map.by_final_slug.get(slug.upper())
858
859
860 def find_custom_tool_map_entry_by_toolkit_and_original_slug(
861 custom_tools_map: t.Optional[CustomToolsMap],
862 toolkit: t.Optional[str],
863 slug: str,
864 ) -> t.Optional[CustomToolsMapEntry]:
865 """Find a custom toolkit tool by toolkit slug and original tool slug."""
866 if custom_tools_map is None:
867 return None
868 return custom_tools_map.by_toolkit_and_original_slug.get(
869 _qualified_original_slug_key(toolkit, slug)
870 )
871
872
873 def assert_no_custom_tool_slugs_in_preload(
874 preload_tools: t.Union[t.Sequence[str], t.Literal["all"], None],
875 custom_tools_map: t.Optional[CustomToolsMap],
876 ) -> None:
877 """Reject legacy top-level preload of custom tool slugs."""
878 if preload_tools is None or preload_tools == PRELOAD_TOOLS_ALL:
879 return
880 if isinstance(preload_tools, str):
881 raise ValidationError(
882 'preload.tools must be a list of Composio tool slugs or "all". '
883 "Set preload=True on the SDK custom tool or custom toolkit "
884 "definition to expose custom tools directly."
885 )
886
887 custom_preload_slugs = []
888 for slug in preload_tools:
889 normalized = slug.upper()
890 if normalized.startswith(LOCAL_TOOL_PREFIX) or (
891 # Top-level preload.tools is only for Composio-managed tool slugs.
892 # Custom tools use preload=True on their SDK definitions instead.
893 custom_tools_map is not None
894 and (
895 normalized in custom_tools_map.by_original_slug
896 or normalized in custom_tools_map.ambiguous_original_slugs
897 or normalized in custom_tools_map.by_final_slug
898 )
899 ):
900 custom_preload_slugs.append(slug)
901
902 if custom_preload_slugs:
903 raise ValidationError(
904 "Custom tool slugs are not supported in preload.tools: "
905 f"{', '.join(custom_preload_slugs)}. Set preload=True on the SDK "
906 "custom tool or custom toolkit definition instead."
907 )
908
909
910 def get_preloaded_custom_tool_slugs(
911 custom_tools_map: t.Optional[CustomToolsMap],
912 *,
913 default_preload: bool = False,
914 ) -> t.List[str]:
915 """Return final custom tool slugs selected locally for preload."""
916 if custom_tools_map is None:
917 return []
918
919 seen: t.Set[str] = set()
920 custom_tool_slugs: t.List[str] = []
921
922 for entry in custom_tools_map.by_final_slug.values():
923 toolkit = next(
924 (
925 tk
926 for tk in custom_tools_map.toolkits or []
927 if entry.toolkit and tk.slug.lower() == entry.toolkit.lower()
928 ),
929 None,
930 )
931 should_preload = (
932 entry.handle.preload
933 if entry.handle.preload is not None
934 else toolkit.preload
935 if toolkit is not None and toolkit.preload is not None
936 else default_preload
937 )
938 if not should_preload:
939 continue
940
941 final_slug_key = entry.final_slug.upper()
942 if final_slug_key in seen:
943 continue
944
945 seen.add(final_slug_key)
946 custom_tool_slugs.append(entry.final_slug)
947
948 return custom_tool_slugs