alita-sdk 0.3.532__py3-none-any.whl → 0.3.602__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.

Potentially problematic release.


This version of alita-sdk might be problematic. Click here for more details.

Files changed (137) hide show
  1. alita_sdk/cli/agent_executor.py +2 -1
  2. alita_sdk/cli/agent_loader.py +34 -4
  3. alita_sdk/cli/agents.py +433 -203
  4. alita_sdk/community/__init__.py +8 -4
  5. alita_sdk/configurations/__init__.py +1 -0
  6. alita_sdk/configurations/openapi.py +323 -0
  7. alita_sdk/runtime/clients/client.py +165 -7
  8. alita_sdk/runtime/langchain/_constants_bkup.py +1318 -0
  9. alita_sdk/runtime/langchain/assistant.py +61 -11
  10. alita_sdk/runtime/langchain/constants.py +419 -171
  11. alita_sdk/runtime/langchain/document_loaders/AlitaJSONLoader.py +4 -2
  12. alita_sdk/runtime/langchain/document_loaders/AlitaTextLoader.py +5 -2
  13. alita_sdk/runtime/langchain/langraph_agent.py +108 -23
  14. alita_sdk/runtime/langchain/utils.py +76 -14
  15. alita_sdk/runtime/skills/__init__.py +91 -0
  16. alita_sdk/runtime/skills/callbacks.py +498 -0
  17. alita_sdk/runtime/skills/discovery.py +540 -0
  18. alita_sdk/runtime/skills/executor.py +610 -0
  19. alita_sdk/runtime/skills/input_builder.py +371 -0
  20. alita_sdk/runtime/skills/models.py +330 -0
  21. alita_sdk/runtime/skills/registry.py +355 -0
  22. alita_sdk/runtime/skills/skill_runner.py +330 -0
  23. alita_sdk/runtime/toolkits/__init__.py +5 -0
  24. alita_sdk/runtime/toolkits/artifact.py +2 -1
  25. alita_sdk/runtime/toolkits/mcp.py +6 -3
  26. alita_sdk/runtime/toolkits/mcp_config.py +1048 -0
  27. alita_sdk/runtime/toolkits/skill_router.py +238 -0
  28. alita_sdk/runtime/toolkits/tools.py +139 -10
  29. alita_sdk/runtime/toolkits/vectorstore.py +1 -1
  30. alita_sdk/runtime/tools/__init__.py +3 -1
  31. alita_sdk/runtime/tools/artifact.py +15 -0
  32. alita_sdk/runtime/tools/data_analysis.py +183 -0
  33. alita_sdk/runtime/tools/llm.py +260 -73
  34. alita_sdk/runtime/tools/loop.py +3 -1
  35. alita_sdk/runtime/tools/loop_output.py +3 -1
  36. alita_sdk/runtime/tools/mcp_server_tool.py +6 -3
  37. alita_sdk/runtime/tools/router.py +2 -4
  38. alita_sdk/runtime/tools/sandbox.py +9 -6
  39. alita_sdk/runtime/tools/skill_router.py +776 -0
  40. alita_sdk/runtime/tools/tool.py +3 -1
  41. alita_sdk/runtime/tools/vectorstore.py +7 -2
  42. alita_sdk/runtime/tools/vectorstore_base.py +7 -2
  43. alita_sdk/runtime/utils/constants.py +5 -1
  44. alita_sdk/runtime/utils/mcp_client.py +1 -1
  45. alita_sdk/runtime/utils/mcp_sse_client.py +1 -1
  46. alita_sdk/runtime/utils/toolkit_utils.py +2 -0
  47. alita_sdk/tools/__init__.py +44 -2
  48. alita_sdk/tools/ado/repos/__init__.py +26 -8
  49. alita_sdk/tools/ado/repos/repos_wrapper.py +78 -52
  50. alita_sdk/tools/ado/test_plan/__init__.py +3 -2
  51. alita_sdk/tools/ado/test_plan/test_plan_wrapper.py +23 -1
  52. alita_sdk/tools/ado/utils.py +1 -18
  53. alita_sdk/tools/ado/wiki/__init__.py +2 -1
  54. alita_sdk/tools/ado/wiki/ado_wrapper.py +23 -1
  55. alita_sdk/tools/ado/work_item/__init__.py +3 -2
  56. alita_sdk/tools/ado/work_item/ado_wrapper.py +56 -3
  57. alita_sdk/tools/advanced_jira_mining/__init__.py +2 -1
  58. alita_sdk/tools/aws/delta_lake/__init__.py +2 -1
  59. alita_sdk/tools/azure_ai/search/__init__.py +2 -1
  60. alita_sdk/tools/azure_ai/search/api_wrapper.py +1 -1
  61. alita_sdk/tools/base_indexer_toolkit.py +51 -30
  62. alita_sdk/tools/bitbucket/__init__.py +2 -1
  63. alita_sdk/tools/bitbucket/api_wrapper.py +1 -1
  64. alita_sdk/tools/bitbucket/cloud_api_wrapper.py +3 -3
  65. alita_sdk/tools/browser/__init__.py +1 -1
  66. alita_sdk/tools/carrier/__init__.py +1 -1
  67. alita_sdk/tools/chunkers/code/treesitter/treesitter.py +37 -13
  68. alita_sdk/tools/cloud/aws/__init__.py +2 -1
  69. alita_sdk/tools/cloud/azure/__init__.py +2 -1
  70. alita_sdk/tools/cloud/gcp/__init__.py +2 -1
  71. alita_sdk/tools/cloud/k8s/__init__.py +2 -1
  72. alita_sdk/tools/code/linter/__init__.py +2 -1
  73. alita_sdk/tools/code/sonar/__init__.py +2 -1
  74. alita_sdk/tools/code_indexer_toolkit.py +19 -2
  75. alita_sdk/tools/confluence/__init__.py +7 -6
  76. alita_sdk/tools/confluence/api_wrapper.py +7 -8
  77. alita_sdk/tools/confluence/loader.py +4 -2
  78. alita_sdk/tools/custom_open_api/__init__.py +2 -1
  79. alita_sdk/tools/elastic/__init__.py +2 -1
  80. alita_sdk/tools/elitea_base.py +28 -9
  81. alita_sdk/tools/figma/__init__.py +52 -6
  82. alita_sdk/tools/figma/api_wrapper.py +1158 -123
  83. alita_sdk/tools/figma/figma_client.py +73 -0
  84. alita_sdk/tools/figma/toon_tools.py +2748 -0
  85. alita_sdk/tools/github/__init__.py +2 -1
  86. alita_sdk/tools/github/github_client.py +56 -92
  87. alita_sdk/tools/github/schemas.py +4 -4
  88. alita_sdk/tools/gitlab/__init__.py +2 -1
  89. alita_sdk/tools/gitlab/api_wrapper.py +118 -38
  90. alita_sdk/tools/gitlab_org/__init__.py +2 -1
  91. alita_sdk/tools/gitlab_org/api_wrapper.py +60 -62
  92. alita_sdk/tools/google/bigquery/__init__.py +2 -1
  93. alita_sdk/tools/google_places/__init__.py +2 -1
  94. alita_sdk/tools/jira/__init__.py +2 -1
  95. alita_sdk/tools/keycloak/__init__.py +2 -1
  96. alita_sdk/tools/localgit/__init__.py +2 -1
  97. alita_sdk/tools/memory/__init__.py +1 -1
  98. alita_sdk/tools/ocr/__init__.py +2 -1
  99. alita_sdk/tools/openapi/__init__.py +490 -118
  100. alita_sdk/tools/openapi/api_wrapper.py +1368 -0
  101. alita_sdk/tools/openapi/tool.py +20 -0
  102. alita_sdk/tools/pandas/__init__.py +11 -5
  103. alita_sdk/tools/pandas/api_wrapper.py +38 -25
  104. alita_sdk/tools/pandas/dataframe/generator/base.py +3 -1
  105. alita_sdk/tools/postman/__init__.py +2 -1
  106. alita_sdk/tools/pptx/__init__.py +2 -1
  107. alita_sdk/tools/qtest/__init__.py +21 -2
  108. alita_sdk/tools/qtest/api_wrapper.py +430 -13
  109. alita_sdk/tools/rally/__init__.py +2 -1
  110. alita_sdk/tools/rally/api_wrapper.py +1 -1
  111. alita_sdk/tools/report_portal/__init__.py +2 -1
  112. alita_sdk/tools/salesforce/__init__.py +2 -1
  113. alita_sdk/tools/servicenow/__init__.py +11 -10
  114. alita_sdk/tools/servicenow/api_wrapper.py +1 -1
  115. alita_sdk/tools/sharepoint/__init__.py +2 -1
  116. alita_sdk/tools/sharepoint/api_wrapper.py +2 -2
  117. alita_sdk/tools/slack/__init__.py +3 -2
  118. alita_sdk/tools/slack/api_wrapper.py +2 -2
  119. alita_sdk/tools/sql/__init__.py +3 -2
  120. alita_sdk/tools/testio/__init__.py +2 -1
  121. alita_sdk/tools/testrail/__init__.py +2 -1
  122. alita_sdk/tools/utils/content_parser.py +77 -3
  123. alita_sdk/tools/utils/text_operations.py +163 -71
  124. alita_sdk/tools/xray/__init__.py +3 -2
  125. alita_sdk/tools/yagmail/__init__.py +2 -1
  126. alita_sdk/tools/zephyr/__init__.py +2 -1
  127. alita_sdk/tools/zephyr_enterprise/__init__.py +2 -1
  128. alita_sdk/tools/zephyr_essential/__init__.py +2 -1
  129. alita_sdk/tools/zephyr_scale/__init__.py +3 -2
  130. alita_sdk/tools/zephyr_scale/api_wrapper.py +2 -2
  131. alita_sdk/tools/zephyr_squad/__init__.py +2 -1
  132. {alita_sdk-0.3.532.dist-info → alita_sdk-0.3.602.dist-info}/METADATA +7 -6
  133. {alita_sdk-0.3.532.dist-info → alita_sdk-0.3.602.dist-info}/RECORD +137 -119
  134. {alita_sdk-0.3.532.dist-info → alita_sdk-0.3.602.dist-info}/WHEEL +0 -0
  135. {alita_sdk-0.3.532.dist-info → alita_sdk-0.3.602.dist-info}/entry_points.txt +0 -0
  136. {alita_sdk-0.3.532.dist-info → alita_sdk-0.3.602.dist-info}/licenses/LICENSE +0 -0
  137. {alita_sdk-0.3.532.dist-info → alita_sdk-0.3.602.dist-info}/top_level.txt +0 -0
@@ -1,140 +1,512 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
1
4
  import json
2
- import re
3
5
  import logging
6
+ import threading
7
+ import time
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+ from urllib.parse import urlparse
10
+
11
+ from langchain_core.tools import BaseTool, BaseToolkit
12
+ from pydantic import BaseModel, ConfigDict, Field, create_model
13
+ import requests
4
14
  import yaml
5
- from typing import List, Any, Optional, Dict
6
- from langchain_core.tools import BaseTool, BaseToolkit, ToolException
7
- from requests_openapi import Operation, Client, Server
8
15
 
9
- from pydantic import create_model, Field
10
- from functools import partial
16
+ from .api_wrapper import _get_base_url_from_spec, build_wrapper
17
+ from .tool import OpenApiAction
18
+ from ..elitea_base import filter_missconfigured_index_tools
19
+ from ...configurations.openapi import OpenApiConfiguration
20
+ from ...runtime.utils.constants import TOOLKIT_NAME_META, TOOL_NAME_META, TOOLKIT_TYPE_META
11
21
 
12
22
  logger = logging.getLogger(__name__)
13
23
 
14
- name = "openapi"
24
+ name = 'openapi'
15
25
 
16
- def get_tools(tool):
17
- headers = {}
18
- if tool['settings'].get('authentication'):
19
- if tool['settings']['authentication']['type'] == 'api_key':
20
- auth_type = tool['settings']['authentication']['settings']['auth_type']
21
- auth_key = tool["settings"]["authentication"]["settings"]["api_key"]
22
- if auth_type.lower() == 'bearer':
23
- headers['Authorization'] = f'Bearer {auth_key}'
24
- if auth_type.lower() == 'basic':
25
- headers['Authorization'] = f'Basic {auth_key}'
26
- if auth_type.lower() == 'custom':
27
- headers[
28
- tool["settings"]["authentication"]["settings"]["custom_header_name"]] = f'{auth_key}'
26
+ # Module-level token cache: {cache_key: (access_token, expires_at_timestamp)}
27
+ # Protected by _oauth_token_cache_lock for thread-safe access
28
+ _oauth_token_cache: Dict[str, Tuple[str, float]] = {}
29
+ _oauth_token_cache_lock = threading.Lock()
30
+
31
+ # Token expiry buffer in seconds (refresh 60 seconds before actual expiry)
32
+ _TOKEN_EXPIRY_BUFFER = 60
33
+
34
+
35
+ def _get_oauth_cache_key(client_id: str, token_url: str, scope: Optional[str]) -> str:
36
+ """Generate a cache key for OAuth tokens."""
37
+ return f"{client_id}:{token_url}:{scope or ''}"
38
+
39
+
40
+ def _get_cached_token(cache_key: str) -> Optional[str]:
41
+ """Get a cached token if it exists and is not expired. Thread-safe."""
42
+ with _oauth_token_cache_lock:
43
+ if cache_key not in _oauth_token_cache:
44
+ return None
45
+ token, expires_at = _oauth_token_cache[cache_key]
46
+ if time.time() >= expires_at - _TOKEN_EXPIRY_BUFFER:
47
+ # Token expired or about to expire
48
+ del _oauth_token_cache[cache_key]
49
+ return None
50
+ return token
51
+
52
+
53
+ def _cache_token(cache_key: str, token: str, expires_in: Optional[int]) -> None:
54
+ """Cache a token with its expiry time. Thread-safe."""
55
+ # Default to 1 hour if expires_in not provided
56
+ expires_in = expires_in or 3600
57
+ expires_at = time.time() + expires_in
58
+ with _oauth_token_cache_lock:
59
+ _oauth_token_cache[cache_key] = (token, expires_at)
60
+
61
+
62
+ def _obtain_oauth_token(
63
+ client_id: str,
64
+ client_secret: str,
65
+ token_url: str,
66
+ scope: Optional[str] = None,
67
+ method: str = 'default',
68
+ timeout: int = 30,
69
+ ) -> Tuple[str, Optional[str]]:
70
+ """
71
+ Obtain an OAuth2 access token using client credentials flow.
72
+
73
+ Args:
74
+ client_id: OAuth client ID
75
+ client_secret: OAuth client secret
76
+ token_url: OAuth token endpoint URL
77
+ scope: Optional OAuth scope(s), space-separated if multiple
78
+ method: Token exchange method - 'default' (POST body) or 'Basic' (Basic auth header)
79
+ timeout: Request timeout in seconds
80
+
81
+ Returns:
82
+ Tuple of (access_token, error_message)
83
+ On success: (token, None)
84
+ On failure: (None, error_message)
85
+ """
86
+ try:
87
+ headers = {
88
+ 'Content-Type': 'application/x-www-form-urlencoded',
89
+ 'Accept': 'application/json',
90
+ }
91
+
92
+ # Build form data
93
+ data: Dict[str, str] = {
94
+ 'grant_type': 'client_credentials',
95
+ }
96
+
97
+ if method == 'Basic':
98
+ # Use Basic auth header for client credentials
99
+ credentials = f"{client_id}:{client_secret}"
100
+ encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
101
+ headers['Authorization'] = f'Basic {encoded_credentials}'
102
+ else:
103
+ # Default: include credentials in POST body
104
+ data['client_id'] = client_id
105
+ data['client_secret'] = client_secret
106
+
107
+ if scope:
108
+ data['scope'] = scope
109
+
110
+ # Log only the domain to avoid exposing sensitive path parameters (e.g., tenant IDs)
111
+ token_domain = urlparse(token_url).netloc or 'unknown'
112
+ logger.debug(f"OAuth token request to {token_domain} using method '{method}'")
113
+
114
+ response = requests.post(
115
+ token_url,
116
+ headers=headers,
117
+ data=data,
118
+ timeout=timeout,
119
+ )
120
+
121
+ if response.status_code == 200:
122
+ try:
123
+ token_data = response.json()
124
+ access_token = token_data.get('access_token')
125
+ if not access_token:
126
+ return None, "OAuth response did not contain 'access_token'"
127
+
128
+ # Cache the token
129
+ cache_key = _get_oauth_cache_key(client_id, token_url, scope)
130
+ expires_in = token_data.get('expires_in')
131
+ _cache_token(cache_key, access_token, expires_in)
132
+
133
+ logger.debug(f"OAuth token obtained successfully (expires_in: {expires_in})")
134
+ return access_token, None
135
+ except json.JSONDecodeError as e:
136
+ return None, f"Failed to parse OAuth token response as JSON: {e}"
137
+
138
+ # Handle error responses
139
+ error_msg = f"OAuth token request failed with status {response.status_code}"
140
+ try:
141
+ error_data = response.json()
142
+ if 'error' in error_data:
143
+ error_msg = f"{error_msg}: {error_data.get('error')}"
144
+ if 'error_description' in error_data:
145
+ error_msg = f"{error_msg} - {error_data.get('error_description')}"
146
+ except Exception:
147
+ if response.text:
148
+ error_msg = f"{error_msg}: {response.text[:500]}"
149
+
150
+ return None, error_msg
151
+
152
+ except requests.exceptions.Timeout:
153
+ return None, f"OAuth token request to {token_url} timed out"
154
+ except requests.exceptions.ConnectionError as e:
155
+ return None, f"Failed to connect to OAuth token endpoint {token_url}: {e}"
156
+ except requests.exceptions.RequestException as e:
157
+ return None, f"OAuth token request failed: {e}"
158
+ except Exception as e:
159
+ return None, f"Unexpected error during OAuth token exchange: {e}"
160
+
161
+
162
+ def _secret_to_str(value: Any) -> Optional[str]:
163
+ """Convert a secret value to string, handling SecretStr and other types."""
164
+ if value is None:
165
+ return None
166
+ if hasattr(value, 'get_secret_value'):
167
+ try:
168
+ value = value.get_secret_value()
169
+ except Exception:
170
+ pass
171
+ if isinstance(value, str):
172
+ return value
173
+ return str(value)
174
+
175
+
176
+ def _get_oauth_access_token(settings: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:
177
+ """
178
+ Get an OAuth access token from settings, using cache if available.
179
+
180
+ Args:
181
+ settings: Dictionary containing OAuth configuration
182
+
183
+ Returns:
184
+ Tuple of (access_token, error_message)
185
+ On success: (token, None)
186
+ On failure: (None, error_message)
187
+ If OAuth not configured: (None, None)
188
+ """
189
+ client_id = settings.get('client_id')
190
+ client_secret = _secret_to_str(settings.get('client_secret'))
191
+ token_url = settings.get('token_url')
192
+
193
+ # Check if OAuth is configured
194
+ if not client_id or not client_secret or not token_url:
195
+ return None, None # OAuth not configured
196
+
197
+ scope = settings.get('scope')
198
+ method = settings.get('method', 'default') or 'default'
199
+
200
+ # Try to get cached token
201
+ cache_key = _get_oauth_cache_key(client_id, token_url, scope)
202
+ cached_token = _get_cached_token(cache_key)
203
+ if cached_token:
204
+ logger.debug("Using cached OAuth token")
205
+ return cached_token, None
206
+
207
+ # Obtain new token
208
+ return _obtain_oauth_token(
209
+ client_id=client_id,
210
+ client_secret=client_secret,
211
+ token_url=token_url,
212
+ scope=scope,
213
+ method=method,
214
+ )
215
+
216
+
217
+ def get_toolkit(tool) -> BaseToolkit:
218
+ settings = tool.get('settings', {}) or {}
219
+ # Extract selected_tools separately to avoid duplicate keyword argument when unpacking **settings
220
+ selected_tools = settings.get('selected_tools', [])
221
+ # Filter out selected_tools from settings to prevent "got multiple values for keyword argument"
222
+ filtered_settings = {k: v for k, v in settings.items() if k != 'selected_tools'}
29
223
  return AlitaOpenAPIToolkit.get_toolkit(
30
- openapi_spec=tool['settings']['schema_settings'],
31
- selected_tools=tool['settings'].get('selected_tools', []),
32
- headers=headers).get_tools()
33
-
34
-
35
- def create_api_tool(name: str, op: Operation):
36
- fields = {}
37
- headers = {}
38
- headers_descriptions = []
39
-
40
- for parameter in op.spec.parameters:
41
- if "header" in parameter.param_in:
42
- headers[parameter.name] = parameter.param_schema.default
43
- headers_descriptions.append(f"Header: {parameter.name}. Description: {parameter.description}.")
44
- continue
45
- fields[parameter.name] = (str, Field(default=parameter.param_schema.default,
46
- description=parameter.description))
47
-
48
- # add headers
49
- if headers:
50
- fields['headers'] = (Optional[dict], Field(default = headers, description="The dict that represents headers for request:\n" + '\n'.join(headers_descriptions)))
51
-
52
- if op.spec.requestBody:
53
- fields['json'] = (Optional[str], Field(default = None, description="JSON request body provided as a string"))
54
-
55
- op.server = Server.from_openapi_server(op.server) # patch this
56
- op.server.get_url = partial(Server.get_url, op.server)
57
- op.server.set_url = partial(Server.set_url, op.server)
58
- return ApiTool(
59
- name=name,
60
- description=op.spec.description if op.spec.description else op.spec.summary,
61
- args_schema=create_model(
62
- 'request_params',
63
- regexp = (Optional[str], Field(description="Regular expression used to remove from final output if any", default=None)),
64
- **fields),
65
- callable=op
224
+ selected_tools=selected_tools,
225
+ toolkit_name=tool.get('toolkit_name'),
226
+ **filtered_settings,
66
227
  )
67
228
 
68
- class ApiTool(BaseTool):
69
- name: str
70
- description: str
71
- callable: Operation
72
-
73
- def _run(self, regexp: str = None, **kwargs):
74
- # set in query parameter from header (actual for authentication)
75
- rq_args = self.args.keys()
76
- headers = self.callable.requestor.headers
77
- for arg in rq_args:
78
- arg_value = headers.get(arg)
79
- if arg_value:
80
- kwargs.update({arg : arg_value})
81
-
82
- if kwargs.get("json"):
83
- # add json to payload
84
- kwargs.update({"json": json.loads(kwargs.get("json"))})
85
- output = self.callable(**kwargs).content
229
+
230
+ def get_tools(tool):
231
+ return get_toolkit(tool).get_tools()
232
+
233
+
234
+ def get_toolkit_available_tools(settings: dict) -> dict:
235
+ """Return instance-dependent tool list + per-tool args JSON schemas.
236
+
237
+ This is used by backend services when the UI needs spec-derived tool names
238
+ and input schemas (one tool per operationId). It must be JSON-serializable.
239
+ """
240
+ if not isinstance(settings, dict):
241
+ settings = {}
242
+
243
+ # Extract and merge openapi_configuration if present (same pattern as get_toolkit)
244
+ openapi_configuration = settings.get('openapi_configuration') or {}
245
+ if hasattr(openapi_configuration, 'model_dump'):
246
+ openapi_configuration = openapi_configuration.model_dump(mode='json')
247
+ if not isinstance(openapi_configuration, dict):
248
+ openapi_configuration = {}
249
+
250
+ # Merge settings with openapi_configuration so api_key, auth_type etc. are at root level
251
+ merged_settings: Dict[str, Any] = {
252
+ **settings,
253
+ **openapi_configuration,
254
+ }
255
+
256
+ spec = merged_settings.get('spec') or merged_settings.get('schema_settings') or merged_settings.get('openapi_spec')
257
+ base_url_override = merged_settings.get('base_url') or merged_settings.get('base_url_override')
258
+
259
+ if not spec or not isinstance(spec, (str, dict)):
260
+ return {"tools": [], "args_schemas": {}, "error": "OpenAPI spec is missing"}
261
+
262
+ try:
263
+ headers = _build_headers_from_settings(merged_settings)
264
+ api_wrapper = build_wrapper(
265
+ openapi_spec=spec,
266
+ base_headers=headers,
267
+ base_url_override=base_url_override,
268
+ )
269
+
270
+ tool_defs = api_wrapper.get_available_tools(selected_tools=None)
271
+
272
+ tools = []
273
+ args_schemas = {}
274
+
275
+ for tool_def in tool_defs:
276
+ name_val = tool_def.get('name')
277
+ if not isinstance(name_val, str) or not name_val:
278
+ continue
279
+
280
+ desc_val = tool_def.get('description')
281
+ if not isinstance(desc_val, str):
282
+ desc_val = ''
283
+
284
+ tools.append({"name": name_val, "description": desc_val})
285
+
286
+ args_schema = tool_def.get('args_schema')
287
+ if args_schema is None:
288
+ args_schemas[name_val] = {"type": "object", "properties": {}, "required": []}
289
+ continue
290
+
291
+ try:
292
+ if hasattr(args_schema, 'model_json_schema'):
293
+ args_schemas[name_val] = args_schema.model_json_schema()
294
+ elif hasattr(args_schema, 'schema'):
295
+ args_schemas[name_val] = args_schema.schema()
296
+ else:
297
+ args_schemas[name_val] = {"type": "object", "properties": {}, "required": []}
298
+ except Exception:
299
+ args_schemas[name_val] = {"type": "object", "properties": {}, "required": []}
300
+
301
+ # Ensure stable JSON-serializability.
86
302
  try:
87
- if regexp is not None:
88
- output = re.sub(rf'{regexp}', "", str(output))
89
- finally:
90
- return output
303
+ json.dumps({"tools": tools, "args_schemas": args_schemas})
304
+ except Exception:
305
+ return {"tools": tools, "args_schemas": {}}
306
+
307
+ return {"tools": tools, "args_schemas": args_schemas}
308
+
309
+ except Exception as e: # pylint: disable=W0718
310
+ return {"tools": [], "args_schemas": {}, "error": str(e)}
91
311
 
92
312
  class AlitaOpenAPIToolkit(BaseToolkit):
93
313
  request_session: Any #: :meta private:
94
314
  tools: List[BaseTool] = []
95
315
 
316
+ @staticmethod
317
+ def toolkit_config_schema() -> BaseModel:
318
+ # OpenAPI tool names + per-tool args schemas depend on the user-provided spec,
319
+ # so `selected_tools` cannot be an enum here (unlike most toolkits).
320
+
321
+ model = create_model(
322
+ name,
323
+ __config__=ConfigDict(
324
+ extra='ignore',
325
+ json_schema_extra={
326
+ 'metadata': {
327
+ 'label': 'OpenAPI',
328
+ 'icon_url': 'openapi.svg',
329
+ 'categories': ['integrations'],
330
+ 'extra_categories': ['api', 'openapi', 'swagger'],
331
+ }
332
+ }
333
+ ),
334
+ openapi_configuration=(
335
+ OpenApiConfiguration,
336
+ Field(
337
+ description='OpenAPI credentials configuration',
338
+ json_schema_extra={'configuration_types': ['openapi']},
339
+ ),
340
+ ),
341
+ base_url=(
342
+ Optional[str],
343
+ Field(
344
+ default=None,
345
+ description=(
346
+ "Optional base URL override (absolute, starting with http:// or https://). "
347
+ "Use this when your OpenAPI spec has no `servers` entry, or when `servers[0].url` "
348
+ "is not absolute (e.g. '/api/v3'). Example: 'https://petstore3.swagger.io'."
349
+ ),
350
+ ),
351
+ ),
352
+ spec=(
353
+ str,
354
+ Field(
355
+ description=(
356
+ 'OpenAPI specification (URL or raw JSON/YAML text). '
357
+ 'Used to generate per-operation tools (one tool per operationId).'
358
+ ),
359
+ json_schema_extra={'ui_component': 'openapi_spec'},
360
+ ),
361
+ ),
362
+ selected_tools=(
363
+ List[str],
364
+ Field(
365
+ default=[],
366
+ description='Optional list of operationIds to enable. If empty, all operations are enabled.',
367
+ json_schema_extra={'args_schemas': {}},
368
+ ),
369
+ ),
370
+ )
371
+ return model
372
+
96
373
  @classmethod
97
- def get_toolkit(cls, openapi_spec: str | dict,
98
- selected_tools: list[dict] | None = None,
99
- headers: Optional[Dict[str, str]] = None,
100
- toolkit_name: Optional[str] = None):
101
- if selected_tools is not None:
102
- tools_set = set([i if not isinstance(i, dict) else i.get('name') for i in selected_tools])
103
- else:
104
- tools_set = {}
105
- if isinstance(openapi_spec, str):
106
- # Try to detect if it's YAML or JSON by attempting to parse as JSON first
107
- try:
108
- openapi_spec = json.loads(openapi_spec)
109
- except json.JSONDecodeError:
110
- # If JSON parsing fails, try YAML
111
- try:
112
- openapi_spec = yaml.safe_load(openapi_spec)
113
- except yaml.YAMLError as e:
114
- raise ToolException(f"Failed to parse OpenAPI spec as JSON or YAML: {e}")
115
- c = Client()
116
- c.load_spec(openapi_spec)
117
- if headers:
118
- c.requestor.headers.update(headers)
119
- tools = []
120
- for i in tools_set:
374
+ @filter_missconfigured_index_tools
375
+ def get_toolkit(
376
+ cls,
377
+ selected_tools: list[str] | None = None,
378
+ toolkit_name: Optional[str] = None,
379
+ **kwargs,
380
+ ):
381
+ if selected_tools is None:
382
+ selected_tools = []
121
383
 
122
- try:
123
- if not i:
124
- raise ToolException("Operation id is missing for some of declared operations.")
125
- tool = c.operations[i]
126
- if not isinstance(tool, Operation):
127
- raise ToolException(f"Operation {i} is not an instance of Operation class.")
128
- api_tool = create_api_tool(i, tool)
129
- if toolkit_name:
130
- api_tool.metadata = {"toolkit_name": toolkit_name}
131
- tools.append(api_tool)
132
- except ToolException:
133
- raise
134
- except Exception as e:
135
- logger.warning(f"Tool {i} not found in OpenAPI spec.")
136
- raise ToolException(f"Cannot create API tool ({i}): \n{e}.")
137
- return cls(request_session=c, tools=tools)
384
+ tool_names = _coerce_selected_tool_names(selected_tools)
385
+
386
+ openapi_configuration = kwargs.get('openapi_configuration') or {}
387
+ if hasattr(openapi_configuration, 'model_dump'):
388
+ openapi_configuration = openapi_configuration.model_dump(mode='json')
389
+ if not isinstance(openapi_configuration, dict):
390
+ openapi_configuration = {}
391
+
392
+ merged_settings: Dict[str, Any] = {
393
+ **kwargs,
394
+ **openapi_configuration,
395
+ }
396
+
397
+ openapi_spec = merged_settings.get('spec') or merged_settings.get('schema_settings') or merged_settings.get('openapi_spec')
398
+ base_url_override = merged_settings.get('base_url') or merged_settings.get('base_url_override')
399
+ headers = _build_headers_from_settings(merged_settings)
400
+
401
+ api_wrapper = build_wrapper(
402
+ openapi_spec=openapi_spec,
403
+ base_headers=headers,
404
+ base_url_override=base_url_override,
405
+ )
406
+ base_url = _get_base_url_from_spec(api_wrapper.spec)
407
+
408
+ tools: List[BaseTool] = []
409
+ for tool_def in api_wrapper.get_available_tools(selected_tools=tool_names):
410
+ description = tool_def.get('description') or ''
411
+ if toolkit_name:
412
+ description = f"{description}\nToolkit: {toolkit_name}"
413
+ if base_url:
414
+ description = f"{description}\nBase URL: {base_url}"
415
+ description = description[:1000]
416
+
417
+ tools.append(
418
+ OpenApiAction(
419
+ api_wrapper=api_wrapper,
420
+ name=tool_def['name'],
421
+ description=description,
422
+ args_schema=tool_def.get('args_schema'),
423
+ metadata={TOOLKIT_NAME_META: toolkit_name, TOOLKIT_TYPE_META: name, TOOL_NAME_META: tool_def["name"]} if toolkit_name else {TOOL_NAME_META: tool_def["name"]},
424
+ )
425
+ )
426
+
427
+ return cls(request_session=api_wrapper, tools=tools)
138
428
 
139
429
  def get_tools(self):
140
430
  return self.tools
431
+
432
+
433
+ def _coerce_selected_tool_names(selected_tools: Any) -> list[str]:
434
+ if not selected_tools:
435
+ return []
436
+
437
+ if isinstance(selected_tools, list):
438
+ tool_names: List[str] = []
439
+ for item in selected_tools:
440
+ if isinstance(item, str):
441
+ tool_names.append(item)
442
+ elif isinstance(item, dict):
443
+ name_val = item.get('name')
444
+ if isinstance(name_val, str) and name_val.strip():
445
+ tool_names.append(name_val)
446
+ return [t for t in tool_names if t]
447
+
448
+ return []
449
+
450
+
451
+ def _build_headers_from_settings(settings: Dict[str, Any]) -> Dict[str, str]:
452
+ """
453
+ Build HTTP headers from settings, supporting API key and OAuth authentication.
454
+
455
+ Authentication priority:
456
+ 1. OAuth (client credentials flow) - if client_id, client_secret, and token_url are provided
457
+ 2. API Key - if api_key is provided
458
+ 3. Legacy authentication structure (for backward compatibility)
459
+
460
+ Args:
461
+ settings: Dictionary containing authentication settings
462
+
463
+ Returns:
464
+ Dictionary of HTTP headers to include in requests
465
+ """
466
+ headers: Dict[str, str] = {}
467
+
468
+ # First, try OAuth authentication (client credentials flow)
469
+ # This takes priority because it's more secure and commonly used with modern APIs
470
+ oauth_token, oauth_error = _get_oauth_access_token(settings)
471
+ if oauth_token:
472
+ headers['Authorization'] = f'Bearer {oauth_token}'
473
+ logger.debug("Using OAuth Bearer token for authentication")
474
+ return headers
475
+ elif oauth_error:
476
+ # OAuth was configured but failed - log the error
477
+ # We'll still try API key auth as fallback
478
+ logger.warning(f"OAuth token exchange failed: {oauth_error}")
479
+
480
+ # Legacy structure used by the custom OpenAPI UI
481
+ auth = settings.get('authentication')
482
+ if isinstance(auth, dict) and auth.get('type') == 'api_key':
483
+ auth_settings = auth.get('settings') or {}
484
+ if isinstance(auth_settings, dict):
485
+ auth_type = str(auth_settings.get('auth_type', '')).strip().lower()
486
+ api_key = _secret_to_str(auth_settings.get('api_key'))
487
+ if api_key:
488
+ if auth_type == 'bearer':
489
+ headers['Authorization'] = f'Bearer {api_key}'
490
+ elif auth_type == 'basic':
491
+ headers['Authorization'] = f'Basic {api_key}'
492
+ elif auth_type == 'custom':
493
+ header_name = auth_settings.get('custom_header_name')
494
+ if header_name:
495
+ headers[str(header_name)] = f'{api_key}'
496
+
497
+ # New regular-schema structure (GitHub-style sections) uses flattened fields
498
+ if not headers:
499
+ api_key = _secret_to_str(settings.get('api_key'))
500
+ if api_key:
501
+ auth_type = str(settings.get('auth_type', 'Bearer'))
502
+ auth_type_norm = auth_type.strip().lower()
503
+ if auth_type_norm == 'bearer':
504
+ headers['Authorization'] = f'Bearer {api_key}'
505
+ elif auth_type_norm == 'basic':
506
+ headers['Authorization'] = f'Basic {api_key}'
507
+ elif auth_type_norm == 'custom':
508
+ header_name = settings.get('custom_header_name')
509
+ if header_name:
510
+ headers[str(header_name)] = f'{api_key}'
511
+
512
+ return headers