datarobot-genai 0.2.6__py3-none-any.whl → 0.2.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,17 +12,23 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  import logging
15
+ import os
15
16
  import warnings
16
17
  from typing import Any
18
+ from typing import Protocol
17
19
 
20
+ import aiohttp
18
21
  import jwt
19
- from datarobot.auth.datarobot.oauth import AsyncOAuth as DatarobotAsyncOAuthClient
22
+ from datarobot.auth.datarobot.oauth import AsyncOAuth as DatarobotOAuthClient
23
+ from datarobot.auth.exceptions import OAuthProviderNotFound
24
+ from datarobot.auth.exceptions import OAuthValidationErr
20
25
  from datarobot.auth.identity import Identity
21
- from datarobot.auth.oauth import AsyncOAuthComponent
26
+ from datarobot.auth.oauth import OAuthToken
22
27
  from datarobot.auth.session import AuthCtx
23
28
  from datarobot.core.config import DataRobotAppFrameworkBaseSettings
24
29
  from datarobot.models.genai.agent.auth import ToolAuth
25
30
  from datarobot.models.genai.agent.auth import get_authorization_context
31
+ from mypyc.ir.ops import Sequence
26
32
  from pydantic import BaseModel
27
33
 
28
34
  logger = logging.getLogger(__name__)
@@ -183,52 +189,203 @@ class AuthContextHeaderHandler:
183
189
  return None
184
190
 
185
191
 
192
+ # --- OAuth Token Provider Implementation ---
193
+
194
+
195
+ class TokenRetriever(Protocol):
196
+ """Protocol for OAuth token retrievers."""
197
+
198
+ def filter_identities(self, identities: Sequence[Identity]) -> list[Identity]:
199
+ """Filter identities to only those valid for this retriever implementation."""
200
+ ...
201
+
202
+ async def refresh_access_token(self, identity: Identity) -> OAuthToken:
203
+ """Refresh the access token for the given identity ID.
204
+
205
+ Parameters
206
+ ----------
207
+ identity_id : str
208
+ The provider identity ID to refresh the token for.
209
+
210
+ Returns
211
+ -------
212
+ OAuthToken
213
+ The refreshed OAuth token.
214
+ """
215
+ ...
216
+
217
+
218
+ class DatarobotTokenRetriever:
219
+ """Retrieves OAuth tokens using the DataRobot platform."""
220
+
221
+ def __init__(self) -> None:
222
+ self._client = DatarobotOAuthClient()
223
+
224
+ def filter_identities(self, identities: Sequence[Identity]) -> list[Identity]:
225
+ """Filter oauth2 identities to only those with provider_identity_id.
226
+
227
+ The `provider_identity_id` is required in order to identify the provider
228
+ and retrieve the access token from DataRobot OAuth Providers service.
229
+ """
230
+ return [i for i in identities if i.type == "oauth2" and i.provider_identity_id]
231
+
232
+ async def refresh_access_token(self, identity: Identity) -> OAuthToken:
233
+ """Refresh the access token using DataRobot's OAuth client."""
234
+ return await self._client.refresh_access_token(provider_id=identity.provider_identity_id)
235
+
236
+
237
+ class AuthlibTokenRetriever:
238
+ """Retrieves OAuth tokens from a generic Authlib-based endpoint."""
239
+
240
+ def __init__(self, application_endpoint: str) -> None:
241
+ if not application_endpoint:
242
+ raise ValueError("AuthlibTokenRetriever requires 'application_endpoint'.")
243
+ self.application_endpoint = application_endpoint.rstrip("/")
244
+
245
+ def filter_identities(self, identities: Sequence[Identity]) -> list[Identity]:
246
+ """Filter identities to only OAuth2 identities."""
247
+ return [i for i in identities if i.type == "oauth2" and i.provider_identity_id is None]
248
+
249
+ async def refresh_access_token(self, identity: Identity) -> OAuthToken:
250
+ """Retrieve an OAuth token via an HTTP POST request.
251
+
252
+ Parameters
253
+ ----------
254
+ identity : Identity
255
+ The identity to retrieve the token for.
256
+
257
+ Returns
258
+ -------
259
+ OAuthToken
260
+ The retrieved OAuth token.
261
+ """
262
+ api_token = os.environ.get("DATAROBOT_API_TOKEN")
263
+ if not api_token:
264
+ raise ValueError("DATAROBOT_API_TOKEN environment variable is required but not set.")
265
+
266
+ token_url = f"{self.application_endpoint}/oauth/token/"
267
+ headers = {"Authorization": f"Bearer {api_token}"}
268
+ payload = {"identity_id": identity.id}
269
+ timeout = aiohttp.ClientTimeout(total=30)
270
+
271
+ try:
272
+ async with aiohttp.ClientSession(timeout=timeout) as session:
273
+ async with session.post(token_url, headers=headers, json=payload) as response:
274
+ response.raise_for_status()
275
+ data = await response.json()
276
+ logger.debug(f"Retrieved access token from {token_url}")
277
+ return OAuthToken(**data)
278
+ except aiohttp.ClientError as e:
279
+ logger.error(f"Error retrieving token from {token_url}: {e}")
280
+ raise
281
+
282
+
283
+ class OAuthConfig(BaseModel):
284
+ """Configuration extracted from AuthCtx metadata for OAuth operations."""
285
+
286
+ implementation: str = "datarobot"
287
+ application_endpoint: str | None = None
288
+
289
+ @classmethod
290
+ def from_auth_ctx(cls, auth_ctx: AuthCtx) -> "OAuthConfig":
291
+ metadata = auth_ctx.metadata or {}
292
+ return cls(
293
+ implementation=metadata.get("oauth_implementation", "datarobot"),
294
+ application_endpoint=metadata.get("application_endpoint"),
295
+ )
296
+
297
+
298
+ def create_token_retriever(config: OAuthConfig) -> TokenRetriever:
299
+ """Create a token retriever based on the OAuth configuration.
300
+
301
+ Parameters
302
+ ----------
303
+ config : OAuthConfig
304
+ The OAuth configuration specifying implementation type and endpoints.
305
+
306
+ Returns
307
+ -------
308
+ TokenRetriever
309
+ The configured token retriever instance.
310
+ """
311
+ if config.implementation == "datarobot":
312
+ return DatarobotTokenRetriever()
313
+
314
+ if config.implementation == "authlib":
315
+ if not config.application_endpoint:
316
+ raise ValueError("Required 'application_endpoint' not found in metadata.")
317
+ return AuthlibTokenRetriever(config.application_endpoint)
318
+
319
+ raise ValueError(
320
+ f"Unsupported OAuth implementation: '{config.implementation}'. "
321
+ f"Supported values: datarobot, authlib."
322
+ )
323
+
324
+
186
325
  class AsyncOAuthTokenProvider:
187
- """Manages OAuth access tokens using generic OAuth client."""
326
+ """Provides OAuth tokens for authorized users.
327
+
328
+ This class manages OAuth token retrieval for users with multiple identity providers.
329
+ It uses either DataRobot or Authlib as the OAuth token storage and refresh backend
330
+ based on the auth context metadata.
331
+ """
188
332
 
189
333
  def __init__(self, auth_ctx: AuthCtx) -> None:
334
+ """Initialize the provider with an authorization context.
335
+
336
+ Parameters
337
+ ----------
338
+ auth_ctx : AuthCtx
339
+ The authorization context containing user identities and metadata.
340
+ """
190
341
  self.auth_ctx = auth_ctx
191
- self.oauth_client = self._create_oauth_client()
342
+ config = OAuthConfig.from_auth_ctx(auth_ctx)
343
+ self._retriever = create_token_retriever(config)
192
344
 
193
345
  def _get_identity(self, provider_type: str | None) -> Identity:
194
- """Retrieve the appropriate identity from the authentication context."""
195
- identities = [x for x in self.auth_ctx.identities if x.provider_identity_id is not None]
196
-
197
- if not identities:
198
- raise ValueError("No identities found in authorization context.")
346
+ """Get identity from auth context, filtered by provider_type if specified."""
347
+ oauth_identities = self._retriever.filter_identities(self.auth_ctx.identities)
348
+ if not oauth_identities:
349
+ raise OAuthProviderNotFound("No OAuth provider found.")
199
350
 
200
351
  if provider_type is None:
201
- if len(identities) > 1:
202
- raise ValueError(
203
- "Multiple identities found. Please specify 'provider_type' parameter."
352
+ if len(oauth_identities) > 1:
353
+ raise OAuthValidationErr(
354
+ "Multiple OAuth providers found. Specify 'provider_type' parameter."
204
355
  )
205
- return identities[0]
206
-
207
- identity = next((id for id in identities if id.provider_type == provider_type), None)
356
+ return oauth_identities[0]
208
357
 
358
+ identity = next((i for i in oauth_identities if i.provider_type == provider_type), None)
209
359
  if identity is None:
210
- raise ValueError(f"No identity found for provider '{provider_type}'.")
211
-
360
+ raise OAuthValidationErr(f"No identity found for provider '{provider_type}'.")
212
361
  return identity
213
362
 
214
363
  async def get_token(self, auth_type: ToolAuth, provider_type: str | None = None) -> str:
215
- """Get OAuth access token using the specified method."""
364
+ """Get an OAuth access token for the specified auth type and provider.
365
+
366
+ Parameters
367
+ ----------
368
+ auth_type : ToolAuth
369
+ Authentication type (only OBO is supported).
370
+ provider_type : str, optional
371
+ The specific provider to use (e.g., 'google'). Required if multiple
372
+ identities are available.
373
+
374
+ Returns
375
+ -------
376
+ str
377
+ The retrieved OAuth access token.
378
+
379
+ Raises
380
+ ------
381
+ ValueError
382
+ If the auth type is unsupported or if a suitable identity cannot be found.
383
+ """
216
384
  if auth_type != ToolAuth.OBO:
217
385
  raise ValueError(
218
- f"Unsupported auth type: {auth_type}. Only {ToolAuth.OBO} is supported."
386
+ f"Unsupported auth type: {auth_type}. Only OBO (on-behalf-of) is supported."
219
387
  )
220
388
 
221
389
  identity = self._get_identity(provider_type)
222
- token_data = await self.oauth_client.refresh_access_token(
223
- identity_id=identity.provider_identity_id
224
- )
390
+ token_data = await self._retriever.refresh_access_token(identity)
225
391
  return token_data.access_token
226
-
227
- def _create_oauth_client(self) -> AsyncOAuthComponent:
228
- """Create either DataRobot or Authlib OAuth client based on
229
- authorization context.
230
-
231
- Note: at the moment, only DataRobot OAuth client is supported.
232
- """
233
- logger.debug("Using DataRobot OAuth client")
234
- return DatarobotAsyncOAuthClient()
@@ -11,13 +11,22 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
+ from collections.abc import AsyncGenerator
15
+ from typing import Any
16
+
14
17
  from datarobot.core.config import DataRobotAppFrameworkBaseSettings
15
18
  from nat.authentication.api_key.api_key_auth_provider import APIKeyAuthProvider
16
19
  from nat.authentication.api_key.api_key_auth_provider_config import APIKeyAuthProviderConfig
20
+ from nat.authentication.interfaces import AuthProviderBase
17
21
  from nat.builder.builder import Builder
18
22
  from nat.cli.register_workflow import register_auth_provider
23
+ from nat.data_models.authentication import AuthProviderBaseConfig
24
+ from nat.data_models.authentication import AuthResult
25
+ from nat.data_models.authentication import HeaderCred
19
26
  from pydantic import Field
20
27
 
28
+ from datarobot_genai.core.mcp.common import MCPConfig
29
+
21
30
 
22
31
  class Config(DataRobotAppFrameworkBaseSettings):
23
32
  """
@@ -49,5 +58,53 @@ class DataRobotAPIKeyAuthProviderConfig(APIKeyAuthProviderConfig, name="datarobo
49
58
  @register_auth_provider(config_type=DataRobotAPIKeyAuthProviderConfig)
50
59
  async def datarobot_api_key_client(
51
60
  config: DataRobotAPIKeyAuthProviderConfig, builder: Builder
52
- ) -> APIKeyAuthProviderConfig:
61
+ ) -> AsyncGenerator[APIKeyAuthProvider]:
53
62
  yield APIKeyAuthProvider(config=config)
63
+
64
+
65
+ mcp_config = MCPConfig().server_config
66
+
67
+
68
+ class DataRobotMCPAuthProviderConfig(AuthProviderBaseConfig, name="datarobot_mcp_auth"): # type: ignore[call-arg]
69
+ headers: dict[str, str] | None = Field(
70
+ description=("Headers to be used for authentication. "),
71
+ default=mcp_config["headers"] if mcp_config else None,
72
+ )
73
+ default_user_id: str | None = Field(default="default-user", description="Default user ID")
74
+ allow_default_user_id_for_tool_calls: bool = Field(
75
+ default=True, description="Allow default user ID for tool calls"
76
+ )
77
+
78
+
79
+ class DataRobotMCPAuthProvider(AuthProviderBase[DataRobotMCPAuthProviderConfig]):
80
+ def __init__(
81
+ self, config: DataRobotMCPAuthProviderConfig, config_name: str | None = None
82
+ ) -> None:
83
+ assert isinstance(config, DataRobotMCPAuthProviderConfig), (
84
+ "Config is not DataRobotMCPAuthProviderConfig"
85
+ )
86
+ super().__init__(config)
87
+
88
+ async def authenticate(self, user_id: str | None = None, **kwargs: Any) -> AuthResult | None:
89
+ """
90
+ Authenticate the user using the API key credentials.
91
+
92
+ Args:
93
+ user_id (str): The user ID to authenticate.
94
+
95
+ Returns
96
+ -------
97
+ AuthenticatedContext: The authenticated context containing headers
98
+ """
99
+ return AuthResult(
100
+ credentials=[
101
+ HeaderCred(name=name, value=value) for name, value in self.config.headers.items()
102
+ ]
103
+ )
104
+
105
+
106
+ @register_auth_provider(config_type=DataRobotMCPAuthProviderConfig)
107
+ async def datarobot_mcp_auth_provider(
108
+ config: DataRobotMCPAuthProviderConfig, builder: Builder
109
+ ) -> AsyncGenerator[DataRobotMCPAuthProvider]:
110
+ yield DataRobotMCPAuthProvider(config=config)
@@ -13,11 +13,15 @@
13
13
  # limitations under the License.
14
14
 
15
15
  import logging
16
+ from datetime import timedelta
16
17
  from typing import Literal
17
18
 
19
+ import httpx
20
+ from nat.authentication.interfaces import AuthProviderBase
18
21
  from nat.builder.builder import Builder
19
22
  from nat.cli.register_workflow import register_function_group
20
23
  from nat.data_models.component_ref import AuthenticationRef
24
+ from nat.plugins.mcp.client_base import AuthAdapter
21
25
  from nat.plugins.mcp.client_base import MCPSSEClient
22
26
  from nat.plugins.mcp.client_base import MCPStdioClient
23
27
  from nat.plugins.mcp.client_base import MCPStreamableHTTPClient
@@ -47,7 +51,7 @@ class DataRobotMCPServerConfig(MCPServerConfig):
47
51
  )
48
52
  # Authentication configuration
49
53
  auth_provider: str | AuthenticationRef | None = Field(
50
- default="datarobot_api_key" if config else None,
54
+ default="datarobot_mcp_auth" if config else None,
51
55
  description="Reference to authentication provider",
52
56
  )
53
57
  command: str | None = Field(
@@ -62,6 +66,55 @@ class DataRobotMCPClientConfig(MCPClientConfig, name="datarobot_mcp_client"): #
62
66
  )
63
67
 
64
68
 
69
+ class DataRobotAuthAdapter(AuthAdapter):
70
+ async def _get_auth_headers(
71
+ self, request: httpx.Request | None = None, response: httpx.Response | None = None
72
+ ) -> dict[str, str]:
73
+ """Get authentication headers from the NAT auth provider."""
74
+ try:
75
+ # Use the user_id passed to this AuthAdapter instance
76
+ auth_result = await self.auth_provider.authenticate(
77
+ user_id=self.user_id, response=response
78
+ )
79
+ as_kwargs = auth_result.as_requests_kwargs()
80
+ return as_kwargs["headers"]
81
+ except Exception as e:
82
+ logger.warning("Failed to get auth token: %s", e)
83
+ return {}
84
+
85
+
86
+ class DataRobotMCPStreamableHTTPClient(MCPStreamableHTTPClient):
87
+ def __init__(
88
+ self,
89
+ url: str,
90
+ auth_provider: AuthProviderBase | None = None,
91
+ user_id: str | None = None,
92
+ tool_call_timeout: timedelta = timedelta(seconds=60),
93
+ auth_flow_timeout: timedelta = timedelta(seconds=300),
94
+ reconnect_enabled: bool = True,
95
+ reconnect_max_attempts: int = 2,
96
+ reconnect_initial_backoff: float = 0.5,
97
+ reconnect_max_backoff: float = 50.0,
98
+ ):
99
+ super().__init__(
100
+ url=url,
101
+ auth_provider=auth_provider,
102
+ user_id=user_id,
103
+ tool_call_timeout=tool_call_timeout,
104
+ auth_flow_timeout=auth_flow_timeout,
105
+ reconnect_enabled=reconnect_enabled,
106
+ reconnect_max_attempts=reconnect_max_attempts,
107
+ reconnect_initial_backoff=reconnect_initial_backoff,
108
+ reconnect_max_backoff=reconnect_max_backoff,
109
+ )
110
+ effective_user_id = user_id or (
111
+ auth_provider.config.default_user_id if auth_provider else None
112
+ )
113
+ self._httpx_auth = (
114
+ DataRobotAuthAdapter(auth_provider, effective_user_id) if auth_provider else None
115
+ )
116
+
117
+
65
118
  @register_function_group(config_type=DataRobotMCPClientConfig)
66
119
  async def datarobot_mcp_client_function_group(
67
120
  config: DataRobotMCPClientConfig, _builder: Builder
@@ -108,7 +161,7 @@ async def datarobot_mcp_client_function_group(
108
161
  elif config.server.transport == "streamable-http":
109
162
  # Use default_user_id for the base client
110
163
  base_user_id = auth_provider.config.default_user_id if auth_provider else None
111
- client = MCPStreamableHTTPClient(
164
+ client = DataRobotMCPStreamableHTTPClient(
112
165
  str(config.server.url),
113
166
  auth_provider=auth_provider,
114
167
  user_id=base_user_id,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datarobot-genai
3
- Version: 0.2.6
3
+ Version: 0.2.8
4
4
  Summary: Generic helpers for GenAI
5
5
  Project-URL: Homepage, https://github.com/datarobot-oss/datarobot-genai
6
6
  Author: DataRobot, Inc.
@@ -15,7 +15,7 @@ datarobot_genai/core/cli/agent_kernel.py,sha256=3XX58DQ6XPpWB_tn5m3iGb3XTfhZf5X3
15
15
  datarobot_genai/core/mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
16
  datarobot_genai/core/mcp/common.py,sha256=Y8SjuquUODKEfI7T9X-QuTMKdIlpCWFI1b3xs6tmHFA,7812
17
17
  datarobot_genai/core/utils/__init__.py,sha256=VxtRUz6iwb04eFQQy0zqTNXLAkYpPXcJxVoKV0nOdXk,59
18
- datarobot_genai/core/utils/auth.py,sha256=LpSoHdPD2siskYwG8q4f9cike4VQdgFWJpuJrpiszXU,8674
18
+ datarobot_genai/core/utils/auth.py,sha256=vvPYGmqJBkbx8FT-iOLibA9WafpIwhtwIRV92e3tLYI,14287
19
19
  datarobot_genai/core/utils/urls.py,sha256=tk0t13duDEPcmwz2OnS4vwEdatruiuX8lnxMMhSaJik,2289
20
20
  datarobot_genai/crewai/__init__.py,sha256=MtFnHA3EtmgiK_GjwUGPgQQ6G1MCEzz1SDBwQi9lE8M,706
21
21
  datarobot_genai/crewai/agent.py,sha256=vp8_2LExpeLls7Fpzo0R6ud5I6Ryfu3n3oVTN4Yyi6A,1417
@@ -101,13 +101,13 @@ datarobot_genai/llama_index/base.py,sha256=ovcQQtC-djD_hcLrWdn93jg23AmD6NBEj7xtw
101
101
  datarobot_genai/llama_index/mcp.py,sha256=leXqF1C4zhuYEKFwNEfZHY4dsUuGZk3W7KArY-zxVL8,2645
102
102
  datarobot_genai/nat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
103
103
  datarobot_genai/nat/agent.py,sha256=jDeIS9f-8vGbeLy5gQkSjeuHINx5Fh_4BvXYERsgIIk,10516
104
- datarobot_genai/nat/datarobot_auth_provider.py,sha256=5SBs0xBEZAlBvK-_zOR2cfE_rnn2CoEXeb-Du-rqotc,2117
104
+ datarobot_genai/nat/datarobot_auth_provider.py,sha256=Z4NSsrHxK8hUeiqtK_lryHsUuZC74ziNo_FHbsZgtiM,4230
105
105
  datarobot_genai/nat/datarobot_llm_clients.py,sha256=STzAZ4OF8U-Y_cUTywxmKBGVotwsnbGP6vTojnu6q0g,9921
106
106
  datarobot_genai/nat/datarobot_llm_providers.py,sha256=aDoQcTeGI-odqydPXEX9OGGNFbzAtpqzTvHHEkmJuEQ,4963
107
- datarobot_genai/nat/datarobot_mcp_client.py,sha256=XK3-Tp4hdQmTdI-Zwrl3Xd81qH5RhFTw_UaLTqwnYn4,7531
108
- datarobot_genai-0.2.6.dist-info/METADATA,sha256=2F0MD9IDjdYCmuhCO76dJHljxSk0cJP0rX17TJQoPaQ,6172
109
- datarobot_genai-0.2.6.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
110
- datarobot_genai-0.2.6.dist-info/entry_points.txt,sha256=jEW3WxDZ8XIK9-ISmTyt5DbmBb047rFlzQuhY09rGrM,284
111
- datarobot_genai-0.2.6.dist-info/licenses/AUTHORS,sha256=isJGUXdjq1U7XZ_B_9AH8Qf0u4eX0XyQifJZ_Sxm4sA,80
112
- datarobot_genai-0.2.6.dist-info/licenses/LICENSE,sha256=U2_VkLIktQoa60Nf6Tbt7E4RMlfhFSjWjcJJfVC-YCE,11341
113
- datarobot_genai-0.2.6.dist-info/RECORD,,
107
+ datarobot_genai/nat/datarobot_mcp_client.py,sha256=35FzilxNp4VqwBYI0NsOc91-xZm1C-AzWqrOdDy962A,9612
108
+ datarobot_genai-0.2.8.dist-info/METADATA,sha256=vhjkIDaML9GN6yQ7X4On2edWKGO0KPWkvqDSvYpUShw,6172
109
+ datarobot_genai-0.2.8.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
110
+ datarobot_genai-0.2.8.dist-info/entry_points.txt,sha256=jEW3WxDZ8XIK9-ISmTyt5DbmBb047rFlzQuhY09rGrM,284
111
+ datarobot_genai-0.2.8.dist-info/licenses/AUTHORS,sha256=isJGUXdjq1U7XZ_B_9AH8Qf0u4eX0XyQifJZ_Sxm4sA,80
112
+ datarobot_genai-0.2.8.dist-info/licenses/LICENSE,sha256=U2_VkLIktQoa60Nf6Tbt7E4RMlfhFSjWjcJJfVC-YCE,11341
113
+ datarobot_genai-0.2.8.dist-info/RECORD,,