alita-sdk 0.3.379__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 (278) hide show
  1. alita_sdk/cli/__init__.py +10 -0
  2. alita_sdk/cli/__main__.py +17 -0
  3. alita_sdk/cli/agent/__init__.py +5 -0
  4. alita_sdk/cli/agent/default.py +258 -0
  5. alita_sdk/cli/agent_executor.py +156 -0
  6. alita_sdk/cli/agent_loader.py +245 -0
  7. alita_sdk/cli/agent_ui.py +228 -0
  8. alita_sdk/cli/agents.py +3113 -0
  9. alita_sdk/cli/callbacks.py +647 -0
  10. alita_sdk/cli/cli.py +168 -0
  11. alita_sdk/cli/config.py +306 -0
  12. alita_sdk/cli/context/__init__.py +30 -0
  13. alita_sdk/cli/context/cleanup.py +198 -0
  14. alita_sdk/cli/context/manager.py +731 -0
  15. alita_sdk/cli/context/message.py +285 -0
  16. alita_sdk/cli/context/strategies.py +289 -0
  17. alita_sdk/cli/context/token_estimation.py +127 -0
  18. alita_sdk/cli/formatting.py +182 -0
  19. alita_sdk/cli/input_handler.py +419 -0
  20. alita_sdk/cli/inventory.py +1073 -0
  21. alita_sdk/cli/mcp_loader.py +315 -0
  22. alita_sdk/cli/testcases/__init__.py +94 -0
  23. alita_sdk/cli/testcases/data_generation.py +119 -0
  24. alita_sdk/cli/testcases/discovery.py +96 -0
  25. alita_sdk/cli/testcases/executor.py +84 -0
  26. alita_sdk/cli/testcases/logger.py +85 -0
  27. alita_sdk/cli/testcases/parser.py +172 -0
  28. alita_sdk/cli/testcases/prompts.py +91 -0
  29. alita_sdk/cli/testcases/reporting.py +125 -0
  30. alita_sdk/cli/testcases/setup.py +108 -0
  31. alita_sdk/cli/testcases/test_runner.py +282 -0
  32. alita_sdk/cli/testcases/utils.py +39 -0
  33. alita_sdk/cli/testcases/validation.py +90 -0
  34. alita_sdk/cli/testcases/workflow.py +196 -0
  35. alita_sdk/cli/toolkit.py +327 -0
  36. alita_sdk/cli/toolkit_loader.py +85 -0
  37. alita_sdk/cli/tools/__init__.py +43 -0
  38. alita_sdk/cli/tools/approval.py +224 -0
  39. alita_sdk/cli/tools/filesystem.py +1751 -0
  40. alita_sdk/cli/tools/planning.py +389 -0
  41. alita_sdk/cli/tools/terminal.py +414 -0
  42. alita_sdk/community/__init__.py +72 -12
  43. alita_sdk/community/inventory/__init__.py +236 -0
  44. alita_sdk/community/inventory/config.py +257 -0
  45. alita_sdk/community/inventory/enrichment.py +2137 -0
  46. alita_sdk/community/inventory/extractors.py +1469 -0
  47. alita_sdk/community/inventory/ingestion.py +3172 -0
  48. alita_sdk/community/inventory/knowledge_graph.py +1457 -0
  49. alita_sdk/community/inventory/parsers/__init__.py +218 -0
  50. alita_sdk/community/inventory/parsers/base.py +295 -0
  51. alita_sdk/community/inventory/parsers/csharp_parser.py +907 -0
  52. alita_sdk/community/inventory/parsers/go_parser.py +851 -0
  53. alita_sdk/community/inventory/parsers/html_parser.py +389 -0
  54. alita_sdk/community/inventory/parsers/java_parser.py +593 -0
  55. alita_sdk/community/inventory/parsers/javascript_parser.py +629 -0
  56. alita_sdk/community/inventory/parsers/kotlin_parser.py +768 -0
  57. alita_sdk/community/inventory/parsers/markdown_parser.py +362 -0
  58. alita_sdk/community/inventory/parsers/python_parser.py +604 -0
  59. alita_sdk/community/inventory/parsers/rust_parser.py +858 -0
  60. alita_sdk/community/inventory/parsers/swift_parser.py +832 -0
  61. alita_sdk/community/inventory/parsers/text_parser.py +322 -0
  62. alita_sdk/community/inventory/parsers/yaml_parser.py +370 -0
  63. alita_sdk/community/inventory/patterns/__init__.py +61 -0
  64. alita_sdk/community/inventory/patterns/ast_adapter.py +380 -0
  65. alita_sdk/community/inventory/patterns/loader.py +348 -0
  66. alita_sdk/community/inventory/patterns/registry.py +198 -0
  67. alita_sdk/community/inventory/presets.py +535 -0
  68. alita_sdk/community/inventory/retrieval.py +1403 -0
  69. alita_sdk/community/inventory/toolkit.py +173 -0
  70. alita_sdk/community/inventory/toolkit_utils.py +176 -0
  71. alita_sdk/community/inventory/visualize.py +1370 -0
  72. alita_sdk/configurations/__init__.py +1 -1
  73. alita_sdk/configurations/ado.py +141 -20
  74. alita_sdk/configurations/bitbucket.py +94 -2
  75. alita_sdk/configurations/confluence.py +130 -1
  76. alita_sdk/configurations/figma.py +76 -0
  77. alita_sdk/configurations/gitlab.py +91 -0
  78. alita_sdk/configurations/jira.py +103 -0
  79. alita_sdk/configurations/openapi.py +329 -0
  80. alita_sdk/configurations/qtest.py +72 -1
  81. alita_sdk/configurations/report_portal.py +96 -0
  82. alita_sdk/configurations/sharepoint.py +148 -0
  83. alita_sdk/configurations/testio.py +83 -0
  84. alita_sdk/configurations/testrail.py +88 -0
  85. alita_sdk/configurations/xray.py +93 -0
  86. alita_sdk/configurations/zephyr_enterprise.py +93 -0
  87. alita_sdk/configurations/zephyr_essential.py +75 -0
  88. alita_sdk/runtime/clients/artifact.py +3 -3
  89. alita_sdk/runtime/clients/client.py +388 -46
  90. alita_sdk/runtime/clients/mcp_discovery.py +342 -0
  91. alita_sdk/runtime/clients/mcp_manager.py +262 -0
  92. alita_sdk/runtime/clients/sandbox_client.py +8 -21
  93. alita_sdk/runtime/langchain/_constants_bkup.py +1318 -0
  94. alita_sdk/runtime/langchain/assistant.py +157 -39
  95. alita_sdk/runtime/langchain/constants.py +647 -1
  96. alita_sdk/runtime/langchain/document_loaders/AlitaDocxMammothLoader.py +315 -3
  97. alita_sdk/runtime/langchain/document_loaders/AlitaExcelLoader.py +103 -60
  98. alita_sdk/runtime/langchain/document_loaders/AlitaJSONLinesLoader.py +77 -0
  99. alita_sdk/runtime/langchain/document_loaders/AlitaJSONLoader.py +10 -4
  100. alita_sdk/runtime/langchain/document_loaders/AlitaPowerPointLoader.py +226 -7
  101. alita_sdk/runtime/langchain/document_loaders/AlitaTextLoader.py +5 -2
  102. alita_sdk/runtime/langchain/document_loaders/constants.py +40 -19
  103. alita_sdk/runtime/langchain/langraph_agent.py +405 -84
  104. alita_sdk/runtime/langchain/utils.py +106 -7
  105. alita_sdk/runtime/llms/preloaded.py +2 -6
  106. alita_sdk/runtime/models/mcp_models.py +61 -0
  107. alita_sdk/runtime/skills/__init__.py +91 -0
  108. alita_sdk/runtime/skills/callbacks.py +498 -0
  109. alita_sdk/runtime/skills/discovery.py +540 -0
  110. alita_sdk/runtime/skills/executor.py +610 -0
  111. alita_sdk/runtime/skills/input_builder.py +371 -0
  112. alita_sdk/runtime/skills/models.py +330 -0
  113. alita_sdk/runtime/skills/registry.py +355 -0
  114. alita_sdk/runtime/skills/skill_runner.py +330 -0
  115. alita_sdk/runtime/toolkits/__init__.py +31 -0
  116. alita_sdk/runtime/toolkits/application.py +29 -10
  117. alita_sdk/runtime/toolkits/artifact.py +20 -11
  118. alita_sdk/runtime/toolkits/datasource.py +13 -6
  119. alita_sdk/runtime/toolkits/mcp.py +783 -0
  120. alita_sdk/runtime/toolkits/mcp_config.py +1048 -0
  121. alita_sdk/runtime/toolkits/planning.py +178 -0
  122. alita_sdk/runtime/toolkits/skill_router.py +238 -0
  123. alita_sdk/runtime/toolkits/subgraph.py +251 -6
  124. alita_sdk/runtime/toolkits/tools.py +356 -69
  125. alita_sdk/runtime/toolkits/vectorstore.py +11 -5
  126. alita_sdk/runtime/tools/__init__.py +10 -3
  127. alita_sdk/runtime/tools/application.py +27 -6
  128. alita_sdk/runtime/tools/artifact.py +511 -28
  129. alita_sdk/runtime/tools/data_analysis.py +183 -0
  130. alita_sdk/runtime/tools/function.py +67 -35
  131. alita_sdk/runtime/tools/graph.py +10 -4
  132. alita_sdk/runtime/tools/image_generation.py +148 -46
  133. alita_sdk/runtime/tools/llm.py +1003 -128
  134. alita_sdk/runtime/tools/loop.py +3 -1
  135. alita_sdk/runtime/tools/loop_output.py +3 -1
  136. alita_sdk/runtime/tools/mcp_inspect_tool.py +284 -0
  137. alita_sdk/runtime/tools/mcp_remote_tool.py +181 -0
  138. alita_sdk/runtime/tools/mcp_server_tool.py +8 -5
  139. alita_sdk/runtime/tools/planning/__init__.py +36 -0
  140. alita_sdk/runtime/tools/planning/models.py +246 -0
  141. alita_sdk/runtime/tools/planning/wrapper.py +607 -0
  142. alita_sdk/runtime/tools/router.py +2 -4
  143. alita_sdk/runtime/tools/sandbox.py +65 -48
  144. alita_sdk/runtime/tools/skill_router.py +776 -0
  145. alita_sdk/runtime/tools/tool.py +3 -1
  146. alita_sdk/runtime/tools/vectorstore.py +9 -3
  147. alita_sdk/runtime/tools/vectorstore_base.py +70 -14
  148. alita_sdk/runtime/utils/AlitaCallback.py +137 -21
  149. alita_sdk/runtime/utils/constants.py +5 -1
  150. alita_sdk/runtime/utils/mcp_client.py +492 -0
  151. alita_sdk/runtime/utils/mcp_oauth.py +361 -0
  152. alita_sdk/runtime/utils/mcp_sse_client.py +434 -0
  153. alita_sdk/runtime/utils/mcp_tools_discovery.py +124 -0
  154. alita_sdk/runtime/utils/serialization.py +155 -0
  155. alita_sdk/runtime/utils/streamlit.py +40 -13
  156. alita_sdk/runtime/utils/toolkit_utils.py +30 -9
  157. alita_sdk/runtime/utils/utils.py +36 -0
  158. alita_sdk/tools/__init__.py +134 -35
  159. alita_sdk/tools/ado/repos/__init__.py +51 -32
  160. alita_sdk/tools/ado/repos/repos_wrapper.py +148 -89
  161. alita_sdk/tools/ado/test_plan/__init__.py +25 -9
  162. alita_sdk/tools/ado/test_plan/test_plan_wrapper.py +23 -1
  163. alita_sdk/tools/ado/utils.py +1 -18
  164. alita_sdk/tools/ado/wiki/__init__.py +25 -12
  165. alita_sdk/tools/ado/wiki/ado_wrapper.py +291 -22
  166. alita_sdk/tools/ado/work_item/__init__.py +26 -13
  167. alita_sdk/tools/ado/work_item/ado_wrapper.py +73 -11
  168. alita_sdk/tools/advanced_jira_mining/__init__.py +11 -8
  169. alita_sdk/tools/aws/delta_lake/__init__.py +13 -9
  170. alita_sdk/tools/aws/delta_lake/tool.py +5 -1
  171. alita_sdk/tools/azure_ai/search/__init__.py +11 -8
  172. alita_sdk/tools/azure_ai/search/api_wrapper.py +1 -1
  173. alita_sdk/tools/base/tool.py +5 -1
  174. alita_sdk/tools/base_indexer_toolkit.py +271 -84
  175. alita_sdk/tools/bitbucket/__init__.py +17 -11
  176. alita_sdk/tools/bitbucket/api_wrapper.py +59 -11
  177. alita_sdk/tools/bitbucket/cloud_api_wrapper.py +49 -35
  178. alita_sdk/tools/browser/__init__.py +5 -4
  179. alita_sdk/tools/carrier/__init__.py +5 -6
  180. alita_sdk/tools/carrier/backend_reports_tool.py +6 -6
  181. alita_sdk/tools/carrier/run_ui_test_tool.py +6 -6
  182. alita_sdk/tools/carrier/ui_reports_tool.py +5 -5
  183. alita_sdk/tools/chunkers/__init__.py +3 -1
  184. alita_sdk/tools/chunkers/code/treesitter/treesitter.py +37 -13
  185. alita_sdk/tools/chunkers/sematic/json_chunker.py +1 -0
  186. alita_sdk/tools/chunkers/sematic/markdown_chunker.py +97 -6
  187. alita_sdk/tools/chunkers/sematic/proposal_chunker.py +1 -1
  188. alita_sdk/tools/chunkers/universal_chunker.py +270 -0
  189. alita_sdk/tools/cloud/aws/__init__.py +10 -7
  190. alita_sdk/tools/cloud/azure/__init__.py +10 -7
  191. alita_sdk/tools/cloud/gcp/__init__.py +10 -7
  192. alita_sdk/tools/cloud/k8s/__init__.py +10 -7
  193. alita_sdk/tools/code/linter/__init__.py +10 -8
  194. alita_sdk/tools/code/loaders/codesearcher.py +3 -2
  195. alita_sdk/tools/code/sonar/__init__.py +11 -8
  196. alita_sdk/tools/code_indexer_toolkit.py +82 -22
  197. alita_sdk/tools/confluence/__init__.py +22 -16
  198. alita_sdk/tools/confluence/api_wrapper.py +107 -30
  199. alita_sdk/tools/confluence/loader.py +14 -2
  200. alita_sdk/tools/custom_open_api/__init__.py +12 -5
  201. alita_sdk/tools/elastic/__init__.py +11 -8
  202. alita_sdk/tools/elitea_base.py +493 -30
  203. alita_sdk/tools/figma/__init__.py +58 -11
  204. alita_sdk/tools/figma/api_wrapper.py +1235 -143
  205. alita_sdk/tools/figma/figma_client.py +73 -0
  206. alita_sdk/tools/figma/toon_tools.py +2748 -0
  207. alita_sdk/tools/github/__init__.py +14 -15
  208. alita_sdk/tools/github/github_client.py +224 -100
  209. alita_sdk/tools/github/graphql_client_wrapper.py +119 -33
  210. alita_sdk/tools/github/schemas.py +14 -5
  211. alita_sdk/tools/github/tool.py +5 -1
  212. alita_sdk/tools/github/tool_prompts.py +9 -22
  213. alita_sdk/tools/gitlab/__init__.py +16 -11
  214. alita_sdk/tools/gitlab/api_wrapper.py +218 -48
  215. alita_sdk/tools/gitlab_org/__init__.py +10 -9
  216. alita_sdk/tools/gitlab_org/api_wrapper.py +63 -64
  217. alita_sdk/tools/google/bigquery/__init__.py +13 -12
  218. alita_sdk/tools/google/bigquery/tool.py +5 -1
  219. alita_sdk/tools/google_places/__init__.py +11 -8
  220. alita_sdk/tools/google_places/api_wrapper.py +1 -1
  221. alita_sdk/tools/jira/__init__.py +17 -10
  222. alita_sdk/tools/jira/api_wrapper.py +92 -41
  223. alita_sdk/tools/keycloak/__init__.py +11 -8
  224. alita_sdk/tools/localgit/__init__.py +9 -3
  225. alita_sdk/tools/localgit/local_git.py +62 -54
  226. alita_sdk/tools/localgit/tool.py +5 -1
  227. alita_sdk/tools/memory/__init__.py +12 -4
  228. alita_sdk/tools/non_code_indexer_toolkit.py +1 -0
  229. alita_sdk/tools/ocr/__init__.py +11 -8
  230. alita_sdk/tools/openapi/__init__.py +491 -106
  231. alita_sdk/tools/openapi/api_wrapper.py +1368 -0
  232. alita_sdk/tools/openapi/tool.py +20 -0
  233. alita_sdk/tools/pandas/__init__.py +20 -12
  234. alita_sdk/tools/pandas/api_wrapper.py +38 -25
  235. alita_sdk/tools/pandas/dataframe/generator/base.py +3 -1
  236. alita_sdk/tools/postman/__init__.py +10 -9
  237. alita_sdk/tools/pptx/__init__.py +11 -10
  238. alita_sdk/tools/pptx/pptx_wrapper.py +1 -1
  239. alita_sdk/tools/qtest/__init__.py +31 -11
  240. alita_sdk/tools/qtest/api_wrapper.py +2135 -86
  241. alita_sdk/tools/rally/__init__.py +10 -9
  242. alita_sdk/tools/rally/api_wrapper.py +1 -1
  243. alita_sdk/tools/report_portal/__init__.py +12 -8
  244. alita_sdk/tools/salesforce/__init__.py +10 -8
  245. alita_sdk/tools/servicenow/__init__.py +17 -15
  246. alita_sdk/tools/servicenow/api_wrapper.py +1 -1
  247. alita_sdk/tools/sharepoint/__init__.py +10 -7
  248. alita_sdk/tools/sharepoint/api_wrapper.py +129 -38
  249. alita_sdk/tools/sharepoint/authorization_helper.py +191 -1
  250. alita_sdk/tools/sharepoint/utils.py +8 -2
  251. alita_sdk/tools/slack/__init__.py +10 -7
  252. alita_sdk/tools/slack/api_wrapper.py +2 -2
  253. alita_sdk/tools/sql/__init__.py +12 -9
  254. alita_sdk/tools/testio/__init__.py +10 -7
  255. alita_sdk/tools/testrail/__init__.py +11 -10
  256. alita_sdk/tools/testrail/api_wrapper.py +1 -1
  257. alita_sdk/tools/utils/__init__.py +9 -4
  258. alita_sdk/tools/utils/content_parser.py +103 -18
  259. alita_sdk/tools/utils/text_operations.py +410 -0
  260. alita_sdk/tools/utils/tool_prompts.py +79 -0
  261. alita_sdk/tools/vector_adapters/VectorStoreAdapter.py +30 -13
  262. alita_sdk/tools/xray/__init__.py +13 -9
  263. alita_sdk/tools/yagmail/__init__.py +9 -3
  264. alita_sdk/tools/zephyr/__init__.py +10 -7
  265. alita_sdk/tools/zephyr_enterprise/__init__.py +11 -7
  266. alita_sdk/tools/zephyr_essential/__init__.py +10 -7
  267. alita_sdk/tools/zephyr_essential/api_wrapper.py +30 -13
  268. alita_sdk/tools/zephyr_essential/client.py +2 -2
  269. alita_sdk/tools/zephyr_scale/__init__.py +11 -8
  270. alita_sdk/tools/zephyr_scale/api_wrapper.py +2 -2
  271. alita_sdk/tools/zephyr_squad/__init__.py +10 -7
  272. {alita_sdk-0.3.379.dist-info → alita_sdk-0.3.627.dist-info}/METADATA +154 -8
  273. alita_sdk-0.3.627.dist-info/RECORD +468 -0
  274. alita_sdk-0.3.627.dist-info/entry_points.txt +2 -0
  275. alita_sdk-0.3.379.dist-info/RECORD +0 -360
  276. {alita_sdk-0.3.379.dist-info → alita_sdk-0.3.627.dist-info}/WHEEL +0 -0
  277. {alita_sdk-0.3.379.dist-info → alita_sdk-0.3.627.dist-info}/licenses/LICENSE +0 -0
  278. {alita_sdk-0.3.379.dist-info → alita_sdk-0.3.627.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,492 @@
1
+ """
2
+ Unified MCP Client with auto-detection for SSE and Streamable HTTP transports.
3
+
4
+ This module provides a unified interface for MCP server communication that
5
+ automatically detects and uses the appropriate transport:
6
+ - SSE (Server-Sent Events): Traditional dual-connection model (GET for stream, POST for commands)
7
+ - Streamable HTTP: Newer POST-based model used by servers like GitHub Copilot MCP
8
+
9
+ Usage:
10
+ # Auto-detect transport (recommended)
11
+ client = McpClient(url=url, session_id=session_id, headers=headers)
12
+
13
+ # Force specific transport
14
+ client = McpClient(url=url, session_id=session_id, transport="streamable_http")
15
+
16
+ async with client:
17
+ await client.initialize()
18
+ tools = await client.list_tools()
19
+ result = await client.call_tool("tool_name", {"arg": "value"})
20
+ """
21
+
22
+ import asyncio
23
+ import json
24
+ import logging
25
+ import uuid
26
+ from typing import Any, Dict, List, Literal, Optional
27
+
28
+ import aiohttp
29
+
30
+ from .mcp_oauth import McpAuthorizationRequired
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # Transport types
35
+ TransportType = Literal["auto", "sse", "streamable_http"]
36
+
37
+
38
+ class McpClient:
39
+ """
40
+ Unified MCP client that supports both SSE and Streamable HTTP transports.
41
+
42
+ Auto-detects the appropriate transport by trying Streamable HTTP first,
43
+ then falling back to SSE if the server returns 405 Method Not Allowed.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ url: str,
49
+ session_id: Optional[str] = None,
50
+ headers: Optional[Dict[str, str]] = None,
51
+ timeout: int = 300,
52
+ transport: TransportType = "auto"
53
+ ):
54
+ """
55
+ Initialize the unified MCP client.
56
+
57
+ Args:
58
+ url: MCP server URL
59
+ session_id: Session ID for stateful connections (auto-generated if not provided)
60
+ headers: HTTP headers (e.g., Authorization)
61
+ timeout: Request timeout in seconds
62
+ transport: Transport type - "auto", "sse", or "streamable_http"
63
+ """
64
+ self.url = url
65
+ self.session_id = session_id or str(uuid.uuid4())
66
+ self.headers = headers or {}
67
+ self.timeout = timeout
68
+ self.transport = transport
69
+
70
+ # Will be set during connection
71
+ self._detected_transport: Optional[str] = None
72
+ self._sse_client = None
73
+ self._http_session: Optional[aiohttp.ClientSession] = None
74
+ self._mcp_session_id: Optional[str] = None # Server-provided session ID
75
+ self._initialized = False
76
+
77
+ logger.info(f"[MCP Client] Created for {url} (transport={transport}, session={self.session_id})")
78
+
79
+ @property
80
+ def server_session_id(self) -> Optional[str]:
81
+ """Get the server-provided session ID (from mcp-session-id header)."""
82
+ return self._mcp_session_id
83
+
84
+ @property
85
+ def detected_transport(self) -> Optional[str]:
86
+ """Get the detected transport type."""
87
+ return self._detected_transport
88
+
89
+ async def __aenter__(self):
90
+ """Async context manager entry - detect and connect."""
91
+ await self._connect()
92
+ return self
93
+
94
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
95
+ """Async context manager exit - cleanup."""
96
+ await self.close()
97
+
98
+ async def _connect(self):
99
+ """Detect transport and establish connection."""
100
+ if self.transport == "sse":
101
+ self._detected_transport = "sse"
102
+ await self._connect_sse()
103
+ elif self.transport == "streamable_http":
104
+ self._detected_transport = "streamable_http"
105
+ await self._connect_streamable_http()
106
+ else: # auto
107
+ await self._auto_detect_and_connect()
108
+
109
+ async def _auto_detect_and_connect(self):
110
+ """Try Streamable HTTP first, fall back to SSE."""
111
+ # If URL ends with /sse, use SSE transport directly
112
+ if self.url.rstrip('/').endswith('/sse'):
113
+ logger.debug("[MCP Client] URL ends with /sse, using SSE transport")
114
+ await self._connect_sse()
115
+ self._detected_transport = "sse"
116
+ logger.info("[MCP Client] Using SSE transport")
117
+ return
118
+
119
+ try:
120
+ logger.debug("[MCP Client] Auto-detecting transport, trying Streamable HTTP first...")
121
+ await self._connect_streamable_http()
122
+ self._detected_transport = "streamable_http"
123
+ logger.info("[MCP Client] Using Streamable HTTP transport")
124
+ except Exception as e:
125
+ error_str = str(e).lower()
126
+ # Check for 405, 404, or indicators that SSE is needed
127
+ if "405" in error_str or "method not allowed" in error_str or "404" in error_str:
128
+ logger.debug(f"[MCP Client] Streamable HTTP not supported ({e}), trying SSE...")
129
+ await self._connect_sse()
130
+ self._detected_transport = "sse"
131
+ logger.info("[MCP Client] Using SSE transport")
132
+ else:
133
+ # Re-raise other errors
134
+ raise
135
+
136
+ async def _connect_streamable_http(self):
137
+ """Connect using Streamable HTTP transport."""
138
+ self._http_session = aiohttp.ClientSession(
139
+ timeout=aiohttp.ClientTimeout(total=self.timeout)
140
+ )
141
+
142
+ async def _connect_sse(self):
143
+ """Connect using SSE transport."""
144
+ from .mcp_sse_client import McpSseClient
145
+
146
+ self._sse_client = McpSseClient(
147
+ url=self.url,
148
+ session_id=self.session_id,
149
+ headers=self.headers,
150
+ timeout=self.timeout
151
+ )
152
+
153
+ async def initialize(self) -> Dict[str, Any]:
154
+ """
155
+ Initialize MCP protocol session.
156
+
157
+ Returns:
158
+ Server capabilities and info
159
+ """
160
+ if self._detected_transport == "streamable_http":
161
+ return await self._initialize_streamable_http()
162
+ else:
163
+ return await self._initialize_sse()
164
+
165
+ async def _initialize_streamable_http(self, retry_without_session: bool = False) -> Dict[str, Any]:
166
+ """Initialize via Streamable HTTP transport."""
167
+ headers = {
168
+ "Content-Type": "application/json",
169
+ "Accept": "application/json, text/event-stream",
170
+ **self.headers
171
+ }
172
+
173
+ # DON'T send session_id on initialization - per MCP spec, initialization requests
174
+ # must not include a sessionId. The server will provide one in the response.
175
+ # Session ID is only used for subsequent requests after initialization.
176
+ # (The retry_without_session flag is kept for backwards compatibility but
177
+ # is effectively always true for initialization now)
178
+
179
+ # Debug: log headers (mask sensitive data)
180
+ debug_headers = {k: (v[:20] + '...' if k.lower() == 'authorization' and len(v) > 20 else v)
181
+ for k, v in headers.items()}
182
+ logger.debug(f"[MCP Client] Request headers: {debug_headers}")
183
+
184
+ init_request = {
185
+ "jsonrpc": "2.0",
186
+ "id": str(uuid.uuid4()),
187
+ "method": "initialize",
188
+ "params": {
189
+ "protocolVersion": "2024-11-05",
190
+ "capabilities": {
191
+ "roots": {"listChanged": True},
192
+ "sampling": {}
193
+ },
194
+ "clientInfo": {
195
+ "name": "ELITEA MCP Client",
196
+ "version": "1.0.0"
197
+ }
198
+ }
199
+ }
200
+
201
+ logger.debug(f"[MCP Client] Sending initialize via Streamable HTTP to {self.url}")
202
+
203
+ async with self._http_session.post(self.url, json=init_request, headers=headers) as response:
204
+ if response.status == 401:
205
+ await self._handle_401_response(response)
206
+
207
+ if response.status == 405:
208
+ raise Exception("HTTP 405 Method Not Allowed - server may require SSE transport")
209
+
210
+ # Handle invalid session error - retry without session_id
211
+ if response.status == 400 and not retry_without_session and self.session_id:
212
+ try:
213
+ error_body = await response.text()
214
+ if "invalid session" in error_body.lower():
215
+ logger.warning(f"[MCP Client] Invalid session, retrying without session_id")
216
+ return await self._initialize_streamable_http(retry_without_session=True)
217
+ except Exception:
218
+ pass
219
+
220
+ # Log error response body for debugging
221
+ if response.status >= 400:
222
+ try:
223
+ error_body = await response.text()
224
+ logger.error(f"[MCP Client] HTTP {response.status} error response: {error_body[:1000]}")
225
+ except Exception:
226
+ pass
227
+
228
+ response.raise_for_status()
229
+
230
+ # Get session ID from response headers
231
+ self._mcp_session_id = response.headers.get("mcp-session-id")
232
+ if self._mcp_session_id:
233
+ logger.info(f"[MCP Client] Server provided session_id: {self._mcp_session_id}")
234
+ else:
235
+ logger.debug(f"[MCP Client] No session_id in response headers. Headers: {dict(response.headers)}")
236
+
237
+ # Parse response
238
+ result = await self._parse_response(response)
239
+ logger.debug(f"[MCP Client] Initialize response: {result}")
240
+
241
+ # Send initialized notification
242
+ await self._send_notification("notifications/initialized")
243
+
244
+ self._initialized = True
245
+ return result.get('result', {})
246
+
247
+ async def _initialize_sse(self) -> Dict[str, Any]:
248
+ """Initialize via SSE transport."""
249
+ result = await self._sse_client.initialize()
250
+ self._initialized = True
251
+ return result
252
+
253
+ async def send_request(
254
+ self,
255
+ method: str,
256
+ params: Optional[Dict[str, Any]] = None,
257
+ request_id: Optional[str] = None
258
+ ) -> Dict[str, Any]:
259
+ """
260
+ Send a JSON-RPC request to the MCP server.
261
+
262
+ Args:
263
+ method: JSON-RPC method name (e.g., "tools/list", "tools/call")
264
+ params: Method parameters
265
+ request_id: Optional request ID (auto-generated if not provided)
266
+
267
+ Returns:
268
+ Parsed JSON-RPC response
269
+ """
270
+ if self._detected_transport == "streamable_http":
271
+ return await self._send_request_streamable_http(method, params, request_id)
272
+ else:
273
+ return await self._sse_client.send_request(method, params, request_id)
274
+
275
+ async def _send_request_streamable_http(
276
+ self,
277
+ method: str,
278
+ params: Optional[Dict[str, Any]] = None,
279
+ request_id: Optional[str] = None
280
+ ) -> Dict[str, Any]:
281
+ """Send request via Streamable HTTP."""
282
+ if request_id is None:
283
+ request_id = str(uuid.uuid4())
284
+
285
+ headers = {
286
+ "Content-Type": "application/json",
287
+ "Accept": "application/json, text/event-stream",
288
+ **self.headers
289
+ }
290
+
291
+ # Add MCP session ID if we have one
292
+ if self._mcp_session_id:
293
+ headers["mcp-session-id"] = self._mcp_session_id
294
+
295
+ request = {
296
+ "jsonrpc": "2.0",
297
+ "id": request_id,
298
+ "method": method,
299
+ "params": params or {}
300
+ }
301
+
302
+ logger.debug(f"[MCP Client] Sending request: {method} (id={request_id})")
303
+
304
+ async with self._http_session.post(self.url, json=request, headers=headers) as response:
305
+ if response.status == 401:
306
+ await self._handle_401_response(response)
307
+
308
+ response.raise_for_status()
309
+
310
+ result = await self._parse_response(response)
311
+
312
+ # Check for JSON-RPC error
313
+ if 'error' in result:
314
+ error = result['error']
315
+ raise Exception(f"MCP Error: {error.get('message', str(error))}")
316
+
317
+ return result
318
+
319
+ async def _send_notification(self, method: str, params: Optional[Dict[str, Any]] = None):
320
+ """Send a JSON-RPC notification (no response expected)."""
321
+ if self._detected_transport == "streamable_http":
322
+ headers = {
323
+ "Content-Type": "application/json",
324
+ **self.headers
325
+ }
326
+ if self._mcp_session_id:
327
+ headers["mcp-session-id"] = self._mcp_session_id
328
+
329
+ notification = {
330
+ "jsonrpc": "2.0",
331
+ "method": method
332
+ }
333
+ if params:
334
+ notification["params"] = params
335
+
336
+ async with self._http_session.post(self.url, json=notification, headers=headers) as response:
337
+ pass # Notifications don't expect a response
338
+
339
+ async def _parse_response(self, response: aiohttp.ClientResponse) -> Dict[str, Any]:
340
+ """Parse response, handling both JSON and SSE formats."""
341
+ content_type = response.headers.get("content-type", "")
342
+ text = await response.text()
343
+
344
+ if "text/event-stream" in content_type:
345
+ return self._parse_sse_text(text)
346
+ else:
347
+ return json.loads(text) if text else {}
348
+
349
+ def _parse_sse_text(self, text: str) -> Dict[str, Any]:
350
+ """Parse SSE formatted response to extract JSON data."""
351
+ for line in text.split('\n'):
352
+ if line.startswith('data:'):
353
+ data = line[5:].strip()
354
+ if data:
355
+ return json.loads(data)
356
+ return {}
357
+
358
+ async def _handle_401_response(self, response: aiohttp.ClientResponse):
359
+ """Handle 401 Unauthorized response with OAuth flow."""
360
+ from .mcp_oauth import (
361
+ canonical_resource,
362
+ extract_resource_metadata_url,
363
+ extract_authorization_uri,
364
+ fetch_resource_metadata_async,
365
+ infer_authorization_servers_from_realm,
366
+ fetch_oauth_authorization_server_metadata
367
+ )
368
+
369
+ auth_header = response.headers.get('WWW-Authenticate', '')
370
+ resource_metadata_url = extract_resource_metadata_url(auth_header, self.url)
371
+
372
+ # First, try authorization_uri from WWW-Authenticate header (preferred)
373
+ authorization_uri = extract_authorization_uri(auth_header)
374
+
375
+ metadata = None
376
+ if authorization_uri:
377
+ # Fetch OAuth metadata directly from authorization_uri
378
+ auth_server_metadata = fetch_oauth_authorization_server_metadata(authorization_uri, timeout=30)
379
+ if auth_server_metadata:
380
+ # Extract base authorization server URL from the issuer or the well-known URL
381
+ base_auth_server = auth_server_metadata.get('issuer')
382
+ if not base_auth_server and '/.well-known/' in authorization_uri:
383
+ base_auth_server = authorization_uri.split('/.well-known/')[0]
384
+
385
+ metadata = {
386
+ 'authorization_servers': [base_auth_server] if base_auth_server else [authorization_uri],
387
+ 'oauth_authorization_server': auth_server_metadata
388
+ }
389
+
390
+ # Fall back to resource_metadata if authorization_uri didn't work
391
+ if not metadata:
392
+ if resource_metadata_url:
393
+ metadata = await fetch_resource_metadata_async(
394
+ resource_metadata_url,
395
+ session=self._http_session,
396
+ timeout=30
397
+ )
398
+ # If we got resource_metadata, also fetch oauth_authorization_server
399
+ if metadata and metadata.get('authorization_servers'):
400
+ auth_server_metadata = fetch_oauth_authorization_server_metadata(
401
+ metadata['authorization_servers'][0], timeout=30
402
+ )
403
+ if auth_server_metadata:
404
+ metadata['oauth_authorization_server'] = auth_server_metadata
405
+
406
+ # Infer authorization servers if not in metadata
407
+ if not metadata or not metadata.get('authorization_servers'):
408
+ inferred_servers = infer_authorization_servers_from_realm(auth_header, self.url)
409
+ if inferred_servers:
410
+ if not metadata:
411
+ metadata = {}
412
+ metadata['authorization_servers'] = inferred_servers
413
+
414
+ # Fetch OAuth metadata
415
+ auth_server_metadata = fetch_oauth_authorization_server_metadata(inferred_servers[0], timeout=30)
416
+ if auth_server_metadata:
417
+ metadata['oauth_authorization_server'] = auth_server_metadata
418
+
419
+ raise McpAuthorizationRequired(
420
+ message=f"MCP server {self.url} requires OAuth authorization",
421
+ server_url=canonical_resource(self.url),
422
+ resource_metadata_url=resource_metadata_url,
423
+ www_authenticate=auth_header,
424
+ resource_metadata=metadata,
425
+ status=401,
426
+ tool_name=self.url,
427
+ )
428
+
429
+ async def list_tools(self) -> List[Dict[str, Any]]:
430
+ """
431
+ Get list of available tools from the MCP server.
432
+
433
+ Returns:
434
+ List of tool definitions
435
+ """
436
+ response = await self.send_request("tools/list")
437
+ result = response.get('result', {})
438
+ tools = result.get('tools', [])
439
+ logger.info(f"[MCP Client] Discovered {len(tools)} tools")
440
+ return tools
441
+
442
+ async def list_prompts(self) -> List[Dict[str, Any]]:
443
+ """
444
+ Get list of available prompts from the MCP server.
445
+
446
+ Returns:
447
+ List of prompt definitions
448
+ """
449
+ response = await self.send_request("prompts/list")
450
+ result = response.get('result', {})
451
+ prompts = result.get('prompts', [])
452
+ logger.debug(f"[MCP Client] Discovered {len(prompts)} prompts")
453
+ return prompts
454
+
455
+ async def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
456
+ """
457
+ Execute a tool on the MCP server.
458
+
459
+ Args:
460
+ tool_name: Name of the tool to call
461
+ arguments: Tool arguments
462
+
463
+ Returns:
464
+ Tool execution result
465
+ """
466
+ response = await self.send_request(
467
+ "tools/call",
468
+ params={
469
+ "name": tool_name,
470
+ "arguments": arguments
471
+ }
472
+ )
473
+ return response.get('result', {})
474
+
475
+ async def close(self):
476
+ """Close the client and cleanup resources."""
477
+ logger.info(f"[MCP Client] Closing connection...")
478
+
479
+ if self._sse_client:
480
+ await self._sse_client.close()
481
+ self._sse_client = None
482
+
483
+ if self._http_session and not self._http_session.closed:
484
+ await self._http_session.close()
485
+ self._http_session = None
486
+
487
+ logger.info(f"[MCP Client] Connection closed")
488
+
489
+ @property
490
+ def detected_transport(self) -> Optional[str]:
491
+ """Return the detected/selected transport type."""
492
+ return self._detected_transport