alita-sdk 0.3.462__py3-none-any.whl → 0.3.627__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 (261) hide show
  1. alita_sdk/cli/agent/__init__.py +5 -0
  2. alita_sdk/cli/agent/default.py +258 -0
  3. alita_sdk/cli/agent_executor.py +15 -3
  4. alita_sdk/cli/agent_loader.py +56 -8
  5. alita_sdk/cli/agent_ui.py +93 -31
  6. alita_sdk/cli/agents.py +2274 -230
  7. alita_sdk/cli/callbacks.py +96 -25
  8. alita_sdk/cli/cli.py +10 -1
  9. alita_sdk/cli/config.py +162 -9
  10. alita_sdk/cli/context/__init__.py +30 -0
  11. alita_sdk/cli/context/cleanup.py +198 -0
  12. alita_sdk/cli/context/manager.py +731 -0
  13. alita_sdk/cli/context/message.py +285 -0
  14. alita_sdk/cli/context/strategies.py +289 -0
  15. alita_sdk/cli/context/token_estimation.py +127 -0
  16. alita_sdk/cli/input_handler.py +419 -0
  17. alita_sdk/cli/inventory.py +1073 -0
  18. alita_sdk/cli/testcases/__init__.py +94 -0
  19. alita_sdk/cli/testcases/data_generation.py +119 -0
  20. alita_sdk/cli/testcases/discovery.py +96 -0
  21. alita_sdk/cli/testcases/executor.py +84 -0
  22. alita_sdk/cli/testcases/logger.py +85 -0
  23. alita_sdk/cli/testcases/parser.py +172 -0
  24. alita_sdk/cli/testcases/prompts.py +91 -0
  25. alita_sdk/cli/testcases/reporting.py +125 -0
  26. alita_sdk/cli/testcases/setup.py +108 -0
  27. alita_sdk/cli/testcases/test_runner.py +282 -0
  28. alita_sdk/cli/testcases/utils.py +39 -0
  29. alita_sdk/cli/testcases/validation.py +90 -0
  30. alita_sdk/cli/testcases/workflow.py +196 -0
  31. alita_sdk/cli/toolkit.py +14 -17
  32. alita_sdk/cli/toolkit_loader.py +35 -5
  33. alita_sdk/cli/tools/__init__.py +36 -2
  34. alita_sdk/cli/tools/approval.py +224 -0
  35. alita_sdk/cli/tools/filesystem.py +910 -64
  36. alita_sdk/cli/tools/planning.py +389 -0
  37. alita_sdk/cli/tools/terminal.py +414 -0
  38. alita_sdk/community/__init__.py +72 -12
  39. alita_sdk/community/inventory/__init__.py +236 -0
  40. alita_sdk/community/inventory/config.py +257 -0
  41. alita_sdk/community/inventory/enrichment.py +2137 -0
  42. alita_sdk/community/inventory/extractors.py +1469 -0
  43. alita_sdk/community/inventory/ingestion.py +3172 -0
  44. alita_sdk/community/inventory/knowledge_graph.py +1457 -0
  45. alita_sdk/community/inventory/parsers/__init__.py +218 -0
  46. alita_sdk/community/inventory/parsers/base.py +295 -0
  47. alita_sdk/community/inventory/parsers/csharp_parser.py +907 -0
  48. alita_sdk/community/inventory/parsers/go_parser.py +851 -0
  49. alita_sdk/community/inventory/parsers/html_parser.py +389 -0
  50. alita_sdk/community/inventory/parsers/java_parser.py +593 -0
  51. alita_sdk/community/inventory/parsers/javascript_parser.py +629 -0
  52. alita_sdk/community/inventory/parsers/kotlin_parser.py +768 -0
  53. alita_sdk/community/inventory/parsers/markdown_parser.py +362 -0
  54. alita_sdk/community/inventory/parsers/python_parser.py +604 -0
  55. alita_sdk/community/inventory/parsers/rust_parser.py +858 -0
  56. alita_sdk/community/inventory/parsers/swift_parser.py +832 -0
  57. alita_sdk/community/inventory/parsers/text_parser.py +322 -0
  58. alita_sdk/community/inventory/parsers/yaml_parser.py +370 -0
  59. alita_sdk/community/inventory/patterns/__init__.py +61 -0
  60. alita_sdk/community/inventory/patterns/ast_adapter.py +380 -0
  61. alita_sdk/community/inventory/patterns/loader.py +348 -0
  62. alita_sdk/community/inventory/patterns/registry.py +198 -0
  63. alita_sdk/community/inventory/presets.py +535 -0
  64. alita_sdk/community/inventory/retrieval.py +1403 -0
  65. alita_sdk/community/inventory/toolkit.py +173 -0
  66. alita_sdk/community/inventory/toolkit_utils.py +176 -0
  67. alita_sdk/community/inventory/visualize.py +1370 -0
  68. alita_sdk/configurations/__init__.py +1 -1
  69. alita_sdk/configurations/ado.py +141 -20
  70. alita_sdk/configurations/bitbucket.py +0 -3
  71. alita_sdk/configurations/confluence.py +76 -42
  72. alita_sdk/configurations/figma.py +76 -0
  73. alita_sdk/configurations/gitlab.py +17 -5
  74. alita_sdk/configurations/openapi.py +329 -0
  75. alita_sdk/configurations/qtest.py +72 -1
  76. alita_sdk/configurations/report_portal.py +96 -0
  77. alita_sdk/configurations/sharepoint.py +148 -0
  78. alita_sdk/configurations/testio.py +83 -0
  79. alita_sdk/runtime/clients/artifact.py +3 -3
  80. alita_sdk/runtime/clients/client.py +353 -48
  81. alita_sdk/runtime/clients/sandbox_client.py +0 -21
  82. alita_sdk/runtime/langchain/_constants_bkup.py +1318 -0
  83. alita_sdk/runtime/langchain/assistant.py +123 -26
  84. alita_sdk/runtime/langchain/constants.py +642 -1
  85. alita_sdk/runtime/langchain/document_loaders/AlitaExcelLoader.py +103 -60
  86. alita_sdk/runtime/langchain/document_loaders/AlitaJSONLinesLoader.py +77 -0
  87. alita_sdk/runtime/langchain/document_loaders/AlitaJSONLoader.py +6 -3
  88. alita_sdk/runtime/langchain/document_loaders/AlitaPowerPointLoader.py +226 -7
  89. alita_sdk/runtime/langchain/document_loaders/AlitaTextLoader.py +5 -2
  90. alita_sdk/runtime/langchain/document_loaders/constants.py +12 -7
  91. alita_sdk/runtime/langchain/langraph_agent.py +279 -73
  92. alita_sdk/runtime/langchain/utils.py +82 -15
  93. alita_sdk/runtime/llms/preloaded.py +2 -6
  94. alita_sdk/runtime/skills/__init__.py +91 -0
  95. alita_sdk/runtime/skills/callbacks.py +498 -0
  96. alita_sdk/runtime/skills/discovery.py +540 -0
  97. alita_sdk/runtime/skills/executor.py +610 -0
  98. alita_sdk/runtime/skills/input_builder.py +371 -0
  99. alita_sdk/runtime/skills/models.py +330 -0
  100. alita_sdk/runtime/skills/registry.py +355 -0
  101. alita_sdk/runtime/skills/skill_runner.py +330 -0
  102. alita_sdk/runtime/toolkits/__init__.py +7 -0
  103. alita_sdk/runtime/toolkits/application.py +21 -9
  104. alita_sdk/runtime/toolkits/artifact.py +15 -5
  105. alita_sdk/runtime/toolkits/datasource.py +13 -6
  106. alita_sdk/runtime/toolkits/mcp.py +139 -251
  107. alita_sdk/runtime/toolkits/mcp_config.py +1048 -0
  108. alita_sdk/runtime/toolkits/planning.py +178 -0
  109. alita_sdk/runtime/toolkits/skill_router.py +238 -0
  110. alita_sdk/runtime/toolkits/subgraph.py +251 -6
  111. alita_sdk/runtime/toolkits/tools.py +238 -32
  112. alita_sdk/runtime/toolkits/vectorstore.py +11 -5
  113. alita_sdk/runtime/tools/__init__.py +3 -1
  114. alita_sdk/runtime/tools/application.py +20 -6
  115. alita_sdk/runtime/tools/artifact.py +511 -28
  116. alita_sdk/runtime/tools/data_analysis.py +183 -0
  117. alita_sdk/runtime/tools/function.py +43 -15
  118. alita_sdk/runtime/tools/image_generation.py +50 -44
  119. alita_sdk/runtime/tools/llm.py +852 -67
  120. alita_sdk/runtime/tools/loop.py +3 -1
  121. alita_sdk/runtime/tools/loop_output.py +3 -1
  122. alita_sdk/runtime/tools/mcp_remote_tool.py +25 -10
  123. alita_sdk/runtime/tools/mcp_server_tool.py +7 -6
  124. alita_sdk/runtime/tools/planning/__init__.py +36 -0
  125. alita_sdk/runtime/tools/planning/models.py +246 -0
  126. alita_sdk/runtime/tools/planning/wrapper.py +607 -0
  127. alita_sdk/runtime/tools/router.py +2 -4
  128. alita_sdk/runtime/tools/sandbox.py +9 -6
  129. alita_sdk/runtime/tools/skill_router.py +776 -0
  130. alita_sdk/runtime/tools/tool.py +3 -1
  131. alita_sdk/runtime/tools/vectorstore.py +7 -2
  132. alita_sdk/runtime/tools/vectorstore_base.py +51 -11
  133. alita_sdk/runtime/utils/AlitaCallback.py +137 -21
  134. alita_sdk/runtime/utils/constants.py +5 -1
  135. alita_sdk/runtime/utils/mcp_client.py +492 -0
  136. alita_sdk/runtime/utils/mcp_oauth.py +202 -5
  137. alita_sdk/runtime/utils/mcp_sse_client.py +36 -7
  138. alita_sdk/runtime/utils/mcp_tools_discovery.py +124 -0
  139. alita_sdk/runtime/utils/serialization.py +155 -0
  140. alita_sdk/runtime/utils/streamlit.py +6 -10
  141. alita_sdk/runtime/utils/toolkit_utils.py +16 -5
  142. alita_sdk/runtime/utils/utils.py +36 -0
  143. alita_sdk/tools/__init__.py +113 -29
  144. alita_sdk/tools/ado/repos/__init__.py +51 -33
  145. alita_sdk/tools/ado/repos/repos_wrapper.py +148 -89
  146. alita_sdk/tools/ado/test_plan/__init__.py +25 -9
  147. alita_sdk/tools/ado/test_plan/test_plan_wrapper.py +23 -1
  148. alita_sdk/tools/ado/utils.py +1 -18
  149. alita_sdk/tools/ado/wiki/__init__.py +25 -8
  150. alita_sdk/tools/ado/wiki/ado_wrapper.py +291 -22
  151. alita_sdk/tools/ado/work_item/__init__.py +26 -9
  152. alita_sdk/tools/ado/work_item/ado_wrapper.py +56 -3
  153. alita_sdk/tools/advanced_jira_mining/__init__.py +11 -8
  154. alita_sdk/tools/aws/delta_lake/__init__.py +13 -9
  155. alita_sdk/tools/aws/delta_lake/tool.py +5 -1
  156. alita_sdk/tools/azure_ai/search/__init__.py +11 -8
  157. alita_sdk/tools/azure_ai/search/api_wrapper.py +1 -1
  158. alita_sdk/tools/base/tool.py +5 -1
  159. alita_sdk/tools/base_indexer_toolkit.py +170 -45
  160. alita_sdk/tools/bitbucket/__init__.py +17 -12
  161. alita_sdk/tools/bitbucket/api_wrapper.py +59 -11
  162. alita_sdk/tools/bitbucket/cloud_api_wrapper.py +49 -35
  163. alita_sdk/tools/browser/__init__.py +5 -4
  164. alita_sdk/tools/carrier/__init__.py +5 -6
  165. alita_sdk/tools/carrier/backend_reports_tool.py +6 -6
  166. alita_sdk/tools/carrier/run_ui_test_tool.py +6 -6
  167. alita_sdk/tools/carrier/ui_reports_tool.py +5 -5
  168. alita_sdk/tools/chunkers/__init__.py +3 -1
  169. alita_sdk/tools/chunkers/code/treesitter/treesitter.py +37 -13
  170. alita_sdk/tools/chunkers/sematic/json_chunker.py +1 -0
  171. alita_sdk/tools/chunkers/sematic/markdown_chunker.py +97 -6
  172. alita_sdk/tools/chunkers/universal_chunker.py +270 -0
  173. alita_sdk/tools/cloud/aws/__init__.py +10 -7
  174. alita_sdk/tools/cloud/azure/__init__.py +10 -7
  175. alita_sdk/tools/cloud/gcp/__init__.py +10 -7
  176. alita_sdk/tools/cloud/k8s/__init__.py +10 -7
  177. alita_sdk/tools/code/linter/__init__.py +10 -8
  178. alita_sdk/tools/code/loaders/codesearcher.py +3 -2
  179. alita_sdk/tools/code/sonar/__init__.py +10 -7
  180. alita_sdk/tools/code_indexer_toolkit.py +73 -23
  181. alita_sdk/tools/confluence/__init__.py +21 -15
  182. alita_sdk/tools/confluence/api_wrapper.py +78 -23
  183. alita_sdk/tools/confluence/loader.py +4 -2
  184. alita_sdk/tools/custom_open_api/__init__.py +12 -5
  185. alita_sdk/tools/elastic/__init__.py +11 -8
  186. alita_sdk/tools/elitea_base.py +493 -30
  187. alita_sdk/tools/figma/__init__.py +58 -11
  188. alita_sdk/tools/figma/api_wrapper.py +1235 -143
  189. alita_sdk/tools/figma/figma_client.py +73 -0
  190. alita_sdk/tools/figma/toon_tools.py +2748 -0
  191. alita_sdk/tools/github/__init__.py +13 -14
  192. alita_sdk/tools/github/github_client.py +224 -100
  193. alita_sdk/tools/github/graphql_client_wrapper.py +119 -33
  194. alita_sdk/tools/github/schemas.py +14 -5
  195. alita_sdk/tools/github/tool.py +5 -1
  196. alita_sdk/tools/github/tool_prompts.py +9 -22
  197. alita_sdk/tools/gitlab/__init__.py +15 -11
  198. alita_sdk/tools/gitlab/api_wrapper.py +207 -41
  199. alita_sdk/tools/gitlab_org/__init__.py +10 -8
  200. alita_sdk/tools/gitlab_org/api_wrapper.py +63 -64
  201. alita_sdk/tools/google/bigquery/__init__.py +13 -12
  202. alita_sdk/tools/google/bigquery/tool.py +5 -1
  203. alita_sdk/tools/google_places/__init__.py +10 -8
  204. alita_sdk/tools/google_places/api_wrapper.py +1 -1
  205. alita_sdk/tools/jira/__init__.py +17 -11
  206. alita_sdk/tools/jira/api_wrapper.py +91 -40
  207. alita_sdk/tools/keycloak/__init__.py +11 -8
  208. alita_sdk/tools/localgit/__init__.py +9 -3
  209. alita_sdk/tools/localgit/local_git.py +62 -54
  210. alita_sdk/tools/localgit/tool.py +5 -1
  211. alita_sdk/tools/memory/__init__.py +11 -3
  212. alita_sdk/tools/non_code_indexer_toolkit.py +1 -0
  213. alita_sdk/tools/ocr/__init__.py +11 -8
  214. alita_sdk/tools/openapi/__init__.py +490 -114
  215. alita_sdk/tools/openapi/api_wrapper.py +1368 -0
  216. alita_sdk/tools/openapi/tool.py +20 -0
  217. alita_sdk/tools/pandas/__init__.py +20 -12
  218. alita_sdk/tools/pandas/api_wrapper.py +38 -25
  219. alita_sdk/tools/pandas/dataframe/generator/base.py +3 -1
  220. alita_sdk/tools/postman/__init__.py +11 -11
  221. alita_sdk/tools/pptx/__init__.py +10 -9
  222. alita_sdk/tools/pptx/pptx_wrapper.py +1 -1
  223. alita_sdk/tools/qtest/__init__.py +30 -10
  224. alita_sdk/tools/qtest/api_wrapper.py +430 -13
  225. alita_sdk/tools/rally/__init__.py +10 -8
  226. alita_sdk/tools/rally/api_wrapper.py +1 -1
  227. alita_sdk/tools/report_portal/__init__.py +12 -9
  228. alita_sdk/tools/salesforce/__init__.py +10 -9
  229. alita_sdk/tools/servicenow/__init__.py +17 -14
  230. alita_sdk/tools/servicenow/api_wrapper.py +1 -1
  231. alita_sdk/tools/sharepoint/__init__.py +10 -8
  232. alita_sdk/tools/sharepoint/api_wrapper.py +4 -4
  233. alita_sdk/tools/slack/__init__.py +10 -8
  234. alita_sdk/tools/slack/api_wrapper.py +2 -2
  235. alita_sdk/tools/sql/__init__.py +11 -9
  236. alita_sdk/tools/testio/__init__.py +10 -8
  237. alita_sdk/tools/testrail/__init__.py +11 -8
  238. alita_sdk/tools/testrail/api_wrapper.py +1 -1
  239. alita_sdk/tools/utils/__init__.py +9 -4
  240. alita_sdk/tools/utils/content_parser.py +77 -3
  241. alita_sdk/tools/utils/text_operations.py +410 -0
  242. alita_sdk/tools/utils/tool_prompts.py +79 -0
  243. alita_sdk/tools/vector_adapters/VectorStoreAdapter.py +17 -13
  244. alita_sdk/tools/xray/__init__.py +12 -9
  245. alita_sdk/tools/yagmail/__init__.py +9 -3
  246. alita_sdk/tools/zephyr/__init__.py +9 -7
  247. alita_sdk/tools/zephyr_enterprise/__init__.py +11 -8
  248. alita_sdk/tools/zephyr_essential/__init__.py +10 -8
  249. alita_sdk/tools/zephyr_essential/api_wrapper.py +30 -13
  250. alita_sdk/tools/zephyr_essential/client.py +2 -2
  251. alita_sdk/tools/zephyr_scale/__init__.py +11 -9
  252. alita_sdk/tools/zephyr_scale/api_wrapper.py +2 -2
  253. alita_sdk/tools/zephyr_squad/__init__.py +10 -8
  254. {alita_sdk-0.3.462.dist-info → alita_sdk-0.3.627.dist-info}/METADATA +147 -7
  255. alita_sdk-0.3.627.dist-info/RECORD +468 -0
  256. alita_sdk-0.3.627.dist-info/entry_points.txt +2 -0
  257. alita_sdk-0.3.462.dist-info/RECORD +0 -384
  258. alita_sdk-0.3.462.dist-info/entry_points.txt +0 -2
  259. {alita_sdk-0.3.462.dist-info → alita_sdk-0.3.627.dist-info}/WHEEL +0 -0
  260. {alita_sdk-0.3.462.dist-info → alita_sdk-0.3.627.dist-info}/licenses/LICENSE +0 -0
  261. {alita_sdk-0.3.462.dist-info → alita_sdk-0.3.627.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1368 @@
1
+ import json
2
+ import logging
3
+ import re
4
+ from urllib.parse import urlencode
5
+ from typing import Annotated, Any, Callable, Optional
6
+ import copy
7
+
8
+ import yaml
9
+ from langchain_core.tools import ToolException
10
+ from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, PrivateAttr, create_model
11
+ from requests_openapi import Client, Operation
12
+
13
+ from ..elitea_base import BaseToolApiWrapper
14
+ from ..utils import clean_string
15
+
16
+
17
+ def _coerce_empty_string_to_none(v: Any) -> Any:
18
+ """Convert empty strings to None for optional fields.
19
+
20
+ This handles UI/pipeline inputs where empty fields are sent as '' instead of null.
21
+ """
22
+ if v == '':
23
+ return None
24
+ return v
25
+
26
+
27
+ def _coerce_headers_value(v: Any) -> Optional[dict]:
28
+ """Convert headers value to dict, handling empty strings and JSON strings.
29
+
30
+ This handles UI/pipeline inputs where:
31
+ - Empty fields are sent as '' instead of null
32
+ - Dict values may be sent as JSON strings like '{}'
33
+ """
34
+ if v is None or v == '':
35
+ return None
36
+ if isinstance(v, dict):
37
+ return v
38
+ if isinstance(v, str):
39
+ try:
40
+ parsed = json.loads(v)
41
+ if isinstance(parsed, dict):
42
+ return parsed
43
+ except json.JSONDecodeError:
44
+ # Intentionally ignore JSON decode errors - fall back to returning
45
+ # the original value which will be validated later in _execute
46
+ pass
47
+ # Return as-is, will be validated later in _execute
48
+ return v
49
+
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ # Base class for dynamically created parameter models
55
+ # Supports populate_by_name so both alias (original param name) and field name (sanitized) work
56
+ class _BaseParamsModel(BaseModel):
57
+ model_config = ConfigDict(populate_by_name=True)
58
+
59
+
60
+ def _sanitize_param_name(name: str) -> str:
61
+ """Sanitize OpenAPI parameter names for use as Python/Pydantic identifiers.
62
+
63
+ Pydantic's create_model requires valid Python identifiers as field names.
64
+ This function handles:
65
+ - Dots in names (e.g., 'searchCriteria.minTime' -> 'searchCriteria_minTime')
66
+ - Dollar sign prefix (e.g., '$top' -> 'dollar_top')
67
+ - Other special characters
68
+
69
+ Returns the sanitized name suitable for use as a Pydantic field name.
70
+ """
71
+ if not name:
72
+ return name
73
+
74
+ sanitized = name
75
+ # Replace dots with underscores
76
+ sanitized = sanitized.replace('.', '_')
77
+ # Handle $ prefix (common in OData APIs like Azure DevOps)
78
+ if sanitized.startswith('$'):
79
+ sanitized = 'dollar_' + sanitized[1:]
80
+ # Replace any remaining invalid characters with underscores
81
+ # Python identifiers: [a-zA-Z_][a-zA-Z0-9_]*
82
+ sanitized = re.sub(r'[^a-zA-Z0-9_]', '_', sanitized)
83
+ # Ensure it doesn't start with a digit
84
+ if sanitized and sanitized[0].isdigit():
85
+ sanitized = '_' + sanitized
86
+
87
+ return sanitized
88
+
89
+
90
+ def _raise_openapi_tool_exception(
91
+ *,
92
+ code: str,
93
+ message: str,
94
+ operation_id: Optional[str] = None,
95
+ url: Optional[str] = None,
96
+ retryable: Optional[bool] = None,
97
+ missing_inputs: Optional[list[str]] = None,
98
+ http_status: Optional[int] = None,
99
+ http_body_preview: Optional[str] = None,
100
+ details: Optional[dict[str, Any]] = None,
101
+ ) -> None:
102
+ payload: dict[str, Any] = {
103
+ "tool": "openapi",
104
+ "code": code,
105
+ "message": message,
106
+ }
107
+ if operation_id:
108
+ payload["operation_id"] = operation_id
109
+ if url:
110
+ payload["url"] = url
111
+ if retryable is not None:
112
+ payload["retryable"] = bool(retryable)
113
+ if missing_inputs:
114
+ payload["missing_inputs"] = list(missing_inputs)
115
+ if http_status is not None:
116
+ payload["http_status"] = int(http_status)
117
+ if http_body_preview:
118
+ payload["http_body_preview"] = str(http_body_preview)
119
+ if details:
120
+ payload["details"] = details
121
+
122
+ try:
123
+ details_json = json.dumps(payload, ensure_ascii=False, indent=2)
124
+ except Exception:
125
+ details_json = str(payload)
126
+
127
+ raise ToolException(f"{message}\n\nToolError:\n{details_json}")
128
+
129
+
130
+ def _truncate(text: Any, max_len: int) -> str:
131
+ if text is None:
132
+ return ""
133
+ s = str(text)
134
+ if len(s) <= max_len:
135
+ return s
136
+ return s[:max_len] + "…"
137
+
138
+
139
+ def _is_retryable_http_status(status_code: Optional[int]) -> bool:
140
+ if status_code is None:
141
+ return False
142
+ return int(status_code) in (408, 425, 429, 500, 502, 503, 504)
143
+
144
+
145
+ def _resolve_server_variables(url: str, variables: Optional[dict]) -> tuple[str, list[str]]:
146
+ """
147
+ Substitute server variables in URL with their default values.
148
+
149
+ Per OpenAPI 3.x spec, server URLs can contain variables like:
150
+ https://dev.azure.com/{organization}/{project}
151
+
152
+ The variables object provides default values:
153
+ {
154
+ "organization": {"default": "MyOrg"},
155
+ "project": {"default": "MyProject"}
156
+ }
157
+
158
+ Args:
159
+ url: Server URL potentially containing {variable} placeholders
160
+ variables: Dict of variable definitions with 'default' values
161
+
162
+ Returns:
163
+ Tuple of (resolved_url, list of variable names that could not be resolved)
164
+ """
165
+ if not url:
166
+ return url, []
167
+
168
+ result = url
169
+ missing_defaults: list[str] = []
170
+
171
+ if variables and isinstance(variables, dict):
172
+ for var_name, var_def in variables.items():
173
+ placeholder = '{' + str(var_name) + '}'
174
+ if placeholder not in result:
175
+ continue # Variable not used in URL
176
+
177
+ if not isinstance(var_def, dict):
178
+ missing_defaults.append(var_name)
179
+ continue
180
+
181
+ default_value = var_def.get('default')
182
+ if default_value is not None:
183
+ result = result.replace(placeholder, str(default_value))
184
+ else:
185
+ # Variable defined but no default provided
186
+ missing_defaults.append(var_name)
187
+
188
+ # Check for any remaining {variable} placeholders that weren't in the variables dict
189
+ # This catches cases where the URL has placeholders but no variables definition
190
+ remaining_placeholders = re.findall(r'\{([^}]+)\}', result)
191
+ for placeholder_name in remaining_placeholders:
192
+ if placeholder_name not in missing_defaults:
193
+ missing_defaults.append(placeholder_name)
194
+
195
+ return result, missing_defaults
196
+
197
+
198
+ def _get_base_url_from_spec(spec: dict) -> str:
199
+ """
200
+ Extract base URL from OpenAPI spec's servers array.
201
+
202
+ Handles server variables by substituting their default values.
203
+ For example:
204
+ url: "https://dev.azure.com/{organization}/{project}"
205
+ variables:
206
+ organization: {default: "MyOrg"}
207
+ project: {default: "MyProject"}
208
+
209
+ Returns: "https://dev.azure.com/MyOrg/MyProject"
210
+
211
+ Note: Unresolved variables are logged but not raised here - this function
212
+ is used for display/debugging purposes. The main validation happens in
213
+ _resolve_server_variables_in_spec() during initialization.
214
+ """
215
+ servers = spec.get("servers") if isinstance(spec, dict) else None
216
+ if isinstance(servers, list) and servers:
217
+ first = servers[0]
218
+ if isinstance(first, dict) and isinstance(first.get("url"), str):
219
+ url = first["url"].strip()
220
+ variables = first.get("variables")
221
+ resolved_url, _ = _resolve_server_variables(url, variables)
222
+ return resolved_url
223
+ return ""
224
+
225
+
226
+ def _is_absolute_url(url: str) -> bool:
227
+ return isinstance(url, str) and (url.startswith("http://") or url.startswith("https://"))
228
+
229
+
230
+ def _resolve_server_variables_in_spec(spec: dict) -> tuple[dict, Optional[dict]]:
231
+ """
232
+ Resolve server variables in the OpenAPI spec by substituting their default values.
233
+
234
+ This modifies the spec's servers[].url to replace {variable} placeholders with
235
+ the default values from servers[].variables. This is necessary because the
236
+ requests_openapi library doesn't handle server variables - it uses the raw URL.
237
+
238
+ Example transformation:
239
+ url: "https://dev.azure.com/{organization}/{project}"
240
+ variables:
241
+ organization: {default: "MyOrg"}
242
+ project: {default: "MyProject"}
243
+
244
+ Becomes:
245
+ url: "https://dev.azure.com/MyOrg/MyProject"
246
+
247
+ Args:
248
+ spec: OpenAPI specification dict
249
+
250
+ Returns:
251
+ Tuple of (spec, unresolved_info) where:
252
+ - spec: The same spec dict with server URLs resolved (modified in place)
253
+ - unresolved_info: None if all variables resolved, or dict with error details:
254
+ {
255
+ "url": original URL with placeholders,
256
+ "missing_vars": list of variable names without defaults,
257
+ "server_index": index of problematic server
258
+ }
259
+ """
260
+ if not isinstance(spec, dict):
261
+ return spec, None
262
+
263
+ servers = spec.get("servers")
264
+ if not isinstance(servers, list):
265
+ return spec, None
266
+
267
+ unresolved_info = None
268
+
269
+ for i, server in enumerate(servers):
270
+ if not isinstance(server, dict):
271
+ continue
272
+ url = server.get("url")
273
+ if not isinstance(url, str):
274
+ continue
275
+ variables = server.get("variables")
276
+
277
+ resolved_url, missing_vars = _resolve_server_variables(url, variables)
278
+
279
+ if missing_vars:
280
+ # Track unresolved variables for deferred error at execution time
281
+ # Store only the first server with issues (usually there's only one)
282
+ if unresolved_info is None:
283
+ logger.warning(
284
+ f"Server URL '{url}' has variables without defaults: {missing_vars}. "
285
+ f"Tool execution will fail until defaults are provided in the spec."
286
+ )
287
+ unresolved_info = {
288
+ "url": url,
289
+ "missing_vars": missing_vars,
290
+ "server_index": i,
291
+ }
292
+
293
+ # Add placeholder defaults so openapi_pydantic validation passes
294
+ # The URL will still have {placeholders} but at least the spec parses
295
+ if variables and isinstance(variables, dict):
296
+ for var_name in missing_vars:
297
+ if var_name in variables and isinstance(variables[var_name], dict):
298
+ # Add a placeholder default - the URL won't work but spec will parse
299
+ variables[var_name]["default"] = f"MISSING_{var_name}"
300
+
301
+ if resolved_url != url:
302
+ server["url"] = resolved_url
303
+ logger.debug(f"Resolved server URL: '{url}' -> '{resolved_url}'")
304
+
305
+ return spec, unresolved_info
306
+
307
+
308
+ def _apply_base_url_override(spec: dict, base_url_override: str) -> dict:
309
+ """Normalize server URL when OpenAPI spec uses relative servers.
310
+
311
+ Some public specs (including Petstore) use relative server URLs like "/api/v3".
312
+ To execute requests against a real host, we can provide a base URL override like
313
+ "https://petstore3.swagger.io" and convert the first server URL to an absolute URL.
314
+ """
315
+ if not isinstance(spec, dict):
316
+ return spec
317
+ if not isinstance(base_url_override, str) or not base_url_override.strip():
318
+ return spec
319
+ base_url_override = base_url_override.strip().rstrip("/")
320
+
321
+ servers = spec.get("servers")
322
+ if not isinstance(servers, list) or not servers:
323
+ spec["servers"] = [{"url": base_url_override}]
324
+ return spec
325
+
326
+ first = servers[0]
327
+ if not isinstance(first, dict):
328
+ return spec
329
+ server_url = first.get("url")
330
+ if not isinstance(server_url, str):
331
+ return spec
332
+ server_url = server_url.strip()
333
+ if not server_url:
334
+ first["url"] = base_url_override
335
+ return spec
336
+ if _is_absolute_url(server_url):
337
+ return spec
338
+
339
+ # Relative server URL ("/api/v3" or "api/v3") -> join with base host.
340
+ if not server_url.startswith("/"):
341
+ server_url = "/" + server_url
342
+ first["url"] = base_url_override + server_url
343
+ return spec
344
+
345
+
346
+ def _join_base_and_path(base_url: str, path: str) -> str:
347
+ base = (base_url or "").rstrip("/")
348
+ p = (path or "")
349
+ if not p.startswith("/"):
350
+ p = "/" + p
351
+ if not base:
352
+ return p
353
+ return base + p
354
+
355
+
356
+ # Maximum length for generated operationIds (tool names)
357
+ _MAX_OPERATION_ID_LENGTH = 64
358
+
359
+ # Map HTTP methods to semantic action names for better readability
360
+ _METHOD_TO_ACTION = {
361
+ 'get': 'get',
362
+ 'post': 'create',
363
+ 'put': 'update',
364
+ 'patch': 'update',
365
+ 'delete': 'delete',
366
+ 'head': 'head',
367
+ 'options': 'options',
368
+ 'trace': 'trace',
369
+ }
370
+
371
+
372
+ def _generate_operation_id(method: str, path: str) -> str:
373
+ """
374
+ Generate an operationId from HTTP method and path when not provided in spec.
375
+
376
+ Follows a pattern that produces readable, unique identifiers:
377
+ - Format: {action}_{path_segments}
378
+ - HTTP methods are mapped to semantic actions (POST→create, PUT/PATCH→update)
379
+ - Path parameters ({id}) become "by_{param}"
380
+ - Segments are joined with underscores
381
+ - Result is snake_case
382
+ - Truncated to _MAX_OPERATION_ID_LENGTH characters
383
+
384
+ Examples:
385
+ GET /users -> get_users
386
+ GET /users/{id} -> get_users_by_id
387
+ POST /users -> create_users
388
+ PUT /users/{id} -> update_users_by_id
389
+ PATCH /users/{id} -> update_users_by_id
390
+ DELETE /api/v1/items/{itemId} -> delete_api_v1_items_by_itemId
391
+
392
+ Args:
393
+ method: HTTP method (GET, POST, etc.)
394
+ path: URL path (e.g., /users/{id})
395
+
396
+ Returns:
397
+ Generated operationId string
398
+ """
399
+ # Map HTTP method to semantic action
400
+ action = _METHOD_TO_ACTION.get(method.lower(), method.lower())
401
+
402
+ # Split path and process segments
403
+ segments = [s for s in path.split('/') if s]
404
+ processed_segments = []
405
+
406
+ for segment in segments:
407
+ # Check if it's a path parameter like {id} or {userId}
408
+ if segment.startswith('{') and segment.endswith('}'):
409
+ param_name = segment[1:-1] # Remove braces
410
+ processed_segments.append(f'by_{param_name}')
411
+ else:
412
+ # Regular segment - keep as is (already suitable for identifier)
413
+ # Replace any non-alphanumeric chars with underscore
414
+ clean_segment = re.sub(r'[^a-zA-Z0-9]', '_', segment)
415
+ if clean_segment:
416
+ processed_segments.append(clean_segment)
417
+
418
+ # Join: action_segment1_segment2_...
419
+ if processed_segments:
420
+ operation_id = f"{action}_{'_'.join(processed_segments)}"
421
+ else:
422
+ # Edge case: root path "/"
423
+ operation_id = f"{action}_root"
424
+
425
+ # Ensure valid Python identifier (no leading digits)
426
+ if operation_id[0].isdigit():
427
+ operation_id = '_' + operation_id
428
+
429
+ # Truncate if too long
430
+ if len(operation_id) > _MAX_OPERATION_ID_LENGTH:
431
+ # Start with a hard cut at the max length
432
+ truncated = operation_id[:_MAX_OPERATION_ID_LENGTH]
433
+ # Prefer truncating at a word boundary (underscore) if possible
434
+ last_underscore = truncated.rfind('_')
435
+ if last_underscore > 0:
436
+ truncated = truncated[:last_underscore]
437
+ # Ensure we don't end with an underscore after truncation
438
+ truncated = truncated.rstrip('_')
439
+ operation_id = truncated
440
+
441
+ return operation_id
442
+
443
+
444
+ def _ensure_operation_ids(spec: dict) -> dict:
445
+ """
446
+ Ensure all operations in the spec have operationIds.
447
+
448
+ For operations missing operationId, generates one from method+path.
449
+ Handles deduplication by appending _2, _3, etc. for collisions.
450
+
451
+ Args:
452
+ spec: Parsed OpenAPI specification dict
453
+
454
+ Returns:
455
+ The same spec dict with operationIds injected where missing
456
+ """
457
+ paths = spec.get('paths')
458
+ if not isinstance(paths, dict):
459
+ return spec
460
+
461
+ # Track all operationIds (existing + generated) to handle collisions
462
+ used_operation_ids: set[str] = set()
463
+
464
+ # First pass: collect existing operationIds
465
+ for path, path_item in paths.items():
466
+ if not isinstance(path_item, dict):
467
+ continue
468
+ for method, operation in path_item.items():
469
+ if not isinstance(operation, dict):
470
+ continue
471
+ # Skip non-operation keys like 'parameters', 'summary', etc.
472
+ if method.lower() not in ('get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'):
473
+ continue
474
+ existing_id = operation.get('operationId')
475
+ if existing_id:
476
+ used_operation_ids.add(str(existing_id))
477
+
478
+ # Second pass: generate missing operationIds
479
+ for path, path_item in paths.items():
480
+ if not isinstance(path_item, dict):
481
+ continue
482
+ for method, operation in path_item.items():
483
+ if not isinstance(operation, dict):
484
+ continue
485
+ # Skip non-operation keys
486
+ if method.lower() not in ('get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'):
487
+ continue
488
+
489
+ if operation.get('operationId'):
490
+ continue # Already has operationId
491
+
492
+ # Generate operationId
493
+ base_id = _generate_operation_id(method, path)
494
+
495
+ # Handle collisions by appending suffix
496
+ final_id = base_id
497
+ counter = 2
498
+ while final_id in used_operation_ids:
499
+ suffix = f'_{counter}'
500
+ # Ensure we don't exceed max length with suffix
501
+ max_base_len = _MAX_OPERATION_ID_LENGTH - len(suffix)
502
+ truncated_base = base_id[:max_base_len]
503
+ final_id = f'{truncated_base}{suffix}'
504
+ counter += 1
505
+
506
+ operation['operationId'] = final_id
507
+ used_operation_ids.add(final_id)
508
+ logger.debug(f"Generated operationId '{final_id}' for {method.upper()} {path}")
509
+
510
+ return spec
511
+
512
+
513
+ def _parse_openapi_spec(spec: str | dict) -> dict:
514
+ if isinstance(spec, dict):
515
+ return spec
516
+ if not isinstance(spec, str) or not spec.strip():
517
+ _raise_openapi_tool_exception(code="missing_spec", message="OpenAPI spec is required")
518
+
519
+ try:
520
+ parsed = json.loads(spec)
521
+ except json.JSONDecodeError:
522
+ try:
523
+ parsed = yaml.safe_load(spec)
524
+ except yaml.YAMLError as e:
525
+ _raise_openapi_tool_exception(
526
+ code="invalid_spec",
527
+ message=f"Failed to parse OpenAPI spec as JSON or YAML: {e}",
528
+ details={"error": str(e)},
529
+ )
530
+
531
+ if not isinstance(parsed, dict):
532
+ _raise_openapi_tool_exception(code="invalid_spec", message="OpenAPI spec must parse to an object")
533
+ return parsed
534
+
535
+
536
+ def _guess_python_type(openapi_schema: dict | None) -> type:
537
+ schema_type = (openapi_schema or {}).get("type")
538
+ if schema_type == "integer":
539
+ return int
540
+ if schema_type == "number":
541
+ return float
542
+ if schema_type == "boolean":
543
+ return bool
544
+ # arrays/objects are left as string for now (simple start)
545
+ return str
546
+
547
+
548
+ def _schema_type_hint(openapi_schema: dict | None) -> str:
549
+ if not isinstance(openapi_schema, dict):
550
+ return ""
551
+ type_ = openapi_schema.get("type")
552
+ fmt = openapi_schema.get("format")
553
+ if not type_:
554
+ return ""
555
+ if fmt:
556
+ return f"{type_} ({fmt})"
557
+ return str(type_)
558
+
559
+
560
+ def _extract_request_body_example(spec: Optional[dict], op_raw: dict) -> Optional[str]:
561
+ request_body = op_raw.get("requestBody") or {}
562
+ content = request_body.get("content") or {}
563
+ for media_type in ("application/json", "application/*+json"):
564
+ mt = content.get(media_type)
565
+ if not isinstance(mt, dict):
566
+ continue
567
+
568
+ if "example" in mt:
569
+ try:
570
+ return json.dumps(mt["example"], indent=2)
571
+ except Exception:
572
+ return str(mt["example"])
573
+
574
+ examples = mt.get("examples")
575
+ if isinstance(examples, dict) and examples:
576
+ first = next(iter(examples.values()))
577
+ if isinstance(first, dict) and "value" in first:
578
+ try:
579
+ return json.dumps(first["value"], indent=2)
580
+ except Exception:
581
+ return str(first["value"])
582
+
583
+ schema = mt.get("schema")
584
+ if isinstance(schema, dict) and "example" in schema:
585
+ try:
586
+ return json.dumps(schema["example"], indent=2)
587
+ except Exception:
588
+ return str(schema["example"])
589
+
590
+ # No explicit example found; fall back to schema-based template.
591
+ if isinstance(schema, dict):
592
+ template_obj = _schema_to_template_json(
593
+ spec=spec,
594
+ schema=schema,
595
+ max_depth=3,
596
+ max_properties=20,
597
+ )
598
+ if template_obj is not None:
599
+ try:
600
+ return json.dumps(template_obj, indent=2)
601
+ except Exception:
602
+ return str(template_obj)
603
+ return None
604
+
605
+
606
+ def _schema_to_template_json(
607
+ spec: Any,
608
+ schema: dict,
609
+ max_depth: int,
610
+ max_properties: int,
611
+ ) -> Any:
612
+ """Build a schema-shaped JSON template from an OpenAPI/JSONSchema fragment.
613
+
614
+ This is a best-effort helper intended for LLM prompting. It avoids infinite recursion
615
+ (via depth and $ref cycle checks) and prefers enum/default/example when available.
616
+ """
617
+ visited_refs: set[str] = set()
618
+ return _schema_node_to_value(
619
+ spec=spec if isinstance(spec, dict) else None,
620
+ node=schema,
621
+ depth=0,
622
+ max_depth=max_depth,
623
+ max_properties=max_properties,
624
+ visited_refs=visited_refs,
625
+ )
626
+
627
+
628
+ def _schema_node_to_value(
629
+ spec: Optional[dict],
630
+ node: Any,
631
+ depth: int,
632
+ max_depth: int,
633
+ max_properties: int,
634
+ visited_refs: set[str],
635
+ ) -> Any:
636
+ if depth > max_depth:
637
+ return "<...>"
638
+
639
+ if not isinstance(node, dict):
640
+ return "<value>"
641
+
642
+ # Prefer explicit example/default/enum at this node.
643
+ if "example" in node:
644
+ return node.get("example")
645
+ if "default" in node:
646
+ return node.get("default")
647
+ if isinstance(node.get("enum"), list) and node.get("enum"):
648
+ return node.get("enum")[0]
649
+
650
+ ref = node.get("$ref")
651
+ if isinstance(ref, str):
652
+ if ref in visited_refs:
653
+ return "<ref-cycle>"
654
+ visited_refs.add(ref)
655
+ resolved = _resolve_ref(spec, ref)
656
+ if resolved is None:
657
+ return "<ref>"
658
+ return _schema_node_to_value(
659
+ spec=spec,
660
+ node=resolved,
661
+ depth=depth + 1,
662
+ max_depth=max_depth,
663
+ max_properties=max_properties,
664
+ visited_refs=visited_refs,
665
+ )
666
+
667
+ # Combinators
668
+ for key in ("oneOf", "anyOf"):
669
+ if isinstance(node.get(key), list) and node.get(key):
670
+ return _schema_node_to_value(
671
+ spec=spec,
672
+ node=node.get(key)[0],
673
+ depth=depth + 1,
674
+ max_depth=max_depth,
675
+ max_properties=max_properties,
676
+ visited_refs=visited_refs,
677
+ )
678
+
679
+ if isinstance(node.get("allOf"), list) and node.get("allOf"):
680
+ # Best-effort merge for objects.
681
+ merged: dict = {"type": "object", "properties": {}, "required": []}
682
+ for part in node.get("allOf"):
683
+ part_resolved = _schema_node_to_value(
684
+ spec=spec,
685
+ node=part,
686
+ depth=depth + 1,
687
+ max_depth=max_depth,
688
+ max_properties=max_properties,
689
+ visited_refs=visited_refs,
690
+ )
691
+ # If a part produced an object template, merge keys.
692
+ if isinstance(part_resolved, dict):
693
+ for k, v in part_resolved.items():
694
+ merged.setdefault(k, v)
695
+ return merged
696
+
697
+ type_ = node.get("type")
698
+ fmt = node.get("format")
699
+
700
+ if type_ == "object" or (type_ is None and ("properties" in node or "additionalProperties" in node)):
701
+ props = node.get("properties") if isinstance(node.get("properties"), dict) else {}
702
+ required = node.get("required") if isinstance(node.get("required"), list) else []
703
+
704
+ out: dict[str, Any] = {}
705
+ # Prefer required fields, then a small subset of optional fields for guidance.
706
+ keys: list[str] = []
707
+ for k in required:
708
+ if isinstance(k, str) and k in props:
709
+ keys.append(k)
710
+ if not keys:
711
+ keys = list(props.keys())[: min(3, len(props))]
712
+ else:
713
+ optional = [k for k in props.keys() if k not in keys]
714
+ keys.extend(optional[: max(0, min(3, len(optional)))])
715
+
716
+ keys = keys[:max_properties]
717
+ for k in keys:
718
+ out[k] = _schema_node_to_value(
719
+ spec=spec,
720
+ node=props.get(k),
721
+ depth=depth + 1,
722
+ max_depth=max_depth,
723
+ max_properties=max_properties,
724
+ visited_refs=visited_refs,
725
+ )
726
+ return out
727
+
728
+ if type_ == "array":
729
+ items = node.get("items")
730
+ return [
731
+ _schema_node_to_value(
732
+ spec=spec,
733
+ node=items,
734
+ depth=depth + 1,
735
+ max_depth=max_depth,
736
+ max_properties=max_properties,
737
+ visited_refs=visited_refs,
738
+ )
739
+ ]
740
+
741
+ if type_ == "integer":
742
+ return 0
743
+ if type_ == "number":
744
+ return 0.0
745
+ if type_ == "boolean":
746
+ return False
747
+ if type_ == "string":
748
+ if fmt == "date-time":
749
+ return "2025-01-01T00:00:00Z"
750
+ if fmt == "date":
751
+ return "2025-01-01"
752
+ if fmt == "uuid":
753
+ return "00000000-0000-0000-0000-000000000000"
754
+ return "<string>"
755
+
756
+ # Unknown: return a placeholder
757
+ return "<value>"
758
+
759
+
760
+ def _resolve_ref(spec: Optional[dict], ref: str) -> Optional[dict]:
761
+ if not spec or not isinstance(ref, str):
762
+ return None
763
+ if not ref.startswith("#/"):
764
+ return None
765
+ # Only local refs supported for now.
766
+ parts = ref.lstrip("#/").split("/")
767
+ cur: Any = spec
768
+ for part in parts:
769
+ if not isinstance(cur, dict):
770
+ return None
771
+ cur = cur.get(part)
772
+ if isinstance(cur, dict):
773
+ return cur
774
+ return None
775
+
776
+
777
+ def _normalize_output(value: Any) -> str:
778
+ if value is None:
779
+ return ""
780
+ if isinstance(value, bytes):
781
+ try:
782
+ return value.decode("utf-8")
783
+ except Exception:
784
+ return value.decode("utf-8", errors="replace")
785
+ return str(value)
786
+
787
+
788
+ class OpenApiApiWrapper(BaseToolApiWrapper):
789
+ """Builds callable tool functions for OpenAPI operations and executes them."""
790
+
791
+ spec: dict = Field(description="Parsed OpenAPI spec")
792
+ base_headers: dict[str, str] = Field(default_factory=dict)
793
+
794
+ _client: Client = PrivateAttr()
795
+ _op_meta: dict[str, dict] = PrivateAttr(default_factory=dict)
796
+ _tool_defs: list[dict[str, Any]] = PrivateAttr(default_factory=list)
797
+ _tool_ref_by_name: dict[str, Callable[..., str]] = PrivateAttr(default_factory=dict)
798
+ # Mapping: operation_id -> {sanitized_field_name: original_param_name}
799
+ # Needed because LangChain passes kwargs using Pydantic field names (sanitized),
800
+ # but the API expects original parameter names
801
+ _param_name_mapping: dict[str, dict[str, str]] = PrivateAttr(default_factory=dict)
802
+ # Stores unresolved server variable info for deferred error reporting
803
+ # If set, any tool execution will fail with a helpful error message
804
+ _unresolved_server_vars: Optional[dict] = PrivateAttr(default=None)
805
+
806
+ def model_post_init(self, __context: Any) -> None:
807
+ # Resolve server variables in spec URLs before loading
808
+ # This handles specs like Azure DevOps that use {organization}/{project} placeholders
809
+ # If variables can't be resolved, we store the info and defer the error to execution time
810
+ _, self._unresolved_server_vars = _resolve_server_variables_in_spec(self.spec)
811
+
812
+ # Build meta from raw spec (method/path/examples)
813
+ op_meta: dict[str, dict] = {}
814
+ paths = self.spec.get("paths") or {}
815
+ if isinstance(paths, dict):
816
+ for path, path_item in paths.items():
817
+ if not isinstance(path_item, dict):
818
+ continue
819
+ for method, op_raw in path_item.items():
820
+ if not isinstance(op_raw, dict):
821
+ continue
822
+ operation_id = op_raw.get("operationId")
823
+ if not operation_id:
824
+ continue
825
+ op_meta[str(operation_id)] = {
826
+ "method": str(method).upper(),
827
+ "path": str(path),
828
+ "raw": op_raw,
829
+ }
830
+
831
+ client = Client()
832
+ client.load_spec(self.spec)
833
+ if self.base_headers:
834
+ client.requestor.headers.update({str(k): str(v) for k, v in self.base_headers.items()})
835
+
836
+ self._client = client
837
+ self._op_meta = op_meta
838
+
839
+ # Build tool definitions once.
840
+ self._tool_defs = self._build_tool_defs()
841
+ self._tool_ref_by_name = {t["name"]: t["ref"] for t in self._tool_defs if "ref" in t}
842
+
843
+ def _build_tool_defs(self) -> list[dict[str, Any]]:
844
+ tool_defs: list[dict[str, Any]] = []
845
+ for operation_id, op in getattr(self._client, "operations", {}).items():
846
+ if not isinstance(op, Operation):
847
+ continue
848
+ op_id = str(operation_id)
849
+ meta = self._op_meta.get(op_id, {})
850
+ op_raw = meta.get("raw") if isinstance(meta.get("raw"), dict) else {}
851
+
852
+ method = meta.get("method")
853
+ path = meta.get("path")
854
+
855
+ title_line = ""
856
+ if method and path:
857
+ title_line = f"{method} {path}"
858
+
859
+ summary = op.spec.summary or ""
860
+ description = op.spec.description or ""
861
+ tool_desc_parts = [p for p in [title_line, summary, description] if p]
862
+
863
+ has_request_body = bool(op.spec.requestBody)
864
+ usage_lines: list[str] = ["How to call:"]
865
+ usage_lines.append("- Provide path/query parameters as named arguments.")
866
+ if has_request_body:
867
+ usage_lines.append("- For JSON request bodies, pass `body_json` as a JSON string.")
868
+ usage_lines.append(
869
+ "- Use `headers` only for per-call extra headers; base/toolkit headers (including auth) are already applied."
870
+ )
871
+ tool_desc_parts.append("\n".join(usage_lines))
872
+
873
+ args_schema = self._create_args_schema(op_id, op, op_raw)
874
+ ref = self._make_operation_callable(op_id)
875
+
876
+ tool_defs.append(
877
+ {
878
+ "name": op_id,
879
+ "description": "\n".join(tool_desc_parts).strip(),
880
+ "args_schema": args_schema,
881
+ "ref": ref,
882
+ }
883
+ )
884
+ return tool_defs
885
+
886
+ def _make_operation_callable(self, operation_id: str) -> Callable[..., str]:
887
+ def _call_operation(*args: Any, **kwargs: Any) -> str:
888
+ return self._execute(operation_id, *args, **kwargs)
889
+
890
+ return _call_operation
891
+
892
+ def _create_args_schema(self, operation_id: str, op: Operation, op_raw: dict) -> type[BaseModel]:
893
+ fields: dict[str, tuple[Any, Any]] = {}
894
+ # Track sanitized -> original name mapping for this operation
895
+ name_mapping: dict[str, str] = {}
896
+
897
+ # Parameters
898
+ raw_params = op_raw.get("parameters") or []
899
+ raw_param_map: dict[tuple[str, str], dict] = {}
900
+ if isinstance(raw_params, list):
901
+ for p in raw_params:
902
+ if isinstance(p, dict) and p.get("name") and p.get("in"):
903
+ raw_param_map[(str(p.get("name")), str(p.get("in")))] = p
904
+
905
+ for param in op.spec.parameters or []:
906
+ param_name = str(param.name)
907
+ # Sanitize parameter name for Pydantic field (handles dots, $ prefix, etc.)
908
+ sanitized_name = _sanitize_param_name(param_name)
909
+ # Track if we need alias (original name differs from sanitized)
910
+ needs_alias = sanitized_name != param_name
911
+ if needs_alias:
912
+ # Store mapping for restoring original names in _execute
913
+ name_mapping[sanitized_name] = param_name
914
+ logger.debug(
915
+ f"Using alias for parameter '{param_name}' (field name: '{sanitized_name}') for operation '{operation_id}'")
916
+
917
+ param_in_obj = getattr(param, "param_in", None)
918
+ # requests_openapi uses an enum-like value for `param_in`.
919
+ # For prompt quality and stable matching against raw spec, normalize to e.g. "query".
920
+ if hasattr(param_in_obj, "value"):
921
+ param_in = str(getattr(param_in_obj, "value"))
922
+ else:
923
+ param_in = str(param_in_obj)
924
+ raw_param = raw_param_map.get((param_name, param_in), {})
925
+
926
+ required = bool(raw_param.get("required", False))
927
+ schema = raw_param.get("schema") if isinstance(raw_param.get("schema"), dict) else None
928
+ py_type = _guess_python_type(schema)
929
+
930
+ example = raw_param.get("example")
931
+ if example is None and isinstance(schema, dict):
932
+ example = schema.get("example")
933
+
934
+ default = getattr(param.param_schema, "default", None)
935
+ # Build description
936
+ desc = (param.description or "").strip()
937
+ desc = f"({param_in}) {desc}".strip()
938
+ type_hint = _schema_type_hint(schema)
939
+ if type_hint:
940
+ desc = f"{desc}\nType: {type_hint}".strip()
941
+ if required:
942
+ desc = f"{desc}\nRequired: true".strip()
943
+ if example is not None:
944
+ desc = f"{desc}\nExample: {example}".strip()
945
+ if default is not None:
946
+ desc = f"{desc}\nDefault: {default}".strip()
947
+
948
+ # Build Field kwargs - use alias if name was sanitized so schema shows original name
949
+ field_kwargs = {"description": desc}
950
+ if needs_alias:
951
+ # Use alias so JSON schema shows original param name (e.g., "$top", "searchCriteria.status")
952
+ # and Pydantic accepts input using original name
953
+ field_kwargs["alias"] = param_name
954
+
955
+ # Required fields have no default. Use sanitized name for field.
956
+ if required:
957
+ fields[sanitized_name] = (py_type, Field(**field_kwargs))
958
+ else:
959
+ field_kwargs["default"] = default
960
+ fields[sanitized_name] = (Optional[py_type], Field(**field_kwargs))
961
+
962
+ # Additional headers not modeled in spec
963
+ # Use Annotated with BeforeValidator to coerce empty strings and JSON strings to dict
964
+ fields["headers"] = (
965
+ Annotated[Optional[dict], BeforeValidator(_coerce_headers_value)],
966
+ Field(
967
+ default_factory=dict,
968
+ description=(
969
+ "Additional HTTP headers to include in this request. "
970
+ "These are merged with the toolkit/base headers (including auth headers). "
971
+ "Only add headers if the API requires them. "
972
+ "Provide a JSON object/dict. Example: {\"X-Trace-Id\": \"123\"}"
973
+ ),
974
+ ),
975
+ )
976
+
977
+ # Request body
978
+ request_body = op_raw.get("requestBody") if isinstance(op_raw.get("requestBody"), dict) else None
979
+ body_required = bool((request_body or {}).get("required", False))
980
+ body_example = _extract_request_body_example(self.spec, op_raw)
981
+ body_desc = (
982
+ "Request body (JSON) as a string. The tool will parse it with json.loads and send as the request JSON body."
983
+ )
984
+ if body_example:
985
+ body_desc = f"{body_desc}\nExample JSON:\n{body_example}"
986
+ if op.spec.requestBody:
987
+ if body_required:
988
+ fields["body_json"] = (str, Field(description=body_desc))
989
+ else:
990
+ # Use BeforeValidator to coerce empty strings to None for optional body_json
991
+ fields["body_json"] = (
992
+ Annotated[Optional[str], BeforeValidator(_coerce_empty_string_to_none)],
993
+ Field(default=None, description=body_desc),
994
+ )
995
+
996
+ model_name = f"OpenApi_{clean_string(operation_id, max_length=40) or 'Operation'}_Params"
997
+
998
+ # Store the mapping for this operation (needed to restore original names in _execute)
999
+ if name_mapping:
1000
+ self._param_name_mapping[operation_id] = name_mapping
1001
+
1002
+ return create_model(
1003
+ model_name,
1004
+ __base__=_BaseParamsModel,
1005
+ # Use BeforeValidator to coerce empty strings to None for optional regexp
1006
+ regexp=(
1007
+ Annotated[Optional[str], BeforeValidator(_coerce_empty_string_to_none)],
1008
+ Field(
1009
+ description="Regular expression to remove from the final output (optional)",
1010
+ default=None,
1011
+ ),
1012
+ ),
1013
+ **fields,
1014
+ )
1015
+
1016
+ def get_available_tools(self, selected_tools: Optional[list[str]] = None) -> list[dict[str, Any]]:
1017
+ if not selected_tools:
1018
+ return list(self._tool_defs)
1019
+ selected_set = {t for t in selected_tools if isinstance(t, str) and t}
1020
+ return [t for t in self._tool_defs if t.get("name") in selected_set]
1021
+
1022
+ def run(self, mode: str, *args: Any, **kwargs: Any) -> str:
1023
+ try:
1024
+ ref = self._tool_ref_by_name[mode]
1025
+ except KeyError:
1026
+ _raise_openapi_tool_exception(
1027
+ code="unknown_operation",
1028
+ message=f"Unknown operation: {mode}",
1029
+ details={"known_operations": sorted(list(self._tool_ref_by_name.keys()))[:200]},
1030
+ )
1031
+ return ref(*args, **kwargs)
1032
+
1033
+ def _get_required_inputs_from_raw_spec(self, operation_id: str) -> dict[str, Any]:
1034
+ meta = self._op_meta.get(str(operation_id), {})
1035
+ op_raw = meta.get("raw") if isinstance(meta, dict) and isinstance(meta.get("raw"), dict) else {}
1036
+
1037
+ required_path: list[str] = []
1038
+ required_query: list[str] = []
1039
+ raw_params = op_raw.get("parameters")
1040
+ if isinstance(raw_params, list):
1041
+ for p in raw_params:
1042
+ if not isinstance(p, dict):
1043
+ continue
1044
+ name = p.get("name")
1045
+ where = p.get("in")
1046
+ required = bool(p.get("required", False))
1047
+ if not required or not isinstance(name, str) or not isinstance(where, str):
1048
+ continue
1049
+ if where == "path":
1050
+ required_path.append(name)
1051
+ elif where == "query":
1052
+ required_query.append(name)
1053
+
1054
+ req_body = False
1055
+ rb = op_raw.get("requestBody")
1056
+ if isinstance(rb, dict):
1057
+ req_body = bool(rb.get("required", False))
1058
+
1059
+ return {
1060
+ "required_path": required_path,
1061
+ "required_query": required_query,
1062
+ "required_body": req_body,
1063
+ }
1064
+
1065
+ def get_operation_request_url(self, operation_id: str, params: dict[str, Any]) -> str:
1066
+ """Best-effort resolved URL for debugging/prompt-quality inspection.
1067
+
1068
+ This does not execute the request.
1069
+ """
1070
+ meta = self._op_meta.get(str(operation_id), {})
1071
+ path = meta.get("path") if isinstance(meta, dict) else None
1072
+ if not isinstance(path, str):
1073
+ return ""
1074
+ base_url = _get_base_url_from_spec(self.spec)
1075
+ url = _join_base_and_path(base_url, path)
1076
+
1077
+ # Substitute {pathParams}
1078
+ for k, v in (params or {}).items():
1079
+ placeholder = "{" + str(k) + "}"
1080
+ if placeholder in url:
1081
+ url = url.replace(placeholder, str(v))
1082
+
1083
+ # Add query params if present.
1084
+ query: dict[str, Any] = {}
1085
+ try:
1086
+ op = self._client.operations[str(operation_id)]
1087
+ if isinstance(op, Operation):
1088
+ for p in op.spec.parameters or []:
1089
+ p_in_obj = getattr(p, "param_in", None)
1090
+ p_in = str(getattr(p_in_obj, "value", p_in_obj))
1091
+ if p_in != "query":
1092
+ continue
1093
+ name = str(p.name)
1094
+ if name in (params or {}) and (params or {}).get(name) is not None:
1095
+ query[name] = (params or {})[name]
1096
+ except Exception:
1097
+ query = {}
1098
+
1099
+ if query:
1100
+ url = url + "?" + urlencode(query, doseq=True)
1101
+ return url
1102
+
1103
+ def _execute(self, operation_id: str, *args: Any, **kwargs: Any) -> str:
1104
+ # Check for unresolved server variables - fail early with helpful error
1105
+ if self._unresolved_server_vars:
1106
+ self._raise_unresolved_server_vars_error(operation_id)
1107
+
1108
+ # Extract special fields (already coerced by BeforeValidator at validation time)
1109
+ regexp = kwargs.pop("regexp", None)
1110
+ extra_headers = kwargs.pop("headers", None)
1111
+
1112
+ # Restore original parameter names from sanitized field names
1113
+ # LangChain passes kwargs using Pydantic field names (sanitized like 'dollar_top'),
1114
+ # but the API expects original parameter names (like '$top')
1115
+ name_mapping = self._param_name_mapping.get(operation_id, {})
1116
+ if name_mapping:
1117
+ restored_kwargs: dict[str, Any] = {}
1118
+ for key, value in kwargs.items():
1119
+ original_name = name_mapping.get(key, key)
1120
+ restored_kwargs[original_name] = value
1121
+ kwargs = restored_kwargs
1122
+
1123
+ # Validate headers type (should be dict or None after BeforeValidator coercion)
1124
+ if extra_headers is not None and not isinstance(extra_headers, dict):
1125
+ _raise_openapi_tool_exception(
1126
+ code="invalid_headers",
1127
+ message="'headers' must be a dict or valid JSON object string",
1128
+ operation_id=str(operation_id),
1129
+ details={"provided_type": str(type(extra_headers)), "provided_value": str(extra_headers)[:100]},
1130
+ )
1131
+
1132
+ # Handle body_json (already coerced to None for empty strings by BeforeValidator)
1133
+ body_json = kwargs.pop("body_json", None)
1134
+ if body_json is not None:
1135
+ if isinstance(body_json, str):
1136
+ try:
1137
+ kwargs["json"] = json.loads(body_json)
1138
+ except Exception as e:
1139
+ _raise_openapi_tool_exception(
1140
+ code="invalid_json_body",
1141
+ message=f"Invalid JSON body: {e}",
1142
+ operation_id=str(operation_id),
1143
+ details={"hint": "Ensure body_json is valid JSON (double quotes, no trailing commas)."},
1144
+ )
1145
+ else:
1146
+ kwargs["json"] = body_json
1147
+
1148
+ # Backward compatible: accept `json` as a string too.
1149
+ if "json" in kwargs and isinstance(kwargs.get("json"), str):
1150
+ try:
1151
+ kwargs["json"] = json.loads(kwargs["json"])
1152
+ except Exception as e:
1153
+ _raise_openapi_tool_exception(
1154
+ code="invalid_json_body",
1155
+ message=f"Invalid JSON body: {e}",
1156
+ operation_id=str(operation_id),
1157
+ details={"hint": "If you pass `json` as a string, it must be valid JSON."},
1158
+ )
1159
+
1160
+ try:
1161
+ op = self._client.operations[operation_id]
1162
+ except Exception:
1163
+ _raise_openapi_tool_exception(
1164
+ code="operation_not_found",
1165
+ message=f"Operation '{operation_id}' not found in OpenAPI spec",
1166
+ operation_id=str(operation_id),
1167
+ )
1168
+ if not isinstance(op, Operation):
1169
+ _raise_openapi_tool_exception(
1170
+ code="invalid_operation",
1171
+ message=f"Operation '{operation_id}' is not a valid OpenAPI operation",
1172
+ operation_id=str(operation_id),
1173
+ )
1174
+
1175
+ # Best-effort URL reconstruction for error context.
1176
+ debug_url = ""
1177
+ try:
1178
+ debug_url = self.get_operation_request_url(operation_id, dict(kwargs))
1179
+ except Exception:
1180
+ debug_url = ""
1181
+
1182
+ # Preflight required input checks (helps LLM recover without needing spec knowledge).
1183
+ missing: list[str] = []
1184
+ required_info = self._get_required_inputs_from_raw_spec(str(operation_id))
1185
+ for name in required_info.get("required_path", []) or []:
1186
+ if name not in kwargs or kwargs.get(name) is None:
1187
+ missing.append(name)
1188
+ for name in required_info.get("required_query", []) or []:
1189
+ if name not in kwargs or kwargs.get(name) is None:
1190
+ missing.append(name)
1191
+ if bool(required_info.get("required_body")) and kwargs.get("json") is None:
1192
+ missing.append("body_json")
1193
+
1194
+ # Also check for unresolved {param} placeholders in the path.
1195
+ meta = self._op_meta.get(str(operation_id), {})
1196
+ path = meta.get("path") if isinstance(meta, dict) else None
1197
+ if isinstance(path, str):
1198
+ for placeholder in re.findall(r"\{([^}]+)\}", path):
1199
+ if placeholder and (placeholder not in kwargs or kwargs.get(placeholder) is None):
1200
+ missing.append(str(placeholder))
1201
+
1202
+ if missing:
1203
+ _raise_openapi_tool_exception(
1204
+ code="missing_required_inputs",
1205
+ message=f"Missing required inputs for operation '{operation_id}': {', '.join(sorted(set(missing)))}",
1206
+ operation_id=str(operation_id),
1207
+ url=debug_url or None,
1208
+ retryable=True,
1209
+ missing_inputs=sorted(set(missing)),
1210
+ details={"hint": "Provide the missing fields and retry the same operation."},
1211
+ )
1212
+
1213
+ # Preflight base URL check: requests_openapi needs an absolute server URL to execute HTTP.
1214
+ base_url = _get_base_url_from_spec(self.spec)
1215
+ if not base_url or not _is_absolute_url(base_url):
1216
+ servers = self.spec.get("servers") if isinstance(self.spec, dict) else None
1217
+ server_url = None
1218
+ if isinstance(servers, list) and servers and isinstance(servers[0], dict):
1219
+ server_url = servers[0].get("url")
1220
+
1221
+ _raise_openapi_tool_exception(
1222
+ code="missing_base_url",
1223
+ message=(
1224
+ "Cannot execute HTTP request because the OpenAPI spec does not contain an absolute server URL. "
1225
+ "Provide `base_url_override`/`base_url` in the toolkit settings (e.g. 'https://host') "
1226
+ "or update `servers[0].url` to an absolute URL (https://...)."
1227
+ ),
1228
+ operation_id=str(operation_id),
1229
+ url=debug_url or None,
1230
+ retryable=False,
1231
+ details={
1232
+ "servers_0_url": server_url,
1233
+ "computed_base_url": base_url,
1234
+ "hint": "If servers[0].url is relative like '/api/v3', set base_url_override to the host (e.g. 'https://petstore3.swagger.io').",
1235
+ },
1236
+ )
1237
+
1238
+ # Apply per-call extra headers (best-effort) without permanently mutating global headers.
1239
+ old_headers = dict(getattr(self._client.requestor, "headers", {}) or {})
1240
+ try:
1241
+ if extra_headers:
1242
+ self._client.requestor.headers.update({str(k): str(v) for k, v in extra_headers.items()})
1243
+ response = op(*args, **kwargs)
1244
+ except Exception as e:
1245
+ _raise_openapi_tool_exception(
1246
+ code="request_failed",
1247
+ message=f"OpenAPI request failed for operation '{operation_id}': {e}",
1248
+ operation_id=str(operation_id),
1249
+ url=debug_url or None,
1250
+ retryable=True,
1251
+ details={"exception": repr(e)},
1252
+ )
1253
+ finally:
1254
+ try:
1255
+ self._client.requestor.headers.clear()
1256
+ self._client.requestor.headers.update(old_headers)
1257
+ except Exception:
1258
+ pass
1259
+
1260
+ # If this looks like a requests.Response, raise on HTTP errors with actionable context.
1261
+ status_code = getattr(response, "status_code", None)
1262
+ if isinstance(status_code, int) and status_code >= 400:
1263
+ body_preview = ""
1264
+ for attr in ("text", "content", "data"):
1265
+ if hasattr(response, attr):
1266
+ body_preview = _normalize_output(getattr(response, attr))
1267
+ break
1268
+ body_preview = _truncate(body_preview, 2000)
1269
+ retryable = _is_retryable_http_status(status_code)
1270
+
1271
+ hint = ""
1272
+ if status_code in (401, 403):
1273
+ hint = "Authentication/authorization failed. Verify toolkit authentication settings / base headers."
1274
+ elif status_code == 404:
1275
+ hint = "Resource not found. Check path parameters and identifiers."
1276
+ elif status_code == 400:
1277
+ hint = "Bad request. Check required parameters and request body schema."
1278
+ elif status_code == 415:
1279
+ hint = "Unsupported media type. The API may require Content-Type headers."
1280
+ elif status_code == 429:
1281
+ hint = "Rate limited. Retry after a short delay."
1282
+
1283
+ _raise_openapi_tool_exception(
1284
+ code="http_error",
1285
+ message=f"OpenAPI request failed with HTTP {status_code} for operation '{operation_id}'",
1286
+ operation_id=str(operation_id),
1287
+ url=debug_url or None,
1288
+ retryable=retryable,
1289
+ http_status=status_code,
1290
+ http_body_preview=body_preview,
1291
+ details={"hint": hint} if hint else None,
1292
+ )
1293
+
1294
+ output = None
1295
+ for attr in ("content", "data", "text"):
1296
+ if hasattr(response, attr):
1297
+ output = getattr(response, attr)
1298
+ break
1299
+ if output is None:
1300
+ output = response
1301
+
1302
+ output_str = _normalize_output(output)
1303
+
1304
+ if regexp:
1305
+ try:
1306
+ output_str = re.sub(rf"{regexp}", "", output_str)
1307
+ except Exception as e:
1308
+ logger.debug(f"Failed to apply regexp filter: {e}")
1309
+
1310
+ return output_str
1311
+
1312
+ def _raise_unresolved_server_vars_error(self, operation_id: str) -> None:
1313
+ """Raise a detailed error for unresolved server variables with YAML/JSON examples."""
1314
+ info = self._unresolved_server_vars
1315
+ if not info:
1316
+ return
1317
+
1318
+ url = info.get("url", "")
1319
+ missing_vars = info.get("missing_vars", [])
1320
+ server_index = info.get("server_index", 0)
1321
+
1322
+ # Build example snippets showing how to fix the spec
1323
+ yaml_vars = '\n'.join(f' {v}:\n default: "your_{v}_value"' for v in missing_vars)
1324
+ json_vars = ', '.join(f'"{v}": {{"default": "your_{v}_value"}}' for v in missing_vars)
1325
+ var_list = ', '.join(f'"{v}"' for v in missing_vars)
1326
+
1327
+ _raise_openapi_tool_exception(
1328
+ code="unresolved_server_variables",
1329
+ message=(
1330
+ f"Server URL contains variables without default values: {var_list}.\n\n"
1331
+ f"The OpenAPI spec defines server URL:\n"
1332
+ f" {url}\n\n"
1333
+ f"These variables must have default values. Update your OpenAPI spec as follows:\n\n"
1334
+ f"YAML format:\n"
1335
+ f" servers:\n"
1336
+ f" - url: \"{url}\"\n"
1337
+ f" variables:\n"
1338
+ f"{yaml_vars}\n\n"
1339
+ f"JSON format:\n"
1340
+ f" {{\n"
1341
+ f" \"servers\": [{{\n"
1342
+ f" \"url\": \"{url}\",\n"
1343
+ f" \"variables\": {{ {json_vars} }}\n"
1344
+ f" }}]\n"
1345
+ f" }}"
1346
+ ),
1347
+ operation_id=str(operation_id),
1348
+ details={
1349
+ "server_url": url,
1350
+ "missing_variables": missing_vars,
1351
+ "server_index": server_index,
1352
+ },
1353
+ )
1354
+
1355
+
1356
+ def build_wrapper(
1357
+ openapi_spec: str | dict,
1358
+ base_headers: Optional[dict[str, str]] = None,
1359
+ base_url_override: Optional[str] = None,
1360
+ ) -> OpenApiApiWrapper:
1361
+ parsed = _parse_openapi_spec(openapi_spec)
1362
+ # Avoid mutating caller-owned spec dict.
1363
+ spec = copy.deepcopy(parsed)
1364
+ if base_url_override:
1365
+ spec = _apply_base_url_override(spec, base_url_override)
1366
+ # Ensure all operations have operationIds (generate from method+path if missing)
1367
+ spec = _ensure_operation_ids(spec)
1368
+ return OpenApiApiWrapper(spec=spec, base_headers=base_headers or {})