datarobot-genai 0.1.75__py3-none-any.whl → 0.2.11__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.
Files changed (32) hide show
  1. datarobot_genai/core/agents/base.py +2 -1
  2. datarobot_genai/core/chat/responses.py +32 -4
  3. datarobot_genai/drmcp/core/config.py +52 -0
  4. datarobot_genai/drmcp/core/dr_mcp_server.py +45 -8
  5. datarobot_genai/drmcp/core/dynamic_prompts/dr_lib.py +22 -80
  6. datarobot_genai/drmcp/core/dynamic_prompts/register.py +4 -5
  7. datarobot_genai/drmcp/core/mcp_instance.py +41 -2
  8. datarobot_genai/drmcp/core/routes.py +4 -1
  9. datarobot_genai/drmcp/core/tool_config.py +95 -0
  10. datarobot_genai/drmcp/test_utils/mcp_utils_ete.py +29 -0
  11. datarobot_genai/drmcp/test_utils/openai_llm_mcp_client.py +6 -1
  12. datarobot_genai/drmcp/tools/clients/__init__.py +14 -0
  13. datarobot_genai/drmcp/tools/clients/atlassian.py +188 -0
  14. datarobot_genai/drmcp/tools/clients/confluence.py +196 -0
  15. datarobot_genai/drmcp/tools/clients/jira.py +147 -0
  16. datarobot_genai/drmcp/tools/clients/s3.py +28 -0
  17. datarobot_genai/drmcp/tools/confluence/__init__.py +14 -0
  18. datarobot_genai/drmcp/tools/confluence/tools.py +81 -0
  19. datarobot_genai/drmcp/tools/jira/__init__.py +14 -0
  20. datarobot_genai/drmcp/tools/jira/tools.py +52 -0
  21. datarobot_genai/drmcp/tools/predictive/predict.py +1 -1
  22. datarobot_genai/drmcp/tools/predictive/predict_realtime.py +1 -1
  23. datarobot_genai/langgraph/agent.py +143 -42
  24. datarobot_genai/nat/agent.py +4 -0
  25. datarobot_genai/nat/datarobot_auth_provider.py +110 -0
  26. datarobot_genai/nat/datarobot_mcp_client.py +234 -0
  27. {datarobot_genai-0.1.75.dist-info → datarobot_genai-0.2.11.dist-info}/METADATA +9 -2
  28. {datarobot_genai-0.1.75.dist-info → datarobot_genai-0.2.11.dist-info}/RECORD +32 -20
  29. {datarobot_genai-0.1.75.dist-info → datarobot_genai-0.2.11.dist-info}/entry_points.txt +2 -0
  30. {datarobot_genai-0.1.75.dist-info → datarobot_genai-0.2.11.dist-info}/WHEEL +0 -0
  31. {datarobot_genai-0.1.75.dist-info → datarobot_genai-0.2.11.dist-info}/licenses/AUTHORS +0 -0
  32. {datarobot_genai-0.1.75.dist-info → datarobot_genai-0.2.11.dist-info}/licenses/LICENSE +0 -0
@@ -95,11 +95,16 @@ class LLMMCPClient:
95
95
  ) -> str:
96
96
  """Call an MCP tool and return the result as a string."""
97
97
  result: CallToolResult = await mcp_session.call_tool(tool_name, parameters)
98
- return (
98
+ content = (
99
99
  result.content[0].text
100
100
  if result.content and isinstance(result.content[0], TextContent)
101
101
  else str(result.content)
102
102
  )
103
+ if result.structuredContent is not None:
104
+ structured_content = json.dumps(result.structuredContent)
105
+ else:
106
+ structured_content = ""
107
+ return f"Content: {content}\nStructured content: {structured_content}"
103
108
 
104
109
  async def _process_tool_calls(
105
110
  self,
@@ -0,0 +1,14 @@
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
+
@@ -0,0 +1,188 @@
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
+ """Atlassian API client utilities for OAuth and cloud ID management."""
16
+
17
+ import logging
18
+ from typing import Any
19
+ from typing import Literal
20
+
21
+ import httpx
22
+ from datarobot.auth.datarobot.exceptions import OAuthServiceClientErr
23
+ from fastmcp.exceptions import ToolError
24
+
25
+ from datarobot_genai.drmcp.core.auth import get_access_token
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # Atlassian Cloud API base URL
30
+ ATLASSIAN_API_BASE = "https://api.atlassian.com"
31
+
32
+ # API endpoint paths
33
+ OAUTH_ACCESSIBLE_RESOURCES_PATH = "/oauth/token/accessible-resources"
34
+
35
+ # Supported Atlassian service types
36
+ AtlassianServiceType = Literal["jira", "confluence"]
37
+
38
+
39
+ async def get_atlassian_access_token() -> str | ToolError:
40
+ """
41
+ Get Atlassian OAuth access token with error handling.
42
+
43
+ Returns
44
+ -------
45
+ Access token string on success, ToolError on failure
46
+
47
+ Example:
48
+ ```python
49
+ token = await get_atlassian_access_token()
50
+ if isinstance(token, ToolError):
51
+ # Handle error
52
+ return token
53
+ # Use token
54
+ ```
55
+ """
56
+ try:
57
+ access_token = await get_access_token("atlassian")
58
+ if not access_token:
59
+ logger.warning("Empty access token received")
60
+ return ToolError("Received empty access token. Please complete the OAuth flow.")
61
+ return access_token
62
+ except OAuthServiceClientErr as e:
63
+ logger.error(f"OAuth client error: {e}", exc_info=True)
64
+ return ToolError(
65
+ "Could not obtain access token for Atlassian. Make sure the OAuth "
66
+ "permission was granted for the application to act on your behalf."
67
+ )
68
+ except Exception as e:
69
+ logger.error(f"Unexpected error obtaining access token: {e}", exc_info=True)
70
+ return ToolError("An unexpected error occurred while obtaining access token for Atlassian.")
71
+
72
+
73
+ def _find_resource_by_service(
74
+ resources: list[dict[str, Any]], service_type: str
75
+ ) -> dict[str, Any] | None:
76
+ """
77
+ Find a resource that matches the specified service type.
78
+
79
+ Args:
80
+ resources: List of accessible resources from Atlassian API
81
+ service_type: Service type to filter by (e.g., "jira", "confluence")
82
+
83
+ Returns
84
+ -------
85
+ Resource dictionary if found, None otherwise
86
+ """
87
+ service_lower = service_type.lower()
88
+ for resource in resources:
89
+ if not resource.get("id"):
90
+ continue
91
+ scopes = resource.get("scopes", [])
92
+ if any(service_lower in scope.lower() for scope in scopes):
93
+ return resource
94
+ return None
95
+
96
+
97
+ def _find_first_resource_with_id(resources: list[dict[str, Any]]) -> dict[str, Any] | None:
98
+ """
99
+ Find the first resource that has an ID.
100
+
101
+ Args:
102
+ resources: List of accessible resources from Atlassian API
103
+
104
+ Returns
105
+ -------
106
+ Resource dictionary if found, None otherwise
107
+ """
108
+ for resource in resources:
109
+ if resource.get("id"):
110
+ return resource
111
+ return None
112
+
113
+
114
+ async def get_atlassian_cloud_id(
115
+ client: httpx.AsyncClient,
116
+ service_type: AtlassianServiceType | None = None,
117
+ ) -> str:
118
+ """
119
+ Get the cloud ID for the authenticated Atlassian instance.
120
+
121
+ According to Atlassian OAuth 2.0 documentation, API calls should use:
122
+ https://api.atlassian.com/ex/{service}/{cloudId}/rest/api/3/...
123
+
124
+ Args:
125
+ client: HTTP client with authentication headers configured
126
+ service_type: Optional service type to filter by (e.g., "jira", "confluence").
127
+ If provided, will prioritize resources matching this service type.
128
+
129
+ Returns
130
+ -------
131
+ Cloud ID string for the Atlassian instance
132
+
133
+ Raises
134
+ ------
135
+ ValueError: If cloud ID cannot be retrieved due to:
136
+ - No accessible resources found
137
+ - No cloud ID found in resources
138
+ - Authentication failure (401)
139
+ - HTTP request failure
140
+
141
+ Example:
142
+ ```python
143
+ client = httpx.AsyncClient(headers={"Authorization": f"Bearer {token}"})
144
+ cloud_id = await get_atlassian_cloud_id(client, service_type="jira")
145
+ ```
146
+ """
147
+ url = f"{ATLASSIAN_API_BASE}{OAUTH_ACCESSIBLE_RESOURCES_PATH}"
148
+
149
+ try:
150
+ response = await client.get(url)
151
+ response.raise_for_status()
152
+ resources = response.json()
153
+
154
+ if not resources:
155
+ raise ValueError(
156
+ "No accessible resources found. Ensure OAuth token has required scopes."
157
+ )
158
+
159
+ # If service_type is specified, try to find matching resource
160
+ if service_type:
161
+ resource = _find_resource_by_service(resources, service_type)
162
+ if resource:
163
+ cloud_id = resource["id"]
164
+ logger.debug(f"Using {service_type} cloud ID: {cloud_id}")
165
+ return cloud_id
166
+ logger.warning(
167
+ f"No {service_type} resource found, falling back to first available resource"
168
+ )
169
+
170
+ # Fallback: use the first resource with an ID
171
+ resource = _find_first_resource_with_id(resources)
172
+ if resource:
173
+ cloud_id = resource["id"]
174
+ logger.debug(f"Using cloud ID (fallback): {cloud_id}")
175
+ return cloud_id
176
+
177
+ raise ValueError("No cloud ID found in accessible resources")
178
+ except httpx.HTTPStatusError as e:
179
+ if e.response.status_code == 401:
180
+ raise ValueError(
181
+ "Authentication failed. Token may be expired. "
182
+ "Complete OAuth flow again: GET /oauth/atlassian/authorize"
183
+ ) from e
184
+ logger.error(f"HTTP error getting cloud ID: {e.response.status_code}")
185
+ raise ValueError(f"Failed to get Atlassian cloud ID: HTTP {e.response.status_code}") from e
186
+ except httpx.RequestError as e:
187
+ logger.error(f"Request error getting cloud ID: {e}")
188
+ raise ValueError("Failed to get Atlassian cloud ID: Network error") from e
@@ -0,0 +1,196 @@
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
+ """Async client for interacting with Confluence Cloud REST API.
16
+
17
+ At the moment of creating this client, official Confluence SDK is not supporting async.
18
+ """
19
+
20
+ import logging
21
+ from http import HTTPStatus
22
+ from typing import Any
23
+
24
+ import httpx
25
+ from pydantic import BaseModel
26
+ from pydantic import Field
27
+
28
+ from .atlassian import ATLASSIAN_API_BASE
29
+ from .atlassian import get_atlassian_cloud_id
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class ConfluencePage(BaseModel):
35
+ """Pydantic model for Confluence page."""
36
+
37
+ page_id: str = Field(..., description="The unique page ID")
38
+ title: str = Field(..., description="Page title")
39
+ space_id: str = Field(..., description="Space ID where the page resides")
40
+ space_key: str | None = Field(None, description="Space key (if available)")
41
+ body: str = Field(..., description="Page content in storage format (HTML-like)")
42
+
43
+ def as_flat_dict(self) -> dict[str, Any]:
44
+ """Return a flat dictionary representation of the page."""
45
+ return {
46
+ "page_id": self.page_id,
47
+ "title": self.title,
48
+ "space_id": self.space_id,
49
+ "space_key": self.space_key,
50
+ "body": self.body,
51
+ }
52
+
53
+
54
+ class ConfluenceClient:
55
+ """
56
+ Client for interacting with Confluence API using OAuth access token.
57
+
58
+ At the moment of creating this client, official Confluence SDK is not supporting async.
59
+ """
60
+
61
+ EXPAND_FIELDS = "body.storage,space"
62
+
63
+ def __init__(self, access_token: str) -> None:
64
+ """
65
+ Initialize Confluence client with access token.
66
+
67
+ Args:
68
+ access_token: OAuth access token for Atlassian API
69
+ """
70
+ self.access_token = access_token
71
+ self._client = httpx.AsyncClient(
72
+ headers={
73
+ "Authorization": f"Bearer {access_token}",
74
+ "Accept": "application/json",
75
+ "Content-Type": "application/json",
76
+ },
77
+ timeout=30.0,
78
+ )
79
+ self._cloud_id: str | None = None
80
+
81
+ async def _get_cloud_id(self) -> str:
82
+ """
83
+ Get the cloud ID for the authenticated Atlassian Confluence instance.
84
+
85
+ According to Atlassian OAuth 2.0 documentation, API calls should use:
86
+ https://api.atlassian.com/ex/confluence/{cloudId}/wiki/rest/api/...
87
+
88
+ Returns
89
+ -------
90
+ Cloud ID string
91
+
92
+ Raises
93
+ ------
94
+ ValueError: If cloud ID cannot be retrieved
95
+ """
96
+ if self._cloud_id:
97
+ return self._cloud_id
98
+
99
+ self._cloud_id = await get_atlassian_cloud_id(self._client, service_type="confluence")
100
+ return self._cloud_id
101
+
102
+ def _parse_response(self, data: dict) -> ConfluencePage:
103
+ """Parse API response into ConfluencePage."""
104
+ body_content = ""
105
+ body = data.get("body", {})
106
+ if isinstance(body, dict):
107
+ storage = body.get("storage", {})
108
+ if isinstance(storage, dict):
109
+ body_content = storage.get("value", "")
110
+
111
+ space = data.get("space", {})
112
+ space_key = space.get("key") if isinstance(space, dict) else None
113
+ space_id = space.get("id", "") if isinstance(space, dict) else data.get("spaceId", "")
114
+
115
+ return ConfluencePage(
116
+ page_id=str(data.get("id", "")),
117
+ title=data.get("title", ""),
118
+ space_id=str(space_id),
119
+ space_key=space_key,
120
+ body=body_content,
121
+ )
122
+
123
+ async def get_page_by_id(self, page_id: str) -> ConfluencePage:
124
+ """
125
+ Get a Confluence page by its ID.
126
+
127
+ Args:
128
+ page_id: The numeric page ID
129
+
130
+ Returns
131
+ -------
132
+ ConfluencePage with page data
133
+
134
+ Raises
135
+ ------
136
+ ValueError: If page is not found
137
+ httpx.HTTPStatusError: If the API request fails
138
+ """
139
+ cloud_id = await self._get_cloud_id()
140
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content/{page_id}"
141
+
142
+ response = await self._client.get(url, params={"expand": self.EXPAND_FIELDS})
143
+
144
+ if response.status_code == HTTPStatus.NOT_FOUND:
145
+ raise ValueError(f"Page with ID '{page_id}' not found")
146
+
147
+ response.raise_for_status()
148
+ return self._parse_response(response.json())
149
+
150
+ async def get_page_by_title(self, title: str, space_key: str) -> ConfluencePage:
151
+ """
152
+ Get a Confluence page by its title within a specific space.
153
+
154
+ Args:
155
+ title: The exact page title
156
+ space_key: The space key where the page resides
157
+
158
+ Returns
159
+ -------
160
+ ConfluencePage with page data
161
+
162
+ Raises
163
+ ------
164
+ ValueError: If the page is not found
165
+ httpx.HTTPStatusError: If the API request fails
166
+ """
167
+ cloud_id = await self._get_cloud_id()
168
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content"
169
+
170
+ response = await self._client.get(
171
+ url,
172
+ params={
173
+ "title": title,
174
+ "spaceKey": space_key,
175
+ "expand": self.EXPAND_FIELDS,
176
+ },
177
+ )
178
+ response.raise_for_status()
179
+
180
+ data = response.json()
181
+ results = data.get("results", [])
182
+
183
+ if not results:
184
+ raise ValueError(f"Page with title '{title}' not found in space '{space_key}'")
185
+
186
+ return self._parse_response(results[0])
187
+
188
+ async def __aenter__(self) -> "ConfluenceClient":
189
+ """Async context manager entry."""
190
+ return self
191
+
192
+ async def __aexit__(
193
+ self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any
194
+ ) -> None:
195
+ """Async context manager exit."""
196
+ await self._client.aclose()
@@ -0,0 +1,147 @@
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
+ from http import HTTPStatus
17
+ from typing import Any
18
+
19
+ import httpx
20
+ from pydantic import BaseModel
21
+ from pydantic import Field
22
+
23
+ from .atlassian import ATLASSIAN_API_BASE
24
+ from .atlassian import get_atlassian_cloud_id
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class _IssuePerson(BaseModel):
30
+ email_address: str = Field(alias="emailAddress")
31
+
32
+
33
+ class _IssueStatus(BaseModel):
34
+ name: str
35
+
36
+
37
+ class _IssueFields(BaseModel):
38
+ summary: str
39
+ status: _IssueStatus
40
+ reporter: _IssuePerson
41
+ assignee: _IssuePerson
42
+ created: str
43
+ updated: str
44
+
45
+
46
+ class Issue(BaseModel):
47
+ id: str
48
+ key: str
49
+ fields: _IssueFields
50
+
51
+ def as_flat_dict(self) -> dict[str, Any]:
52
+ return {
53
+ "id": self.id,
54
+ "key": self.key,
55
+ "summary": self.fields.summary,
56
+ "reporterEmailAddress": self.fields.reporter.email_address,
57
+ "assigneeEmailAddress": self.fields.assignee.email_address,
58
+ "created": self.fields.created,
59
+ "updated": self.fields.updated,
60
+ "status": self.fields.status.name,
61
+ }
62
+
63
+
64
+ class JiraClient:
65
+ """
66
+ Client for interacting with Jira API using OAuth access token.
67
+
68
+ At the moment of creating this client, official Jira SDK is not supporting async.
69
+ """
70
+
71
+ def __init__(self, access_token: str) -> None:
72
+ """
73
+ Initialize Jira client with access token.
74
+
75
+ Args:
76
+ access_token: OAuth access token for Atlassian API
77
+ """
78
+ self.access_token = access_token
79
+ self._client = httpx.AsyncClient(
80
+ headers={
81
+ "Authorization": f"Bearer {access_token}",
82
+ "Accept": "application/json",
83
+ "Content-Type": "application/json",
84
+ },
85
+ timeout=30.0,
86
+ )
87
+ self._cloud_id: str | None = None
88
+
89
+ async def _get_cloud_id(self) -> str:
90
+ """
91
+ Get the cloud ID for the authenticated Atlassian Jira instance.
92
+
93
+ According to Atlassian OAuth 2.0 documentation, API calls should use:
94
+ https://api.atlassian.com/ex/jira/{cloudId}/rest/api/3/...
95
+
96
+ Returns
97
+ -------
98
+ Cloud ID string
99
+
100
+ Raises
101
+ ------
102
+ ValueError: If cloud ID cannot be retrieved
103
+ """
104
+ if self._cloud_id:
105
+ return self._cloud_id
106
+
107
+ self._cloud_id = await get_atlassian_cloud_id(self._client, service_type="jira")
108
+ return self._cloud_id
109
+
110
+ async def get_jira_issue(self, issue_key: str) -> Issue:
111
+ """
112
+ Get a Jira issue by its key.
113
+
114
+ Args:
115
+ issue_key: The key of the Jira issue, e.g., 'PROJ-123'
116
+
117
+ Returns
118
+ -------
119
+ Jira issue
120
+
121
+ Raises
122
+ ------
123
+ httpx.HTTPStatusError: If the API request fails
124
+ """
125
+ cloud_id = await self._get_cloud_id()
126
+ url = f"{ATLASSIAN_API_BASE}/ex/jira/{cloud_id}/rest/api/3/issue/{issue_key}"
127
+
128
+ response = await self._client.get(
129
+ url, params={"fields": "id,key,summary,status,reporter,assignee,created,updated"}
130
+ )
131
+
132
+ if response.status_code == HTTPStatus.NOT_FOUND:
133
+ raise ValueError(f"{issue_key} not found")
134
+
135
+ response.raise_for_status()
136
+ issue = Issue(**response.json())
137
+ return issue
138
+
139
+ async def __aenter__(self) -> "JiraClient":
140
+ """Async context manager entry."""
141
+ return self
142
+
143
+ async def __aexit__(
144
+ self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any
145
+ ) -> None:
146
+ """Async context manager exit."""
147
+ await self._client.aclose()
@@ -0,0 +1,28 @@
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 datarobot_genai.drmcp.core.credentials import get_credentials
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def get_s3_bucket_info() -> dict[str, str]:
23
+ """Get S3 bucket configuration."""
24
+ credentials = get_credentials()
25
+ return {
26
+ "bucket": credentials.aws_predictions_s3_bucket,
27
+ "prefix": credentials.aws_predictions_s3_prefix,
28
+ }
@@ -0,0 +1,14 @@
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
+
@@ -0,0 +1,81 @@
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
+ """Confluence MCP tools for interacting with Confluence Cloud."""
16
+
17
+ import logging
18
+ from typing import Annotated
19
+
20
+ from fastmcp.exceptions import ToolError
21
+ from fastmcp.tools.tool import ToolResult
22
+
23
+ from datarobot_genai.drmcp.core.mcp_instance import dr_mcp_tool
24
+ from datarobot_genai.drmcp.tools.clients.atlassian import get_atlassian_access_token
25
+ from datarobot_genai.drmcp.tools.clients.confluence import ConfluenceClient
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ @dr_mcp_tool(tags={"confluence", "read", "get", "page"})
31
+ async def confluence_get_page(
32
+ *,
33
+ page_id_or_title: Annotated[str, "The ID or the exact title of the Confluence page."],
34
+ space_key: Annotated[
35
+ str | None,
36
+ "Required if identifying the page by title. The space key (e.g., 'PROJ').",
37
+ ] = None,
38
+ ) -> ToolResult | ToolError:
39
+ """Retrieve the content of a specific Confluence page.
40
+
41
+ Use this tool to fetch Confluence pages by their numeric ID or by title.
42
+ Returns page content in HTML storage format.
43
+
44
+ Usage:
45
+ - By ID: page_id_or_title="856391684"
46
+ - By title: page_id_or_title="Meeting Notes", space_key="TEAM"
47
+
48
+ When using a page title, the space_key parameter is required.
49
+ """
50
+ if not page_id_or_title:
51
+ raise ToolError("Argument validation error: 'page_id_or_title' cannot be empty.")
52
+
53
+ access_token = await get_atlassian_access_token()
54
+ if isinstance(access_token, ToolError):
55
+ raise access_token
56
+
57
+ try:
58
+ async with ConfluenceClient(access_token) as client:
59
+ if page_id_or_title.isdigit():
60
+ page_response = await client.get_page_by_id(page_id_or_title)
61
+ else:
62
+ if not space_key:
63
+ raise ToolError(
64
+ "Argument validation error: "
65
+ "'space_key' is required when identifying a page by title."
66
+ )
67
+ page_response = await client.get_page_by_title(page_id_or_title, space_key)
68
+ except ValueError as e:
69
+ logger.error(f"Value error getting Confluence page: {e}")
70
+ raise ToolError(str(e))
71
+ except Exception as e:
72
+ logger.error(f"Unexpected error getting Confluence page: {e}")
73
+ raise ToolError(
74
+ f"An unexpected error occurred while getting Confluence page "
75
+ f"'{page_id_or_title}': {str(e)}"
76
+ )
77
+
78
+ return ToolResult(
79
+ content=f"Successfully retrieved page '{page_response.title}'.",
80
+ structured_content=page_response.as_flat_dict(),
81
+ )