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 161 lines 5.49 KB
Raw
1 """
2 Base resource class for representing resources in the composio client.
3 """
4
5 import contextvars
6 from collections.abc import Mapping
7 import functools
8 import os
9 import time
10 import traceback
11 import typing as t
12
13 from composio_client import AutoAuth, NoAuth, ProjectAuth, Scope, UserAuth
14
15 from composio.__version__ import __version__
16 from composio.client import HttpClient
17 from composio.core.models.tool_router_constants import (
18 ORG_ID_HEADER,
19 PROJECT_ID_HEADER,
20 USER_API_KEY_HEADER,
21 )
22 from composio.utils.redaction import redact_sensitive_text
23 from composio.utils.logging import WithLogger
24
25 from ._telemetry import Event, create_event, push_event
26
27 PayloadT = t.TypeVar("PayloadT", bound=dict)
28
29 allow_tracking = contextvars.ContextVar[bool]("allow_tracking", default=True)
30 _environment = os.getenv("ENVIRONMENT", "development")
31
32
33 def trace_method(method: t.Callable, name: str) -> t.Callable:
34 """Wrap a method to log the call."""
35
36 # Check if the method is a class method
37 if getattr(method, "__self__", None) is not None:
38 return method
39
40 @functools.wraps(method)
41 def trace_wrapper(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
42 if not allow_tracking.get():
43 return method(self, *args, **kwargs)
44
45 event: t.Optional[Event] = None
46 start_time = time.time()
47 event = create_event(
48 type="metric",
49 functionName=name,
50 timestamp=time.time(),
51 props={},
52 source={
53 "environment": _environment, # type: ignore
54 "language": "python",
55 "service": "sdk",
56 "version": __version__,
57 },
58 metadata={
59 "provider": self._client.provider,
60 },
61 )
62 try:
63 return method(self, *args, **kwargs)
64 except Exception as e:
65 _, payload = event
66 payload["error"] = {
67 "name": e.__class__.__name__,
68 "message": redact_sensitive_text(str(e)),
69 "stack": redact_sensitive_text(traceback.format_exc()),
70 }
71 event = ("error", payload)
72 raise e
73 finally:
74 if event is not None:
75 event[1]["durationMs"] = (time.time() - start_time) * 1000
76 push_event(event=event)
77
78 trace_wrapper.__name__ = method.__name__
79 return trace_wrapper
80
81
82 class ResourceMeta(type):
83 """Meta class for resource classes."""
84
85 def __init__(cls, name, bases, attrs):
86 for attr in attrs:
87 if attr.startswith("_") or not callable(getattr(cls, attr)):
88 continue
89 setattr(cls, attr, trace_method(getattr(cls, attr), f"{name}.{attr}"))
90
91
92 class Resource(WithLogger, metaclass=ResourceMeta):
93 """Base resource class for composio client."""
94
95 def sanitize_payload(self, payload: PayloadT) -> PayloadT:
96 return {k: v for k, v in payload.items()} # type: ignore
97
98 def __init__(self, client: HttpClient):
99 super().__init__()
100 self._client = client
101
102
103 def header_value(headers: t.Mapping[str, t.Any], name: str) -> t.Optional[str]:
104 """The non-empty value of ``name`` in ``headers``, matched case-insensitively."""
105 if not isinstance(headers, Mapping):
106 return None
107 wanted = name.lower()
108 for key, value in headers.items():
109 if isinstance(key, str) and key.lower() == wanted:
110 if isinstance(value, str) and value:
111 return value
112 return None
113
114
115 def credential_headers(client: HttpClient) -> t.Dict[str, str]:
116 """The single credential header the client puts on its own requests.
117
118 For the destinations the SDK hands a credential to outside the client (the
119 session MCP config, the realtime channel auth). Read from the ``auth`` the
120 SDK constructed the client with, never from the client's read-back
121 properties: a project key (``ProjectAuth``, or ``AutoAuth`` holding one)
122 travels as ``x-api-key``, otherwise a user key (``UserAuth``, or
123 ``AutoAuth`` holding only a user key) as ``x-user-api-key``. Under
124 ``NoAuth`` a caller-placed ``x-user-api-key`` default header is the
125 credential. Empty when no such key is held as a string. The environment is
126 never consulted here.
127 """
128 auth = client.sdk_auth
129 project: object = None
130 user: object = None
131 if isinstance(auth, NoAuth):
132 user = header_value(client.default_headers, USER_API_KEY_HEADER)
133 elif isinstance(auth, ProjectAuth):
134 project = auth.credential
135 elif isinstance(auth, UserAuth):
136 user = auth.credential
137 elif isinstance(auth, AutoAuth):
138 project, user = auth.project, auth.user
139 if isinstance(project, str) and project:
140 return {"x-api-key": project}
141 if isinstance(user, str) and user:
142 return {USER_API_KEY_HEADER: user}
143 return {}
144
145
146 def scope_headers(client: HttpClient) -> t.Dict[str, str]:
147 """The ``x-org-id`` / ``x-project-id`` the client sends to its API origin:
148 its ``scope``, or without one the caller-placed default headers."""
149 scope = client.scope
150 if isinstance(scope, Scope):
151 pairs = (
152 (ORG_ID_HEADER, scope.organization_id),
153 (PROJECT_ID_HEADER, scope.project_id),
154 )
155 else:
156 default_headers: t.Mapping[str, t.Any] = client.default_headers
157 pairs = (
158 (ORG_ID_HEADER, header_value(default_headers, ORG_ID_HEADER)),
159 (PROJECT_ID_HEADER, header_value(default_headers, PROJECT_ID_HEADER)),
160 )
161 return {name: value for name, value in pairs if value}