datarobot-genai 0.2.31__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 (125) hide show
  1. datarobot_genai/__init__.py +19 -0
  2. datarobot_genai/core/__init__.py +0 -0
  3. datarobot_genai/core/agents/__init__.py +43 -0
  4. datarobot_genai/core/agents/base.py +195 -0
  5. datarobot_genai/core/chat/__init__.py +19 -0
  6. datarobot_genai/core/chat/auth.py +146 -0
  7. datarobot_genai/core/chat/client.py +178 -0
  8. datarobot_genai/core/chat/responses.py +297 -0
  9. datarobot_genai/core/cli/__init__.py +18 -0
  10. datarobot_genai/core/cli/agent_environment.py +47 -0
  11. datarobot_genai/core/cli/agent_kernel.py +211 -0
  12. datarobot_genai/core/custom_model.py +141 -0
  13. datarobot_genai/core/mcp/__init__.py +0 -0
  14. datarobot_genai/core/mcp/common.py +218 -0
  15. datarobot_genai/core/telemetry_agent.py +126 -0
  16. datarobot_genai/core/utils/__init__.py +3 -0
  17. datarobot_genai/core/utils/auth.py +234 -0
  18. datarobot_genai/core/utils/urls.py +64 -0
  19. datarobot_genai/crewai/__init__.py +24 -0
  20. datarobot_genai/crewai/agent.py +42 -0
  21. datarobot_genai/crewai/base.py +159 -0
  22. datarobot_genai/crewai/events.py +117 -0
  23. datarobot_genai/crewai/mcp.py +59 -0
  24. datarobot_genai/drmcp/__init__.py +78 -0
  25. datarobot_genai/drmcp/core/__init__.py +13 -0
  26. datarobot_genai/drmcp/core/auth.py +165 -0
  27. datarobot_genai/drmcp/core/clients.py +180 -0
  28. datarobot_genai/drmcp/core/config.py +364 -0
  29. datarobot_genai/drmcp/core/config_utils.py +174 -0
  30. datarobot_genai/drmcp/core/constants.py +18 -0
  31. datarobot_genai/drmcp/core/credentials.py +190 -0
  32. datarobot_genai/drmcp/core/dr_mcp_server.py +350 -0
  33. datarobot_genai/drmcp/core/dr_mcp_server_logo.py +136 -0
  34. datarobot_genai/drmcp/core/dynamic_prompts/__init__.py +13 -0
  35. datarobot_genai/drmcp/core/dynamic_prompts/controllers.py +130 -0
  36. datarobot_genai/drmcp/core/dynamic_prompts/dr_lib.py +70 -0
  37. datarobot_genai/drmcp/core/dynamic_prompts/register.py +205 -0
  38. datarobot_genai/drmcp/core/dynamic_prompts/utils.py +33 -0
  39. datarobot_genai/drmcp/core/dynamic_tools/__init__.py +14 -0
  40. datarobot_genai/drmcp/core/dynamic_tools/deployment/__init__.py +0 -0
  41. datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/__init__.py +14 -0
  42. datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/base.py +72 -0
  43. datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/default.py +82 -0
  44. datarobot_genai/drmcp/core/dynamic_tools/deployment/adapters/drum.py +238 -0
  45. datarobot_genai/drmcp/core/dynamic_tools/deployment/config.py +228 -0
  46. datarobot_genai/drmcp/core/dynamic_tools/deployment/controllers.py +63 -0
  47. datarobot_genai/drmcp/core/dynamic_tools/deployment/metadata.py +162 -0
  48. datarobot_genai/drmcp/core/dynamic_tools/deployment/register.py +87 -0
  49. datarobot_genai/drmcp/core/dynamic_tools/deployment/schemas/drum_agentic_fallback_schema.json +36 -0
  50. datarobot_genai/drmcp/core/dynamic_tools/deployment/schemas/drum_prediction_fallback_schema.json +10 -0
  51. datarobot_genai/drmcp/core/dynamic_tools/register.py +254 -0
  52. datarobot_genai/drmcp/core/dynamic_tools/schema.py +532 -0
  53. datarobot_genai/drmcp/core/exceptions.py +25 -0
  54. datarobot_genai/drmcp/core/logging.py +98 -0
  55. datarobot_genai/drmcp/core/mcp_instance.py +515 -0
  56. datarobot_genai/drmcp/core/memory_management/__init__.py +13 -0
  57. datarobot_genai/drmcp/core/memory_management/manager.py +820 -0
  58. datarobot_genai/drmcp/core/memory_management/memory_tools.py +201 -0
  59. datarobot_genai/drmcp/core/routes.py +439 -0
  60. datarobot_genai/drmcp/core/routes_utils.py +30 -0
  61. datarobot_genai/drmcp/core/server_life_cycle.py +107 -0
  62. datarobot_genai/drmcp/core/telemetry.py +424 -0
  63. datarobot_genai/drmcp/core/tool_config.py +111 -0
  64. datarobot_genai/drmcp/core/tool_filter.py +117 -0
  65. datarobot_genai/drmcp/core/utils.py +138 -0
  66. datarobot_genai/drmcp/server.py +19 -0
  67. datarobot_genai/drmcp/test_utils/__init__.py +13 -0
  68. datarobot_genai/drmcp/test_utils/clients/__init__.py +0 -0
  69. datarobot_genai/drmcp/test_utils/clients/anthropic.py +68 -0
  70. datarobot_genai/drmcp/test_utils/clients/base.py +300 -0
  71. datarobot_genai/drmcp/test_utils/clients/dr_gateway.py +58 -0
  72. datarobot_genai/drmcp/test_utils/clients/openai.py +68 -0
  73. datarobot_genai/drmcp/test_utils/elicitation_test_tool.py +89 -0
  74. datarobot_genai/drmcp/test_utils/integration_mcp_server.py +109 -0
  75. datarobot_genai/drmcp/test_utils/mcp_utils_ete.py +133 -0
  76. datarobot_genai/drmcp/test_utils/mcp_utils_integration.py +107 -0
  77. datarobot_genai/drmcp/test_utils/test_interactive.py +205 -0
  78. datarobot_genai/drmcp/test_utils/tool_base_ete.py +220 -0
  79. datarobot_genai/drmcp/test_utils/utils.py +91 -0
  80. datarobot_genai/drmcp/tools/__init__.py +14 -0
  81. datarobot_genai/drmcp/tools/clients/__init__.py +14 -0
  82. datarobot_genai/drmcp/tools/clients/atlassian.py +188 -0
  83. datarobot_genai/drmcp/tools/clients/confluence.py +584 -0
  84. datarobot_genai/drmcp/tools/clients/gdrive.py +832 -0
  85. datarobot_genai/drmcp/tools/clients/jira.py +334 -0
  86. datarobot_genai/drmcp/tools/clients/microsoft_graph.py +479 -0
  87. datarobot_genai/drmcp/tools/clients/s3.py +28 -0
  88. datarobot_genai/drmcp/tools/confluence/__init__.py +14 -0
  89. datarobot_genai/drmcp/tools/confluence/tools.py +321 -0
  90. datarobot_genai/drmcp/tools/gdrive/__init__.py +0 -0
  91. datarobot_genai/drmcp/tools/gdrive/tools.py +347 -0
  92. datarobot_genai/drmcp/tools/jira/__init__.py +14 -0
  93. datarobot_genai/drmcp/tools/jira/tools.py +243 -0
  94. datarobot_genai/drmcp/tools/microsoft_graph/__init__.py +13 -0
  95. datarobot_genai/drmcp/tools/microsoft_graph/tools.py +198 -0
  96. datarobot_genai/drmcp/tools/predictive/__init__.py +27 -0
  97. datarobot_genai/drmcp/tools/predictive/data.py +133 -0
  98. datarobot_genai/drmcp/tools/predictive/deployment.py +91 -0
  99. datarobot_genai/drmcp/tools/predictive/deployment_info.py +392 -0
  100. datarobot_genai/drmcp/tools/predictive/model.py +148 -0
  101. datarobot_genai/drmcp/tools/predictive/predict.py +254 -0
  102. datarobot_genai/drmcp/tools/predictive/predict_realtime.py +307 -0
  103. datarobot_genai/drmcp/tools/predictive/project.py +90 -0
  104. datarobot_genai/drmcp/tools/predictive/training.py +661 -0
  105. datarobot_genai/langgraph/__init__.py +0 -0
  106. datarobot_genai/langgraph/agent.py +341 -0
  107. datarobot_genai/langgraph/mcp.py +73 -0
  108. datarobot_genai/llama_index/__init__.py +16 -0
  109. datarobot_genai/llama_index/agent.py +50 -0
  110. datarobot_genai/llama_index/base.py +299 -0
  111. datarobot_genai/llama_index/mcp.py +79 -0
  112. datarobot_genai/nat/__init__.py +0 -0
  113. datarobot_genai/nat/agent.py +275 -0
  114. datarobot_genai/nat/datarobot_auth_provider.py +110 -0
  115. datarobot_genai/nat/datarobot_llm_clients.py +318 -0
  116. datarobot_genai/nat/datarobot_llm_providers.py +130 -0
  117. datarobot_genai/nat/datarobot_mcp_client.py +266 -0
  118. datarobot_genai/nat/helpers.py +87 -0
  119. datarobot_genai/py.typed +0 -0
  120. datarobot_genai-0.2.31.dist-info/METADATA +145 -0
  121. datarobot_genai-0.2.31.dist-info/RECORD +125 -0
  122. datarobot_genai-0.2.31.dist-info/WHEEL +4 -0
  123. datarobot_genai-0.2.31.dist-info/entry_points.txt +5 -0
  124. datarobot_genai-0.2.31.dist-info/licenses/AUTHORS +2 -0
  125. datarobot_genai-0.2.31.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,584 @@
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
+ # Search expand fields for CQL search - content.space gives us space.key directly
34
+ SEARCH_EXPAND_FIELDS = "content.space"
35
+
36
+
37
+ class ConfluenceError(Exception):
38
+ """Exception for Confluence API errors."""
39
+
40
+ def __init__(self, message: str, status_code: int | None = None) -> None:
41
+ super().__init__(message)
42
+ self.status_code = status_code
43
+
44
+
45
+ class ConfluencePage(BaseModel):
46
+ """Pydantic model for Confluence page."""
47
+
48
+ page_id: str = Field(..., description="The unique page ID")
49
+ title: str = Field(..., description="Page title")
50
+ space_id: str = Field(..., description="Space ID where the page resides")
51
+ space_key: str | None = Field(None, description="Space key (if available)")
52
+ body: str = Field(..., description="Page content in storage format (HTML-like)")
53
+ version: int = Field(..., description="Current version number of the page")
54
+
55
+ def as_flat_dict(self) -> dict[str, Any]:
56
+ """Return a flat dictionary representation of the page."""
57
+ return {
58
+ "page_id": self.page_id,
59
+ "title": self.title,
60
+ "space_id": self.space_id,
61
+ "space_key": self.space_key,
62
+ "body": self.body,
63
+ "version": self.version,
64
+ }
65
+
66
+
67
+ class ConfluenceComment(BaseModel):
68
+ """Pydantic model for Confluence comment."""
69
+
70
+ comment_id: str = Field(..., description="The unique comment ID")
71
+ page_id: str = Field(..., description="The page ID where the comment was added")
72
+ body: str = Field(..., description="Comment content in storage format")
73
+
74
+ def as_flat_dict(self) -> dict[str, Any]:
75
+ """Return a flat dictionary representation of the comment."""
76
+ return {
77
+ "comment_id": self.comment_id,
78
+ "page_id": self.page_id,
79
+ "body": self.body,
80
+ }
81
+
82
+
83
+ class ContentSearchResult(BaseModel):
84
+ """Pydantic model for Confluence search result item."""
85
+
86
+ id: str
87
+ title: str
88
+ type: str
89
+ space_key: str = ""
90
+ space_name: str = ""
91
+ excerpt: str = ""
92
+ last_modified: str | None = None
93
+ url: str = ""
94
+
95
+ def as_flat_dict(self) -> dict[str, Any]:
96
+ """Return a flat dictionary representation of the search result."""
97
+ return {
98
+ "id": self.id,
99
+ "title": self.title,
100
+ "type": self.type,
101
+ "spaceKey": self.space_key,
102
+ "spaceName": self.space_name,
103
+ "excerpt": self.excerpt,
104
+ "lastModified": self.last_modified,
105
+ "url": self.url,
106
+ }
107
+
108
+
109
+ class ConfluenceClient:
110
+ """
111
+ Client for interacting with Confluence API using OAuth access token.
112
+
113
+ At the moment of creating this client, official Confluence SDK is not supporting async.
114
+ """
115
+
116
+ EXPAND_FIELDS = "body.storage,space,version"
117
+
118
+ def __init__(self, access_token: str) -> None:
119
+ """
120
+ Initialize Confluence client with access token.
121
+
122
+ Args:
123
+ access_token: OAuth access token for Atlassian API
124
+ """
125
+ self.access_token = access_token
126
+ self._client = httpx.AsyncClient(
127
+ headers={
128
+ "Authorization": f"Bearer {access_token}",
129
+ "Accept": "application/json",
130
+ "Content-Type": "application/json",
131
+ },
132
+ timeout=30.0,
133
+ )
134
+ self._cloud_id: str | None = None
135
+
136
+ async def _get_cloud_id(self) -> str:
137
+ """
138
+ Get the cloud ID for the authenticated Atlassian Confluence instance.
139
+
140
+ According to Atlassian OAuth 2.0 documentation, API calls should use:
141
+ https://api.atlassian.com/ex/confluence/{cloudId}/wiki/rest/api/...
142
+
143
+ Returns
144
+ -------
145
+ Cloud ID string
146
+
147
+ Raises
148
+ ------
149
+ ValueError: If cloud ID cannot be retrieved
150
+ """
151
+ if self._cloud_id:
152
+ return self._cloud_id
153
+
154
+ self._cloud_id = await get_atlassian_cloud_id(self._client, service_type="confluence")
155
+ return self._cloud_id
156
+
157
+ def _parse_response(self, data: dict) -> ConfluencePage:
158
+ """Parse API response into ConfluencePage."""
159
+ body_content = ""
160
+ body = data.get("body", {})
161
+ if isinstance(body, dict):
162
+ storage = body.get("storage", {})
163
+ if isinstance(storage, dict):
164
+ body_content = storage.get("value", "")
165
+
166
+ space = data.get("space", {})
167
+ space_key = space.get("key") if isinstance(space, dict) else None
168
+ space_id = space.get("id", "") if isinstance(space, dict) else data.get("spaceId", "")
169
+ version_data = data.get("version", {})
170
+ version_number = version_data.get("number", 1) if isinstance(version_data, dict) else 1
171
+
172
+ return ConfluencePage(
173
+ page_id=str(data.get("id", "")),
174
+ title=data.get("title", ""),
175
+ space_id=str(space_id),
176
+ space_key=space_key,
177
+ body=body_content,
178
+ version=version_number,
179
+ )
180
+
181
+ async def get_page_by_id(self, page_id: str) -> ConfluencePage:
182
+ """
183
+ Get a Confluence page by its ID.
184
+
185
+ Args:
186
+ page_id: The numeric page ID
187
+
188
+ Returns
189
+ -------
190
+ ConfluencePage with page data
191
+
192
+ Raises
193
+ ------
194
+ ConfluenceError: If page is not found
195
+ httpx.HTTPStatusError: If the API request fails
196
+ """
197
+ cloud_id = await self._get_cloud_id()
198
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content/{page_id}"
199
+
200
+ response = await self._client.get(url, params={"expand": self.EXPAND_FIELDS})
201
+
202
+ if response.status_code == HTTPStatus.NOT_FOUND:
203
+ raise ConfluenceError(f"Page with ID '{page_id}' not found", status_code=404)
204
+
205
+ response.raise_for_status()
206
+ return self._parse_response(response.json())
207
+
208
+ async def get_page_by_title(self, title: str, space_key: str) -> ConfluencePage:
209
+ """
210
+ Get a Confluence page by its title within a specific space.
211
+
212
+ Args:
213
+ title: The exact page title
214
+ space_key: The space key where the page resides
215
+
216
+ Returns
217
+ -------
218
+ ConfluencePage with page data
219
+
220
+ Raises
221
+ ------
222
+ ConfluenceError: If the page is not found
223
+ httpx.HTTPStatusError: If the API request fails
224
+ """
225
+ cloud_id = await self._get_cloud_id()
226
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content"
227
+
228
+ response = await self._client.get(
229
+ url,
230
+ params={
231
+ "title": title,
232
+ "spaceKey": space_key,
233
+ "expand": self.EXPAND_FIELDS,
234
+ },
235
+ )
236
+ response.raise_for_status()
237
+
238
+ data = response.json()
239
+ results = data.get("results", [])
240
+
241
+ if not results:
242
+ raise ConfluenceError(
243
+ f"Page with title '{title}' not found in space '{space_key}'", status_code=404
244
+ )
245
+
246
+ return self._parse_response(results[0])
247
+
248
+ def _extract_error_message(self, response: httpx.Response) -> str:
249
+ """Extract error message from Confluence API error response."""
250
+ try:
251
+ error_data = response.json()
252
+ # Confluence API returns errors in different formats
253
+ if "message" in error_data:
254
+ return error_data["message"]
255
+ if "errorMessages" in error_data and error_data["errorMessages"]:
256
+ return "; ".join(error_data["errorMessages"])
257
+ if "errors" in error_data:
258
+ errors = error_data["errors"]
259
+ if isinstance(errors, list):
260
+ return "; ".join(str(e) for e in errors)
261
+ if isinstance(errors, dict):
262
+ return "; ".join(f"{k}: {v}" for k, v in errors.items())
263
+ except Exception:
264
+ pass
265
+ return response.text or "Unknown error"
266
+
267
+ async def create_page(
268
+ self,
269
+ space_key: str,
270
+ title: str,
271
+ body_content: str,
272
+ parent_id: int | None = None,
273
+ ) -> ConfluencePage:
274
+ """
275
+ Create a new Confluence page in a specified space.
276
+
277
+ Args:
278
+ space_key: The key of the Confluence space where the page should live
279
+ title: The title of the new page
280
+ body_content: The content in Confluence Storage Format (XML) or raw text
281
+ parent_id: Optional ID of the parent page for creating a child page
282
+
283
+ Returns
284
+ -------
285
+ ConfluencePage with the created page data
286
+
287
+ Raises
288
+ ------
289
+ ConfluenceError: If space not found, parent page not found, duplicate title,
290
+ permission denied, or invalid content
291
+ httpx.HTTPStatusError: If the API request fails with unexpected status
292
+ """
293
+ cloud_id = await self._get_cloud_id()
294
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content"
295
+
296
+ payload: dict[str, Any] = {
297
+ "type": "page",
298
+ "title": title,
299
+ "space": {"key": space_key},
300
+ "body": {
301
+ "storage": {
302
+ "value": body_content,
303
+ "representation": "storage",
304
+ }
305
+ },
306
+ }
307
+
308
+ if parent_id is not None:
309
+ payload["ancestors"] = [{"id": parent_id}]
310
+
311
+ response = await self._client.post(url, json=payload)
312
+
313
+ if response.status_code == HTTPStatus.NOT_FOUND:
314
+ error_msg = self._extract_error_message(response)
315
+ if parent_id is not None and "ancestor" in error_msg.lower():
316
+ raise ConfluenceError(
317
+ f"Parent page with ID '{parent_id}' not found", status_code=404
318
+ )
319
+ raise ConfluenceError(
320
+ f"Space '{space_key}' not found or resource unavailable: {error_msg}",
321
+ status_code=404,
322
+ )
323
+
324
+ if response.status_code == HTTPStatus.CONFLICT:
325
+ raise ConfluenceError(
326
+ f"A page with title '{title}' already exists in space '{space_key}'",
327
+ status_code=409,
328
+ )
329
+
330
+ if response.status_code == HTTPStatus.FORBIDDEN:
331
+ raise ConfluenceError(
332
+ f"Permission denied: you don't have access to create pages in space '{space_key}'",
333
+ status_code=403,
334
+ )
335
+
336
+ if response.status_code == HTTPStatus.BAD_REQUEST:
337
+ error_msg = self._extract_error_message(response)
338
+ raise ConfluenceError(f"Invalid request: {error_msg}", status_code=400)
339
+
340
+ if response.status_code == HTTPStatus.TOO_MANY_REQUESTS:
341
+ raise ConfluenceError("Rate limit exceeded. Please try again later.", status_code=429)
342
+
343
+ response.raise_for_status()
344
+
345
+ return self._parse_response(response.json())
346
+
347
+ async def update_page(
348
+ self,
349
+ page_id: str,
350
+ new_body_content: str,
351
+ version_number: int,
352
+ ) -> ConfluencePage:
353
+ """
354
+ Update the content of an existing Confluence page.
355
+
356
+ Args:
357
+ page_id: The ID of the page to update
358
+ new_body_content: The new content in Confluence Storage Format (XML) or raw text
359
+ version_number: The current version number of the page (for optimistic locking).
360
+ The update will increment this by 1.
361
+
362
+ Returns
363
+ -------
364
+ ConfluencePage with the updated page data including the new version number
365
+
366
+ Raises
367
+ ------
368
+ ConfluenceError: If page not found (404), version conflict (409),
369
+ permission denied (403), invalid content (400),
370
+ or rate limited (429)
371
+ httpx.HTTPStatusError: If the API request fails with unexpected status
372
+ """
373
+ cloud_id = await self._get_cloud_id()
374
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content/{page_id}"
375
+
376
+ try:
377
+ current_page = await self.get_page_by_id(page_id)
378
+ title_to_use = current_page.title
379
+ except ConfluenceError as e:
380
+ if e.status_code == 404:
381
+ raise ConfluenceError(
382
+ f"Page with ID '{page_id}' not found: cannot fetch existing title",
383
+ status_code=404,
384
+ )
385
+ raise
386
+
387
+ payload: dict[str, Any] = {
388
+ "type": "page",
389
+ "title": title_to_use,
390
+ "body": {
391
+ "storage": {
392
+ "value": new_body_content,
393
+ "representation": "storage",
394
+ }
395
+ },
396
+ "version": {
397
+ "number": version_number + 1,
398
+ },
399
+ }
400
+
401
+ response = await self._client.put(url, json=payload)
402
+
403
+ if response.status_code == HTTPStatus.NOT_FOUND:
404
+ error_msg = self._extract_error_message(response)
405
+ raise ConfluenceError(
406
+ f"Page with ID '{page_id}' not found: {error_msg}",
407
+ status_code=404,
408
+ )
409
+
410
+ if response.status_code == HTTPStatus.CONFLICT:
411
+ error_msg = self._extract_error_message(response)
412
+ raise ConfluenceError(
413
+ f"Version conflict: the page has been modified since version {version_number}. "
414
+ f"Please fetch the latest version and retry. Details: {error_msg}",
415
+ status_code=409,
416
+ )
417
+
418
+ if response.status_code == HTTPStatus.FORBIDDEN:
419
+ raise ConfluenceError(
420
+ f"Permission denied: you don't have access to update page '{page_id}'",
421
+ status_code=403,
422
+ )
423
+
424
+ if response.status_code == HTTPStatus.BAD_REQUEST:
425
+ error_msg = self._extract_error_message(response)
426
+ raise ConfluenceError(f"Invalid request: {error_msg}", status_code=400)
427
+
428
+ if response.status_code == HTTPStatus.TOO_MANY_REQUESTS:
429
+ raise ConfluenceError("Rate limit exceeded. Please try again later.", status_code=429)
430
+
431
+ response.raise_for_status()
432
+ return self._parse_response(response.json())
433
+
434
+ def _parse_comment_response(self, data: dict, page_id: str) -> ConfluenceComment:
435
+ """Parse API response into ConfluenceComment."""
436
+ body_content = ""
437
+ body = data.get("body", {})
438
+ if isinstance(body, dict):
439
+ storage = body.get("storage", {})
440
+ if isinstance(storage, dict):
441
+ body_content = storage.get("value", "")
442
+
443
+ return ConfluenceComment(
444
+ comment_id=str(data.get("id", "")),
445
+ page_id=page_id,
446
+ body=body_content,
447
+ )
448
+
449
+ async def add_comment(self, page_id: str, comment_body: str) -> ConfluenceComment:
450
+ """
451
+ Add a comment to a Confluence page.
452
+
453
+ Args:
454
+ page_id: The numeric page ID where the comment will be added
455
+ comment_body: The text content of the comment
456
+
457
+ Returns
458
+ -------
459
+ ConfluenceComment with the created comment data
460
+
461
+ Raises
462
+ ------
463
+ ConfluenceError: If page not found, permission denied, or invalid content
464
+ httpx.HTTPStatusError: If the API request fails with unexpected status
465
+ """
466
+ cloud_id = await self._get_cloud_id()
467
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/content"
468
+
469
+ payload: dict[str, Any] = {
470
+ "type": "comment",
471
+ "container": {"id": page_id, "type": "page"},
472
+ "body": {
473
+ "storage": {
474
+ "value": comment_body,
475
+ "representation": "storage",
476
+ }
477
+ },
478
+ }
479
+
480
+ response = await self._client.post(url, json=payload)
481
+
482
+ if response.status_code == HTTPStatus.NOT_FOUND:
483
+ error_msg = self._extract_error_message(response)
484
+ raise ConfluenceError(
485
+ f"Page with ID '{page_id}' not found: {error_msg}",
486
+ status_code=404,
487
+ )
488
+
489
+ if response.status_code == HTTPStatus.FORBIDDEN:
490
+ raise ConfluenceError(
491
+ f"Permission denied: you don't have access to add comments to page '{page_id}'",
492
+ status_code=403,
493
+ )
494
+
495
+ if response.status_code == HTTPStatus.BAD_REQUEST:
496
+ error_msg = self._extract_error_message(response)
497
+ raise ConfluenceError(f"Invalid request: {error_msg}", status_code=400)
498
+
499
+ if response.status_code == HTTPStatus.TOO_MANY_REQUESTS:
500
+ raise ConfluenceError("Rate limit exceeded. Please try again later.", status_code=429)
501
+
502
+ response.raise_for_status()
503
+
504
+ return self._parse_comment_response(response.json(), page_id)
505
+
506
+ async def search_confluence_content(
507
+ self, cql_query: str, max_results: int
508
+ ) -> list[ContentSearchResult]:
509
+ """
510
+ Search Confluence content using CQL (Confluence Query Language).
511
+
512
+ Args:
513
+ cql_query: CQL Query
514
+ max_results: Maximum number of results to return
515
+
516
+ Returns
517
+ -------
518
+ List of Confluence content search results
519
+
520
+ Raises
521
+ ------
522
+ ConfluenceError: If the API request fails (400, 403, 429)
523
+ """
524
+ cloud_id = await self._get_cloud_id()
525
+ url = f"{ATLASSIAN_API_BASE}/ex/confluence/{cloud_id}/wiki/rest/api/search"
526
+
527
+ response = await self._client.get(
528
+ url,
529
+ params={
530
+ "cql": cql_query,
531
+ "limit": max_results,
532
+ "expand": SEARCH_EXPAND_FIELDS,
533
+ },
534
+ )
535
+
536
+ if response.status_code == HTTPStatus.BAD_REQUEST:
537
+ error_msg = self._extract_error_message(response)
538
+ raise ConfluenceError(f"Invalid CQL query: {error_msg}", status_code=400)
539
+
540
+ if response.status_code == HTTPStatus.FORBIDDEN:
541
+ raise ConfluenceError(
542
+ "Permission denied: you don't have access to search this content",
543
+ status_code=403,
544
+ )
545
+
546
+ if response.status_code == HTTPStatus.TOO_MANY_REQUESTS:
547
+ raise ConfluenceError("Rate limit exceeded. Please try again later.", status_code=429)
548
+
549
+ response.raise_for_status()
550
+ raw_results = response.json().get("results", [])
551
+ results = [ContentSearchResult(**self._parse_search_item(item)) for item in raw_results]
552
+ return results
553
+
554
+ def _parse_search_item(self, item: dict) -> dict:
555
+ """Parse raw search API response item into model-compatible dict."""
556
+ content = item.get("content", item)
557
+ links = content.get("_links", {})
558
+ base_url = links.get("base", "")
559
+ webui = links.get("webui", "")
560
+ url = f"{base_url}{webui}" if base_url and webui else webui
561
+
562
+ # Get space from content.space (requires expand=content.space)
563
+ content_space = content.get("space", {})
564
+
565
+ return {
566
+ "id": str(content.get("id", "")),
567
+ "title": content.get("title", ""),
568
+ "type": content.get("type", "page"),
569
+ "space_key": content_space.get("key", ""),
570
+ "space_name": content_space.get("name", ""),
571
+ "excerpt": item.get("excerpt", ""),
572
+ "last_modified": item.get("lastModified"),
573
+ "url": url,
574
+ }
575
+
576
+ async def __aenter__(self) -> "ConfluenceClient":
577
+ """Async context manager entry."""
578
+ return self
579
+
580
+ async def __aexit__(
581
+ self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any
582
+ ) -> None:
583
+ """Async context manager exit."""
584
+ await self._client.aclose()