datarobot-genai 0.1.59__tar.gz → 0.1.64__tar.gz

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.
Files changed (105) hide show
  1. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/PKG-INFO +1 -1
  2. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/pyproject.toml +1 -1
  3. datarobot_genai-0.1.64/src/datarobot_genai/core/mcp/common.py +161 -0
  4. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/utils/auth.py +64 -0
  5. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/crewai/base.py +0 -2
  6. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/crewai/mcp.py +2 -9
  7. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/auth.py +28 -25
  8. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/clients.py +67 -3
  9. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/config.py +0 -8
  10. datarobot_genai-0.1.64/src/datarobot_genai/drmcp/core/dynamic_prompts/controllers.py +85 -0
  11. datarobot_genai-0.1.64/src/datarobot_genai/drmcp/core/dynamic_prompts/dr_lib.py +128 -0
  12. datarobot_genai-0.1.64/src/datarobot_genai/drmcp/core/dynamic_prompts/register.py +206 -0
  13. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/mcp_instance.py +10 -0
  14. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/routes.py +112 -28
  15. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/langgraph/agent.py +3 -6
  16. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/langgraph/mcp.py +1 -9
  17. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/llama_index/base.py +0 -2
  18. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/llama_index/mcp.py +1 -7
  19. datarobot_genai-0.1.64/src/datarobot_genai/nat/agent.py +258 -0
  20. datarobot_genai-0.1.59/src/datarobot_genai/core/mcp/common.py +0 -109
  21. datarobot_genai-0.1.59/src/datarobot_genai/drmcp/core/dynamic_prompts/dr_lib.py +0 -91
  22. datarobot_genai-0.1.59/src/datarobot_genai/drmcp/core/dynamic_prompts/register.py +0 -150
  23. datarobot_genai-0.1.59/src/datarobot_genai/nat/agent.py +0 -137
  24. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/.gitignore +0 -0
  25. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/AUTHORS +0 -0
  26. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/LICENSE +0 -0
  27. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/README.md +0 -0
  28. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/__init__.py +0 -0
  29. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/__init__.py +0 -0
  30. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/agents/__init__.py +0 -0
  31. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/agents/base.py +0 -0
  32. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/chat/__init__.py +0 -0
  33. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/chat/auth.py +0 -0
  34. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/chat/client.py +0 -0
  35. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/chat/responses.py +0 -0
  36. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/cli/__init__.py +0 -0
  37. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/cli/agent_environment.py +0 -0
  38. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/cli/agent_kernel.py +0 -0
  39. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/custom_model.py +0 -0
  40. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/mcp/__init__.py +0 -0
  41. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/telemetry_agent.py +0 -0
  42. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/utils/__init__.py +0 -0
  43. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/core/utils/urls.py +0 -0
  44. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/crewai/__init__.py +0 -0
  45. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/crewai/agent.py +0 -0
  46. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/crewai/events.py +0 -0
  47. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/__init__.py +0 -0
  48. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/__init__.py +0 -0
  49. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/config_utils.py +0 -0
  50. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/constants.py +0 -0
  51. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/credentials.py +0 -0
  52. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dr_mcp_server.py +0 -0
  53. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dr_mcp_server_logo.py +0 -0
  54. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_prompts/__init__.py +0 -0
  55. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_prompts/utils.py +0 -0
  56. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/__init__.py +0 -0
  57. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/__init__.py +0 -0
  58. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/__init__.py +0 -0
  59. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/base.py +0 -0
  60. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/default.py +0 -0
  61. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/drum.py +0 -0
  62. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/config.py +0 -0
  63. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/controllers.py +0 -0
  64. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/metadata.py +0 -0
  65. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/register.py +0 -0
  66. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/schemas/drum_agentic_fallback_schema.json +0 -0
  67. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/deployment/schemas/drum_prediction_fallback_schema.json +0 -0
  68. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/register.py +0 -0
  69. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/dynamic_tools/schema.py +0 -0
  70. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/exceptions.py +0 -0
  71. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/logging.py +0 -0
  72. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/mcp_server_tools.py +0 -0
  73. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/memory_management/__init__.py +0 -0
  74. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/memory_management/manager.py +0 -0
  75. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/memory_management/memory_tools.py +0 -0
  76. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/routes_utils.py +0 -0
  77. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/server_life_cycle.py +0 -0
  78. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/telemetry.py +0 -0
  79. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/tool_filter.py +0 -0
  80. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/core/utils.py +0 -0
  81. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/server.py +0 -0
  82. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/__init__.py +0 -0
  83. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/integration_mcp_server.py +0 -0
  84. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/mcp_utils_ete.py +0 -0
  85. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/mcp_utils_integration.py +0 -0
  86. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/openai_llm_mcp_client.py +0 -0
  87. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/tool_base_ete.py +0 -0
  88. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/test_utils/utils.py +0 -0
  89. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/__init__.py +0 -0
  90. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/__init__.py +0 -0
  91. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/data.py +0 -0
  92. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/deployment.py +0 -0
  93. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/deployment_info.py +0 -0
  94. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/model.py +0 -0
  95. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/predict.py +0 -0
  96. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/predict_realtime.py +0 -0
  97. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/project.py +0 -0
  98. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/drmcp/tools/predictive/training.py +0 -0
  99. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/langgraph/__init__.py +0 -0
  100. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/llama_index/__init__.py +0 -0
  101. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/llama_index/agent.py +0 -0
  102. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/nat/__init__.py +0 -0
  103. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/nat/datarobot_llm_clients.py +0 -0
  104. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/nat/datarobot_llm_providers.py +0 -0
  105. {datarobot_genai-0.1.59 → datarobot_genai-0.1.64}/src/datarobot_genai/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datarobot-genai
3
- Version: 0.1.59
3
+ Version: 0.1.64
4
4
  Summary: Generic helpers for GenAI
5
5
  Project-URL: Homepage, https://github.com/datarobot-oss/datarobot-genai
6
6
  Author: DataRobot, Inc.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "datarobot-genai"
7
- version = "0.1.59"
7
+ version = "0.1.64"
8
8
  description = "Generic helpers for GenAI"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10, <3.13"
@@ -0,0 +1,161 @@
1
+ # Copyright 2025 DataRobot, Inc. and its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import re
17
+ from typing import Any
18
+ from typing import Literal
19
+
20
+ from datarobot.core.config import DataRobotAppFrameworkBaseSettings
21
+ from pydantic import field_validator
22
+
23
+ from datarobot_genai.core.utils.auth import AuthContextHeaderHandler
24
+
25
+
26
+ class MCPConfig(DataRobotAppFrameworkBaseSettings):
27
+ """Configuration for MCP server connection.
28
+
29
+ Derived values are exposed as properties rather than stored, avoiding
30
+ Pydantic field validation/serialization concerns for internal helpers.
31
+ """
32
+
33
+ external_mcp_url: str | None = None
34
+ external_mcp_headers: str | None = None
35
+ external_mcp_transport: Literal["sse", "streamable-http"] = "streamable-http"
36
+ mcp_deployment_id: str | None = None
37
+ datarobot_endpoint: str | None = None
38
+ datarobot_api_token: str | None = None
39
+ authorization_context: dict[str, Any] | None = None
40
+
41
+ _auth_context_handler: AuthContextHeaderHandler | None = None
42
+ _server_config: dict[str, Any] | None = None
43
+
44
+ @field_validator("external_mcp_headers", mode="before")
45
+ @classmethod
46
+ def validate_external_mcp_headers(cls, value: str | None) -> str | None:
47
+ if value is None:
48
+ return None
49
+
50
+ if not isinstance(value, str):
51
+ msg = "external_mcp_headers must be a JSON string"
52
+ raise TypeError(msg)
53
+
54
+ candidate = value.strip()
55
+
56
+ try:
57
+ json.loads(candidate)
58
+ except json.JSONDecodeError as exc:
59
+ msg = "external_mcp_headers must be valid JSON"
60
+ raise ValueError(msg) from exc
61
+
62
+ return candidate
63
+
64
+ @field_validator("mcp_deployment_id", mode="before")
65
+ @classmethod
66
+ def validate_mcp_deployment_id(cls, value: str | None) -> str | None:
67
+ if value is None:
68
+ return None
69
+
70
+ if not isinstance(value, str):
71
+ msg = "mcp_deployment_id must be a string"
72
+ raise TypeError(msg)
73
+
74
+ candidate = value.strip()
75
+
76
+ if not re.fullmatch(r"[0-9a-fA-F]{24}", candidate):
77
+ msg = "mcp_deployment_id must be a valid 24-character hex ID"
78
+ raise ValueError(msg)
79
+
80
+ return candidate
81
+
82
+ def _authorization_bearer_header(self) -> dict[str, str]:
83
+ """Return Authorization header with Bearer token or empty dict."""
84
+ if not self.datarobot_api_token:
85
+ return {}
86
+ auth = (
87
+ self.datarobot_api_token
88
+ if self.datarobot_api_token.startswith("Bearer ")
89
+ else f"Bearer {self.datarobot_api_token}"
90
+ )
91
+ return {"Authorization": auth}
92
+
93
+ @property
94
+ def auth_context_handler(self) -> AuthContextHeaderHandler:
95
+ if self._auth_context_handler is None:
96
+ self._auth_context_handler = AuthContextHeaderHandler()
97
+ return self._auth_context_handler
98
+
99
+ @property
100
+ def server_config(self) -> dict[str, Any] | None:
101
+ if self._server_config is None:
102
+ self._server_config = self._build_server_config()
103
+ return self._server_config
104
+
105
+ def _authorization_context_header(self) -> dict[str, str]:
106
+ """Return X-DataRobot-Authorization-Context header or empty dict."""
107
+ try:
108
+ return self.auth_context_handler.get_header(self.authorization_context)
109
+ except (LookupError, RuntimeError):
110
+ # Authorization context not available (e.g., in tests)
111
+ return {}
112
+
113
+ def _build_server_config(self) -> dict[str, Any] | None:
114
+ """
115
+ Get MCP server configuration.
116
+
117
+ Returns
118
+ -------
119
+ Server configuration dict with url, transport, and optional headers,
120
+ or None if not configured.
121
+ """
122
+ if self.external_mcp_url:
123
+ # External MCP URL - no authentication needed
124
+ if self.external_mcp_headers:
125
+ headers = json.loads(self.external_mcp_headers)
126
+ else:
127
+ headers = {}
128
+
129
+ config = {
130
+ "url": self.external_mcp_url.rstrip("/"),
131
+ "transport": self.external_mcp_transport,
132
+ "headers": headers,
133
+ }
134
+ return config
135
+ elif self.mcp_deployment_id:
136
+ # DataRobot deployment ID - requires authentication
137
+ if self.datarobot_endpoint is None:
138
+ raise ValueError(
139
+ "When using a DataRobot hosted MCP deployment, datarobot_endpoint must be set."
140
+ )
141
+ if self.datarobot_api_token is None:
142
+ raise ValueError(
143
+ "When using a DataRobot hosted MCP deployment, datarobot_api_token must be set."
144
+ )
145
+ base_url = self.datarobot_endpoint.rstrip("/")
146
+ if not base_url.endswith("/api/v2"):
147
+ base_url = base_url + "/api/v2"
148
+ url = f"{base_url}/deployments/{self.mcp_deployment_id}/directAccess/mcp"
149
+
150
+ headers = {
151
+ **self._authorization_bearer_header(),
152
+ **self._authorization_context_header(),
153
+ }
154
+
155
+ return {
156
+ "url": url,
157
+ "transport": "streamable-http",
158
+ "headers": headers,
159
+ }
160
+
161
+ return None
@@ -16,9 +16,14 @@ import warnings
16
16
  from typing import Any
17
17
 
18
18
  import jwt
19
+ from datarobot.auth.datarobot.oauth import AsyncOAuth as DatarobotAsyncOAuthClient
20
+ from datarobot.auth.identity import Identity
21
+ from datarobot.auth.oauth import AsyncOAuthComponent
19
22
  from datarobot.auth.session import AuthCtx
20
23
  from datarobot.core.config import DataRobotAppFrameworkBaseSettings
24
+ from datarobot.models.genai.agent.auth import ToolAuth
21
25
  from datarobot.models.genai.agent.auth import get_authorization_context
26
+ from pydantic import BaseModel
22
27
 
23
28
  logger = logging.getLogger(__name__)
24
29
 
@@ -27,6 +32,13 @@ class AuthContextConfig(DataRobotAppFrameworkBaseSettings):
27
32
  session_secret_key: str = ""
28
33
 
29
34
 
35
+ class DRAppCtx(BaseModel):
36
+ """DataRobot application context from authorization metadata."""
37
+
38
+ email: str | None = None
39
+ api_key: str | None = None
40
+
41
+
30
42
  class AuthContextHeaderHandler:
31
43
  """Manages encoding and decoding of authorization context into JWT tokens.
32
44
 
@@ -146,6 +158,7 @@ class AuthContextHeaderHandler:
146
158
 
147
159
  auth_ctx_dict = self.decode(token)
148
160
  if not auth_ctx_dict:
161
+ logger.debug("Failed to decode auth context from token")
149
162
  return None
150
163
 
151
164
  try:
@@ -153,3 +166,54 @@ class AuthContextHeaderHandler:
153
166
  except Exception as e:
154
167
  logger.error(f"Failed to create AuthCtx from decoded token: {e}", exc_info=True)
155
168
  return None
169
+
170
+
171
+ class AsyncOAuthTokenProvider:
172
+ """Manages OAuth access tokens using generic OAuth client."""
173
+
174
+ def __init__(self, auth_ctx: AuthCtx) -> None:
175
+ self.auth_ctx = auth_ctx
176
+ self.oauth_client = self._create_oauth_client()
177
+
178
+ def _get_identity(self, provider_type: str | None) -> Identity:
179
+ """Retrieve the appropriate identity from the authentication context."""
180
+ identities = [x for x in self.auth_ctx.identities if x.provider_identity_id is not None]
181
+
182
+ if not identities:
183
+ raise ValueError("No identities found in authorization context.")
184
+
185
+ if provider_type is None:
186
+ if len(identities) > 1:
187
+ raise ValueError(
188
+ "Multiple identities found. Please specify 'provider_type' parameter."
189
+ )
190
+ return identities[0]
191
+
192
+ identity = next((id for id in identities if id.provider_type == provider_type), None)
193
+
194
+ if identity is None:
195
+ raise ValueError(f"No identity found for provider '{provider_type}'.")
196
+
197
+ return identity
198
+
199
+ async def get_token(self, auth_type: ToolAuth, provider_type: str | None = None) -> str:
200
+ """Get OAuth access token using the specified method."""
201
+ if auth_type != ToolAuth.OBO:
202
+ raise ValueError(
203
+ f"Unsupported auth type: {auth_type}. Only {ToolAuth.OBO} is supported."
204
+ )
205
+
206
+ identity = self._get_identity(provider_type)
207
+ token_data = await self.oauth_client.refresh_access_token(
208
+ identity_id=identity.provider_identity_id
209
+ )
210
+ return token_data.access_token
211
+
212
+ def _create_oauth_client(self) -> AsyncOAuthComponent:
213
+ """Create either DataRobot or Authlib OAuth client based on
214
+ authorization context.
215
+
216
+ Note: at the moment, only DataRobot OAuth client is supported.
217
+ """
218
+ logger.debug("Using DataRobot OAuth client")
219
+ return DatarobotAsyncOAuthClient()
@@ -92,8 +92,6 @@ class CrewAIAgent(BaseAgent[BaseTool], abc.ABC):
92
92
 
93
93
  # Use MCP context manager to handle connection lifecycle
94
94
  with mcp_tools_context(
95
- api_base=self.api_base,
96
- api_key=self.api_key,
97
95
  authorization_context=self._authorization_context,
98
96
  ) as mcp_tools:
99
97
  # Set MCP tools for all agents if MCP is not configured this is effectively a no-op
@@ -29,15 +29,10 @@ from datarobot_genai.core.mcp.common import MCPConfig
29
29
 
30
30
  @contextmanager
31
31
  def mcp_tools_context(
32
- api_base: str | None = None,
33
- api_key: str | None = None,
34
32
  authorization_context: dict[str, Any] | None = None,
35
33
  ) -> Generator[list[Any], None, None]:
36
34
  """Context manager for MCP tools that handles connection lifecycle."""
37
- config = MCPConfig(
38
- api_base=api_base, api_key=api_key, authorization_context=authorization_context
39
- )
40
-
35
+ config = MCPConfig(authorization_context=authorization_context)
41
36
  # If no MCP server configured, return empty tools list
42
37
  if not config.server_config:
43
38
  print("No MCP server configured, using empty tools list", flush=True)
@@ -47,10 +42,8 @@ def mcp_tools_context(
47
42
  print(f"Connecting to MCP server: {config.server_config['url']}", flush=True)
48
43
 
49
44
  # Use MCPServerAdapter as context manager with the server config
50
- adapter_setting = config.server_config.copy()
51
- adapter_setting["transport"] = "streamable-http"
52
45
  try:
53
- with MCPServerAdapter(adapter_setting) as tools:
46
+ with MCPServerAdapter(config.server_config) as tools:
54
47
  print(
55
48
  f"Successfully connected to MCP server, got {len(tools)} tools",
56
49
  flush=True,
@@ -18,7 +18,6 @@ import logging
18
18
  from typing import Any
19
19
 
20
20
  from datarobot.auth.session import AuthCtx
21
- from datarobot.models.genai.agent.auth import OAuthAccessTokenProvider
22
21
  from datarobot.models.genai.agent.auth import ToolAuth
23
22
  from fastmcp.server.dependencies import get_context
24
23
  from fastmcp.server.dependencies import get_http_headers
@@ -27,12 +26,15 @@ from fastmcp.server.middleware import Middleware
27
26
  from fastmcp.server.middleware import MiddlewareContext
28
27
  from fastmcp.tools.tool import ToolResult
29
28
 
29
+ from datarobot_genai.core.utils.auth import AsyncOAuthTokenProvider
30
30
  from datarobot_genai.core.utils.auth import AuthContextHeaderHandler
31
- from datarobot_genai.drmcp import get_config
32
31
 
33
32
  logger = logging.getLogger(__name__)
34
33
 
35
34
 
35
+ AUTH_CTX_KEY = "authorization_context"
36
+
37
+
36
38
  class OAuthMiddleWare(Middleware):
37
39
  """Middleware that parses `x-datarobot-authorization-context` for tool calls.
38
40
 
@@ -45,16 +47,8 @@ class OAuthMiddleWare(Middleware):
45
47
  Handler for encoding/decoding JWT tokens containing auth context.
46
48
  """
47
49
 
48
- def __init__(self, secret_key: str | None = None) -> None:
49
- """Initialize the middleware with authentication handler.
50
-
51
- Parameters
52
- ----------
53
- secret_key : Optional[str]
54
- Secret key for JWT validation. If None, uses the value from config.
55
- """
56
- secret_key = secret_key or get_config().session_secret_key
57
- self.auth_handler = AuthContextHeaderHandler(secret_key)
50
+ def __init__(self, auth_handler: AuthContextHeaderHandler | None = None) -> None:
51
+ self.auth_handler = auth_handler or AuthContextHeaderHandler()
58
52
 
59
53
  async def on_call_tool(
60
54
  self, context: MiddlewareContext, call_next: CallNext[Any, ToolResult]
@@ -74,9 +68,12 @@ class OAuthMiddleWare(Middleware):
74
68
  The result from the tool execution.
75
69
  """
76
70
  auth_context = self._extract_auth_context()
71
+ if not auth_context:
72
+ logger.debug("No valid authorization context extracted from request headers.")
77
73
 
78
74
  if context.fastmcp_context is not None:
79
- context.fastmcp_context.auth_context = auth_context
75
+ context.fastmcp_context.set_state(AUTH_CTX_KEY, auth_context)
76
+ logger.debug("Authorization context attached to state.")
80
77
 
81
78
  return await call_next(context)
82
79
 
@@ -99,8 +96,8 @@ class OAuthMiddleWare(Middleware):
99
96
  return None
100
97
 
101
98
 
102
- async def get_auth_context() -> AuthCtx:
103
- """Retrieve the AuthCtx from the current request context, if available.
99
+ async def must_get_auth_context() -> AuthCtx:
100
+ """Retrieve the AuthCtx from the current request context or raise error.
104
101
 
105
102
  Raises
106
103
  ------
@@ -113,14 +110,15 @@ async def get_auth_context() -> AuthCtx:
113
110
  The authorization context associated with the current request.
114
111
  """
115
112
  context = get_context()
116
- auth_ctx = getattr(context, "auth_context", None)
113
+
114
+ auth_ctx = context.get_state(AUTH_CTX_KEY)
117
115
  if not auth_ctx:
118
- raise RuntimeError("No authorization context found.")
116
+ raise RuntimeError("Could not retrieve authorization context from FastMCP context state.")
119
117
 
120
118
  return auth_ctx
121
119
 
122
120
 
123
- async def get_access_token(provider: str | None = None) -> str:
121
+ async def get_access_token(provider_type: str | None = None) -> str:
124
122
  """Retrieve access token from the DataRobot OAuth Provider Service.
125
123
 
126
124
  OAuth access tokens can be retrieved only for providers where the user completed
@@ -132,7 +130,7 @@ async def get_access_token(provider: str | None = None) -> str:
132
130
 
133
131
  Parameters
134
132
  ----------
135
- provider : str, optional
133
+ provider_type : str, optional
136
134
  The name of the OAuth provider. It should match the name of the provider configured
137
135
  during provider setup. If no value is provided and only one OAuth provider exists, that
138
136
  provider will be used. If multiple providers exist and none is specified, an error will be
@@ -142,12 +140,18 @@ async def get_access_token(provider: str | None = None) -> str:
142
140
  -------
143
141
  The oauth access token.
144
142
  """
145
- token_provider = OAuthAccessTokenProvider(await get_auth_context())
146
- access_token = token_provider.get_token(ToolAuth.OBO, provider)
147
- return access_token
143
+ auth_ctx = await must_get_auth_context()
144
+ logger.debug("Retrieved authorization context")
145
+
146
+ oauth_token_provider = AsyncOAuthTokenProvider(auth_ctx)
147
+ oauth_access_token = await oauth_token_provider.get_token(
148
+ auth_type=ToolAuth.OBO,
149
+ provider_type=provider_type,
150
+ )
151
+ return oauth_access_token
148
152
 
149
153
 
150
- def initialize_oauth_middleware(mcp: Any, secret_key: str | None = None) -> None:
154
+ def initialize_oauth_middleware(mcp: Any) -> None:
151
155
  """Initialize and register OAuth middleware with the MCP server.
152
156
 
153
157
  Parameters
@@ -157,6 +161,5 @@ def initialize_oauth_middleware(mcp: Any, secret_key: str | None = None) -> None
157
161
  secret_key : Optional[str]
158
162
  Secret key for JWT validation. If None, uses the value from config.
159
163
  """
160
- middleware = OAuthMiddleWare(secret_key=secret_key)
161
- mcp.add_middleware(middleware)
164
+ mcp.add_middleware(OAuthMiddleWare())
162
165
  logger.info("OAuth middleware registered successfully")
@@ -21,6 +21,9 @@ from datarobot.context import Context as DRContext
21
21
  from datarobot.rest import RESTClientObject
22
22
  from fastmcp.server.dependencies import get_http_headers
23
23
 
24
+ from datarobot_genai.core.utils.auth import AuthContextHeaderHandler
25
+ from datarobot_genai.core.utils.auth import DRAppCtx
26
+
24
27
  from .credentials import get_credentials
25
28
 
26
29
  logger = logging.getLogger(__name__)
@@ -66,19 +69,80 @@ def _extract_token_from_headers(headers: dict[str, str]) -> str | None:
66
69
  return None
67
70
 
68
71
 
72
+ def _extract_token_from_auth_context(headers: dict[str, str]) -> str | None:
73
+ """
74
+ Extract API token from authorization context metadata as a fallback.
75
+
76
+ Args:
77
+ headers: Dictionary of headers (keys should be lowercase)
78
+
79
+ Returns
80
+ -------
81
+ The extracted API key from auth context metadata, or None if not found
82
+ """
83
+ try:
84
+ auth_handler = AuthContextHeaderHandler()
85
+
86
+ auth_ctx = auth_handler.get_context(headers)
87
+ if not auth_ctx or not auth_ctx.metadata:
88
+ return None
89
+
90
+ metadata = auth_ctx.metadata
91
+ if not isinstance(metadata, dict):
92
+ return None
93
+
94
+ dr_ctx: DRAppCtx = DRAppCtx(**metadata.get("dr_ctx", {}))
95
+ if dr_ctx.api_key:
96
+ logger.debug("Extracted token from auth context")
97
+ return dr_ctx.api_key
98
+
99
+ return None
100
+
101
+ except Exception as e:
102
+ logger.debug(f"Failed to get token from auth context: {e}")
103
+ return None
104
+
105
+
106
+ def extract_token_from_headers(headers: dict[str, str]) -> str | None:
107
+ """
108
+ Extract a token from headers with multiple fallback strategies.
109
+
110
+ This function attempts to extract a token in the following order:
111
+ 1. From standard authorization headers (Bearer token, x-datarobot-api-token, etc.)
112
+ 2. From authorization context metadata (dr_ctx.api_key)
113
+
114
+ Args:
115
+ headers: Dictionary of headers (keys should be lowercase)
116
+
117
+ Returns
118
+ -------
119
+ The extracted token string, or None if not found
120
+ """
121
+ if token := _extract_token_from_headers(headers):
122
+ return token
123
+
124
+ if token := _extract_token_from_auth_context(headers):
125
+ return token
126
+
127
+ return None
128
+
129
+
69
130
  def get_sdk_client() -> Any:
70
131
  """
71
132
  Get a DataRobot SDK client, using the user's Bearer token from the request.
72
133
 
73
- This function attempts to extract the Bearer token from the HTTP request headers.
74
- If no token is found, it uses the application credentials.
134
+ This function attempts to extract the Bearer token from the HTTP request headers
135
+ with fallback strategies:
136
+ 1. Standard authorization headers (Bearer token, x-datarobot-api-token, etc.)
137
+ 2. Authorization context metadata (dr_ctx.api_key)
138
+ 3. Application credentials as final fallback
75
139
  """
76
140
  token = None
77
141
 
78
142
  try:
79
143
  headers = get_http_headers()
80
144
  if headers:
81
- token = _extract_token_from_headers(headers)
145
+ token = extract_token_from_headers(headers)
82
146
  if token:
83
147
  logger.debug("Using API token found in HTTP headers")
84
148
  except Exception:
@@ -196,14 +196,6 @@ class MCPServerConfig(BaseSettings):
196
196
  ),
197
197
  description="Enable/disable predictive tools",
198
198
  )
199
- session_secret_key: str | None = Field(
200
- default=None,
201
- validation_alias=AliasChoices(
202
- RUNTIME_PARAM_ENV_VAR_NAME_PREFIX + "SESSION_SECRET_KEY",
203
- "SESSION_SECRET_KEY",
204
- ),
205
- description="Session secret key for the MCP server",
206
- )
207
199
 
208
200
  @field_validator(
209
201
  "otel_attributes",
@@ -0,0 +1,85 @@
1
+ # Copyright 2025 DataRobot, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+
17
+ from fastmcp.prompts.prompt import Prompt
18
+
19
+ from datarobot_genai.drmcp.core.dynamic_prompts.dr_lib import get_datarobot_prompt_template
20
+ from datarobot_genai.drmcp.core.dynamic_prompts.dr_lib import get_datarobot_prompt_template_version
21
+ from datarobot_genai.drmcp.core.dynamic_prompts.register import (
22
+ register_prompt_from_datarobot_prompt_management,
23
+ )
24
+ from datarobot_genai.drmcp.core.exceptions import DynamicPromptRegistrationError
25
+ from datarobot_genai.drmcp.core.mcp_instance import mcp
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ async def register_prompt_from_prompt_template_id_and_version(
31
+ prompt_template_id: str, prompt_template_version_id: str | None
32
+ ) -> Prompt:
33
+ """Register a Prompt for a specific prompt template ID and version.
34
+
35
+ Args:
36
+ prompt_template_id: The ID of the DataRobot prompt template.
37
+ prompt_template_version_id: Optional ID of the DataRobot prompt template version.
38
+ If not provided latest will be used
39
+
40
+ Raises
41
+ ------
42
+ DynamicPromptRegistrationError: If registration fails at any step.
43
+
44
+ Returns
45
+ -------
46
+ The registered Prompt instance.
47
+ """
48
+ prompt_template = get_datarobot_prompt_template(prompt_template_id)
49
+
50
+ if not prompt_template:
51
+ raise DynamicPromptRegistrationError("Registration failed. Could not find prompt template.")
52
+
53
+ if not prompt_template_version_id:
54
+ return await register_prompt_from_datarobot_prompt_management(
55
+ prompt_template=prompt_template
56
+ )
57
+
58
+ prompt_template_version = get_datarobot_prompt_template_version(
59
+ prompt_template_id, prompt_template_version_id
60
+ )
61
+
62
+ if not prompt_template_version:
63
+ raise DynamicPromptRegistrationError(
64
+ "Registration failed. Could not find prompt template version."
65
+ )
66
+
67
+ return await register_prompt_from_datarobot_prompt_management(
68
+ prompt_template=prompt_template, prompt_template_version=prompt_template_version
69
+ )
70
+
71
+
72
+ async def delete_registered_prompt_template(prompt_template_id: str) -> bool:
73
+ """Delete the prompt registered for the prompt template id in the MCP instance."""
74
+ prompt_templates_mappings = await mcp.get_prompt_mapping()
75
+ if prompt_template_id not in prompt_templates_mappings:
76
+ logger.debug(f"No prompt registered for prompt template id {prompt_template_id}")
77
+ return False
78
+
79
+ prompt_template_version_id, prompt_name = prompt_templates_mappings[prompt_template_id]
80
+ await mcp.remove_prompt_mapping(prompt_template_id, prompt_template_version_id)
81
+ logger.info(
82
+ f"Deleted prompt name {prompt_name} for prompt template id {prompt_template_id}, "
83
+ f"version {prompt_template_version_id}"
84
+ )
85
+ return True