aip-agents-binary 0.5.25b9__py3-none-any.whl → 0.6.1__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.
- aip_agents/agent/base_langgraph_agent.py +137 -68
- aip_agents/agent/base_langgraph_agent.pyi +3 -2
- aip_agents/agent/langgraph_react_agent.py +252 -16
- aip_agents/agent/langgraph_react_agent.pyi +40 -1
- aip_agents/examples/compare_streaming_client.py +2 -2
- aip_agents/examples/compare_streaming_server.py +1 -1
- aip_agents/examples/hello_world_ptc.py +51 -0
- aip_agents/examples/hello_world_ptc.pyi +5 -0
- aip_agents/examples/hello_world_tool_output_client.py +9 -0
- aip_agents/examples/todolist_planning_a2a_langchain_client.py +2 -2
- aip_agents/examples/todolist_planning_a2a_langgraph_server.py +1 -1
- aip_agents/guardrails/engines/base.py +6 -6
- aip_agents/mcp/client/connection_manager.py +36 -1
- aip_agents/mcp/client/connection_manager.pyi +3 -0
- aip_agents/mcp/client/persistent_session.py +318 -68
- aip_agents/mcp/client/persistent_session.pyi +9 -0
- aip_agents/mcp/client/transports.py +33 -2
- aip_agents/mcp/client/transports.pyi +9 -0
- aip_agents/ptc/__init__.py +48 -0
- aip_agents/ptc/__init__.pyi +10 -0
- aip_agents/ptc/doc_gen.py +122 -0
- aip_agents/ptc/doc_gen.pyi +40 -0
- aip_agents/ptc/exceptions.py +39 -0
- aip_agents/ptc/exceptions.pyi +22 -0
- aip_agents/ptc/executor.py +143 -0
- aip_agents/ptc/executor.pyi +73 -0
- aip_agents/ptc/mcp/__init__.py +45 -0
- aip_agents/ptc/mcp/__init__.pyi +7 -0
- aip_agents/ptc/mcp/sandbox_bridge.py +668 -0
- aip_agents/ptc/mcp/sandbox_bridge.pyi +47 -0
- aip_agents/ptc/mcp/templates/__init__.py +1 -0
- aip_agents/ptc/mcp/templates/__init__.pyi +0 -0
- aip_agents/ptc/mcp/templates/mcp_client.py.template +239 -0
- aip_agents/ptc/naming.py +184 -0
- aip_agents/ptc/naming.pyi +76 -0
- aip_agents/ptc/payload.py +26 -0
- aip_agents/ptc/payload.pyi +15 -0
- aip_agents/ptc/prompt_builder.py +571 -0
- aip_agents/ptc/prompt_builder.pyi +55 -0
- aip_agents/ptc/ptc_helper.py +16 -0
- aip_agents/ptc/ptc_helper.pyi +1 -0
- aip_agents/ptc/sandbox_bridge.py +58 -0
- aip_agents/ptc/sandbox_bridge.pyi +25 -0
- aip_agents/ptc/template_utils.py +33 -0
- aip_agents/ptc/template_utils.pyi +13 -0
- aip_agents/ptc/templates/__init__.py +1 -0
- aip_agents/ptc/templates/__init__.pyi +0 -0
- aip_agents/ptc/templates/ptc_helper.py.template +134 -0
- aip_agents/sandbox/__init__.py +43 -0
- aip_agents/sandbox/__init__.pyi +5 -0
- aip_agents/sandbox/defaults.py +9 -0
- aip_agents/sandbox/defaults.pyi +2 -0
- aip_agents/sandbox/e2b_runtime.py +267 -0
- aip_agents/sandbox/e2b_runtime.pyi +51 -0
- aip_agents/sandbox/template_builder.py +131 -0
- aip_agents/sandbox/template_builder.pyi +36 -0
- aip_agents/sandbox/types.py +24 -0
- aip_agents/sandbox/types.pyi +14 -0
- aip_agents/sandbox/validation.py +50 -0
- aip_agents/sandbox/validation.pyi +20 -0
- aip_agents/tools/__init__.py +2 -0
- aip_agents/tools/__init__.pyi +2 -1
- aip_agents/tools/browser_use/browser_use_tool.py +8 -0
- aip_agents/tools/browser_use/streaming.py +2 -0
- aip_agents/tools/execute_ptc_code.py +305 -0
- aip_agents/tools/execute_ptc_code.pyi +87 -0
- aip_agents/utils/langgraph/tool_managers/delegation_tool_manager.py +26 -1
- aip_agents/utils/langgraph/tool_output_management.py +80 -0
- aip_agents/utils/langgraph/tool_output_management.pyi +37 -0
- {aip_agents_binary-0.5.25b9.dist-info → aip_agents_binary-0.6.1.dist-info}/METADATA +51 -48
- {aip_agents_binary-0.5.25b9.dist-info → aip_agents_binary-0.6.1.dist-info}/RECORD +73 -27
- {aip_agents_binary-0.5.25b9.dist-info → aip_agents_binary-0.6.1.dist-info}/WHEEL +0 -0
- {aip_agents_binary-0.5.25b9.dist-info → aip_agents_binary-0.6.1.dist-info}/top_level.txt +0 -0
|
@@ -60,6 +60,9 @@ class MCPConnectionManager:
|
|
|
60
60
|
async def start(self) -> tuple[Any, Any]:
|
|
61
61
|
"""Start connection in background task.
|
|
62
62
|
|
|
63
|
+
For HTTP/SSE transports, establishes connection directly to avoid anyio context issues.
|
|
64
|
+
For stdio transport, uses background task to manage subprocess lifecycle.
|
|
65
|
+
|
|
63
66
|
Returns:
|
|
64
67
|
tuple[Any, Any]: Tuple of (read_stream, write_stream) for ClientSession
|
|
65
68
|
|
|
@@ -67,6 +70,17 @@ class MCPConnectionManager:
|
|
|
67
70
|
Exception: If connection establishment fails
|
|
68
71
|
"""
|
|
69
72
|
logger.debug(f"Starting connection manager for {self.server_name}")
|
|
73
|
+
|
|
74
|
+
# Determine transport type first
|
|
75
|
+
self.transport_type = self._get_transport_type()
|
|
76
|
+
|
|
77
|
+
# For HTTP/SSE: connect directly (no background task needed)
|
|
78
|
+
# This avoids anyio.BrokenResourceError when streams cross task boundaries
|
|
79
|
+
if self.transport_type in (TransportType.HTTP, TransportType.SSE):
|
|
80
|
+
await self._establish_connection()
|
|
81
|
+
return self._connection
|
|
82
|
+
|
|
83
|
+
# For stdio: use background task to manage subprocess
|
|
70
84
|
self._task = asyncio.create_task(self._connection_task())
|
|
71
85
|
await self._ready_event.wait()
|
|
72
86
|
|
|
@@ -78,6 +92,20 @@ class MCPConnectionManager:
|
|
|
78
92
|
async def stop(self) -> None:
|
|
79
93
|
"""Stop connection gracefully."""
|
|
80
94
|
logger.debug(f"Stopping connection manager for {self.server_name}")
|
|
95
|
+
|
|
96
|
+
# For HTTP/SSE (no background task), just close transport
|
|
97
|
+
if self.transport_type in (TransportType.HTTP, TransportType.SSE):
|
|
98
|
+
if self._transport:
|
|
99
|
+
try:
|
|
100
|
+
close_result = self._transport.close()
|
|
101
|
+
if inspect.isawaitable(close_result):
|
|
102
|
+
await close_result
|
|
103
|
+
except Exception as exc:
|
|
104
|
+
logger.warning(f"Failed to close transport cleanly for {self.server_name}: {exc}")
|
|
105
|
+
self._connection = None
|
|
106
|
+
return
|
|
107
|
+
|
|
108
|
+
# For stdio (with background task), wait for task to finish
|
|
81
109
|
if self._task and not self._task.done():
|
|
82
110
|
self._stop_event.set()
|
|
83
111
|
try:
|
|
@@ -94,6 +122,11 @@ class MCPConnectionManager:
|
|
|
94
122
|
Returns:
|
|
95
123
|
bool: True if connected, False otherwise
|
|
96
124
|
"""
|
|
125
|
+
# For HTTP/SSE (no background task), just check if connection exists
|
|
126
|
+
if self.transport_type in (TransportType.HTTP, TransportType.SSE):
|
|
127
|
+
return self._connection is not None
|
|
128
|
+
|
|
129
|
+
# For stdio (with background task), check task status too
|
|
97
130
|
return (
|
|
98
131
|
self._connection is not None
|
|
99
132
|
and self._task is not None
|
|
@@ -144,7 +177,9 @@ class MCPConnectionManager:
|
|
|
144
177
|
Raises:
|
|
145
178
|
ConnectionError: If all connection attempts fail
|
|
146
179
|
"""
|
|
147
|
-
|
|
180
|
+
# transport_type may already be set by start() for HTTP/SSE
|
|
181
|
+
if not self.transport_type:
|
|
182
|
+
self.transport_type = self._get_transport_type()
|
|
148
183
|
details = f"URL: {self.config.get('url', 'N/A')}, Command: {self.config.get('command', 'N/A')}"
|
|
149
184
|
logger.info(f"Establishing connection to {self.server_name} via {self.transport_type} ({details})")
|
|
150
185
|
|
|
@@ -31,6 +31,9 @@ class MCPConnectionManager:
|
|
|
31
31
|
async def start(self) -> tuple[Any, Any]:
|
|
32
32
|
"""Start connection in background task.
|
|
33
33
|
|
|
34
|
+
For HTTP/SSE transports, establishes connection directly to avoid anyio context issues.
|
|
35
|
+
For stdio transport, uses background task to manage subprocess lifecycle.
|
|
36
|
+
|
|
34
37
|
Returns:
|
|
35
38
|
tuple[Any, Any]: Tuple of (read_stream, write_stream) for ClientSession
|
|
36
39
|
|
|
@@ -8,6 +8,7 @@ Authors:
|
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
10
|
import asyncio
|
|
11
|
+
from collections.abc import Awaitable, Callable
|
|
11
12
|
from typing import Any
|
|
12
13
|
|
|
13
14
|
from gllm_tools.mcp.client.config import MCPConfiguration
|
|
@@ -69,6 +70,13 @@ class PersistentMCPSession:
|
|
|
69
70
|
|
|
70
71
|
self._initialized = False
|
|
71
72
|
self._lock = asyncio.Lock()
|
|
73
|
+
self._owner_task: asyncio.Task | None = None
|
|
74
|
+
self._owner_ready: asyncio.Event = asyncio.Event()
|
|
75
|
+
self._owner_exception: Exception | None = None
|
|
76
|
+
self._timeout = float(config.get("timeout", 30.0))
|
|
77
|
+
self._request_queue: asyncio.Queue[
|
|
78
|
+
tuple[Callable[..., Awaitable[Any]], tuple[Any, ...], asyncio.Future, bool]
|
|
79
|
+
] = asyncio.Queue()
|
|
72
80
|
|
|
73
81
|
async def initialize(self) -> None:
|
|
74
82
|
"""Initialize session once and cache tools.
|
|
@@ -85,50 +93,28 @@ class PersistentMCPSession:
|
|
|
85
93
|
# Double-check pattern
|
|
86
94
|
if self._initialized:
|
|
87
95
|
return
|
|
96
|
+
if self._owner_task is None or self._owner_task.done():
|
|
97
|
+
self._owner_ready = asyncio.Event()
|
|
98
|
+
self._owner_exception = None
|
|
99
|
+
self._owner_task = asyncio.create_task(self._owner_loop())
|
|
88
100
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
self.tools = tools_result.tools if tools_result else []
|
|
107
|
-
self._filtered_tools_cache = None # Invalidate cache when tools change
|
|
108
|
-
logger.info(f"Cached {len(self.tools)} tools for {self.server_name}")
|
|
109
|
-
else:
|
|
110
|
-
logger.info(f"No tools available for {self.server_name}")
|
|
111
|
-
|
|
112
|
-
# Warn once per initialization if allowed_tools references unknown names
|
|
113
|
-
if self._allowed_tools_set:
|
|
114
|
-
self._warn_on_unknown_allowed_tools(list(self._allowed_tools_set), self.tools)
|
|
115
|
-
|
|
116
|
-
# Discover resources (for future use)
|
|
117
|
-
if result.capabilities.resources:
|
|
118
|
-
try:
|
|
119
|
-
resources_result = await self.client_session.list_resources()
|
|
120
|
-
if resources_result and resources_result.resources:
|
|
121
|
-
logger.debug(f"Found {len(resources_result.resources)} resources for {self.server_name}")
|
|
122
|
-
except Exception:
|
|
123
|
-
logger.debug(f"Could not list resources for {self.server_name}, skipping")
|
|
124
|
-
|
|
125
|
-
self._initialized = True
|
|
126
|
-
logger.info(f"Session initialization complete for {self.server_name}")
|
|
127
|
-
|
|
128
|
-
except Exception as e:
|
|
129
|
-
logger.error(f"Failed to initialize session for {self.server_name}: {e}", exc_info=True)
|
|
130
|
-
await self._cleanup_on_error()
|
|
131
|
-
raise ConnectionError(f"Failed to initialize MCP session for {self.server_name}: {str(e)}") from e
|
|
101
|
+
try:
|
|
102
|
+
await asyncio.wait_for(self._owner_ready.wait(), timeout=self._timeout)
|
|
103
|
+
except asyncio.CancelledError:
|
|
104
|
+
if self._owner_task and not self._owner_task.done():
|
|
105
|
+
self._owner_task.cancel()
|
|
106
|
+
raise
|
|
107
|
+
except TimeoutError as e:
|
|
108
|
+
logger.error(f"Initialization timed out for {self.server_name} after {self._timeout}s")
|
|
109
|
+
if self._owner_task and not self._owner_task.done():
|
|
110
|
+
self._owner_task.cancel()
|
|
111
|
+
self._owner_exception = ConnectionError(
|
|
112
|
+
f"Initialization timed out for {self.server_name} after {self._timeout}s"
|
|
113
|
+
)
|
|
114
|
+
self._owner_ready.set()
|
|
115
|
+
raise self._owner_exception from e
|
|
116
|
+
if self._owner_exception:
|
|
117
|
+
raise self._owner_exception
|
|
132
118
|
|
|
133
119
|
async def call_tool(self, name: str, arguments: dict[str, Any]) -> CallToolResult:
|
|
134
120
|
"""Call MCP tool using persistent session.
|
|
@@ -143,7 +129,19 @@ class PersistentMCPSession:
|
|
|
143
129
|
Raises:
|
|
144
130
|
Exception: If tool call fails
|
|
145
131
|
"""
|
|
146
|
-
await self.
|
|
132
|
+
return await self._run_in_owner(self._call_tool_impl, name, arguments)
|
|
133
|
+
|
|
134
|
+
async def _call_tool_impl(self, name: str, arguments: dict[str, Any]) -> CallToolResult:
|
|
135
|
+
"""Call MCP tool using the owner task.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
name: Tool name.
|
|
139
|
+
arguments: Tool arguments.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
CallToolResult: Tool call result.
|
|
143
|
+
"""
|
|
144
|
+
await self._ensure_connected_impl()
|
|
147
145
|
|
|
148
146
|
if self._allowed_tools_set and name not in self._allowed_tools_set:
|
|
149
147
|
allowed_display = ", ".join(sorted(self._allowed_tools_set))
|
|
@@ -173,10 +171,9 @@ class PersistentMCPSession:
|
|
|
173
171
|
Raises:
|
|
174
172
|
Exception: If resource reading fails
|
|
175
173
|
"""
|
|
176
|
-
await self.
|
|
177
|
-
return await self._execute_read_resource(uri)
|
|
174
|
+
return await self._run_in_owner(self._execute_read_resource_impl, uri)
|
|
178
175
|
|
|
179
|
-
async def
|
|
176
|
+
async def _execute_read_resource_impl(self, uri: str) -> Any:
|
|
180
177
|
"""Execute the reading of an MCP resource.
|
|
181
178
|
|
|
182
179
|
Args:
|
|
@@ -188,6 +185,7 @@ class PersistentMCPSession:
|
|
|
188
185
|
Raises:
|
|
189
186
|
Exception: If resource reading fails
|
|
190
187
|
"""
|
|
188
|
+
await self._ensure_connected_impl()
|
|
191
189
|
try:
|
|
192
190
|
logger.debug(f"Reading resource '{uri}' on {self.server_name}")
|
|
193
191
|
result = await self.client_session.read_resource(uri)
|
|
@@ -202,7 +200,15 @@ class PersistentMCPSession:
|
|
|
202
200
|
Returns:
|
|
203
201
|
list[Tool]: a copy of list of available tools, filtered to only allowed tools if configured
|
|
204
202
|
"""
|
|
205
|
-
await self.
|
|
203
|
+
return await self._run_in_owner(self._list_tools_impl)
|
|
204
|
+
|
|
205
|
+
async def _list_tools_impl(self) -> list[Tool]:
|
|
206
|
+
"""Return the cached tools list from the owner task.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
list[Tool]: Filtered tool list if allowed tools are configured, otherwise all tools.
|
|
210
|
+
"""
|
|
211
|
+
await self._ensure_connected_impl()
|
|
206
212
|
|
|
207
213
|
if not self._allowed_tools_set:
|
|
208
214
|
return list(self.tools)
|
|
@@ -234,9 +240,13 @@ class PersistentMCPSession:
|
|
|
234
240
|
Raises:
|
|
235
241
|
Exception: If reconnection fails
|
|
236
242
|
"""
|
|
243
|
+
await self._run_in_owner(self._ensure_connected_impl)
|
|
244
|
+
|
|
245
|
+
async def _ensure_connected_impl(self) -> None:
|
|
246
|
+
"""Ensure the session is connected, reconnecting if needed."""
|
|
237
247
|
if not self._initialized or not self.connection_manager.is_connected:
|
|
238
248
|
logger.info(f"Reconnecting session for {self.server_name}")
|
|
239
|
-
await self.
|
|
249
|
+
await self._initialize_impl()
|
|
240
250
|
|
|
241
251
|
def _handle_connection_error(self, e: Exception, operation: str) -> None:
|
|
242
252
|
"""Handle connection-related errors with logging and reconnection marking.
|
|
@@ -255,29 +265,44 @@ class PersistentMCPSession:
|
|
|
255
265
|
"""Disconnect session gracefully.
|
|
256
266
|
|
|
257
267
|
This method cleans up all resources and connections.
|
|
268
|
+
Always succeeds, even if the session was already in an error state.
|
|
258
269
|
"""
|
|
259
270
|
logger.info(f"Disconnecting session for {self.server_name}")
|
|
260
271
|
|
|
261
|
-
|
|
272
|
+
if self._owner_task is None or self._owner_task.done():
|
|
273
|
+
await self._disconnect_impl()
|
|
274
|
+
return
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
await self._run_in_owner(self._disconnect_impl, shutdown=True, ensure_initialized=False)
|
|
278
|
+
except ConnectionError:
|
|
279
|
+
# Owner task already failed; just clean up directly
|
|
280
|
+
logger.debug(f"Owner task already failed for {self.server_name}, cleaning up directly")
|
|
281
|
+
await self._disconnect_impl()
|
|
282
|
+
finally:
|
|
283
|
+
await self._await_owner_shutdown()
|
|
284
|
+
|
|
285
|
+
async def _await_owner_shutdown(self) -> None:
|
|
286
|
+
"""Wait for the owner task to exit, cancelling on timeout."""
|
|
287
|
+
if not self._owner_task:
|
|
288
|
+
return
|
|
289
|
+
|
|
290
|
+
owner_task = self._owner_task
|
|
291
|
+
try:
|
|
292
|
+
await asyncio.wait_for(owner_task, timeout=self._timeout)
|
|
293
|
+
except TimeoutError:
|
|
294
|
+
logger.warning(f"Owner task for {self.server_name} did not exit within {self._timeout}s, cancelling")
|
|
295
|
+
owner_task.cancel()
|
|
262
296
|
try:
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
await self.connection_manager.stop()
|
|
273
|
-
|
|
274
|
-
except Exception as e:
|
|
275
|
-
logger.error(f"Error during disconnect for {self.server_name}: {e}")
|
|
276
|
-
finally:
|
|
277
|
-
self._initialized = False
|
|
278
|
-
self.tools.clear()
|
|
279
|
-
self._filtered_tools_cache = None # Clear cache on disconnect
|
|
280
|
-
logger.info(f"Session disconnected for {self.server_name}")
|
|
297
|
+
await owner_task
|
|
298
|
+
except (asyncio.CancelledError, Exception):
|
|
299
|
+
pass
|
|
300
|
+
except asyncio.CancelledError:
|
|
301
|
+
pass
|
|
302
|
+
except Exception:
|
|
303
|
+
pass
|
|
304
|
+
finally:
|
|
305
|
+
self._owner_task = None
|
|
281
306
|
|
|
282
307
|
async def _cleanup_on_error(self) -> None:
|
|
283
308
|
"""Internal cleanup method for error scenarios."""
|
|
@@ -306,6 +331,17 @@ class PersistentMCPSession:
|
|
|
306
331
|
"""
|
|
307
332
|
return self._initialized and self.connection_manager.is_connected
|
|
308
333
|
|
|
334
|
+
@property
|
|
335
|
+
def allowed_tools(self) -> list[str] | None:
|
|
336
|
+
"""Return the configured allowed tools, sorted if present.
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
Sorted list of allowed tool names, or None if unrestricted.
|
|
340
|
+
"""
|
|
341
|
+
if not self._allowed_tools_set:
|
|
342
|
+
return None
|
|
343
|
+
return sorted(self._allowed_tools_set)
|
|
344
|
+
|
|
309
345
|
def update_allowed_tools(self, allowed_tools: list[str] | None) -> bool:
|
|
310
346
|
"""Update the list of allowed tools for this session.
|
|
311
347
|
|
|
@@ -360,3 +396,217 @@ class PersistentMCPSession:
|
|
|
360
396
|
logger.warning(
|
|
361
397
|
f"[{self.server_name}] Tool '{tool_name}' not found in available tools but specified in allowed_tools"
|
|
362
398
|
)
|
|
399
|
+
|
|
400
|
+
async def _owner_loop(self) -> None:
|
|
401
|
+
"""Run the owner task loop and process queued requests.
|
|
402
|
+
|
|
403
|
+
Returns:
|
|
404
|
+
None
|
|
405
|
+
"""
|
|
406
|
+
shutdown_requested = False
|
|
407
|
+
try:
|
|
408
|
+
shutdown_requested = await self._initialize_owner()
|
|
409
|
+
if shutdown_requested:
|
|
410
|
+
return
|
|
411
|
+
|
|
412
|
+
while True:
|
|
413
|
+
func, args, future, shutdown = await self._request_queue.get()
|
|
414
|
+
if await self._process_owner_request(func, args, future):
|
|
415
|
+
continue
|
|
416
|
+
if shutdown:
|
|
417
|
+
shutdown_requested = True
|
|
418
|
+
break
|
|
419
|
+
finally:
|
|
420
|
+
# Drain and cancel any pending requests to avoid hanging callers
|
|
421
|
+
await self._drain_pending_requests()
|
|
422
|
+
if not shutdown_requested and (
|
|
423
|
+
self._initialized or self.client_session or self.connection_manager.transport_type is not None
|
|
424
|
+
):
|
|
425
|
+
await self._cleanup_on_error()
|
|
426
|
+
self._owner_task = None
|
|
427
|
+
|
|
428
|
+
async def _drain_pending_requests(self) -> None:
|
|
429
|
+
"""Cancel all pending requests in the queue.
|
|
430
|
+
|
|
431
|
+
This prevents callers from hanging when the owner loop exits unexpectedly.
|
|
432
|
+
"""
|
|
433
|
+
error = ConnectionError(f"Session for {self.server_name} is shutting down")
|
|
434
|
+
while not self._request_queue.empty():
|
|
435
|
+
try:
|
|
436
|
+
_, _, future, _ = self._request_queue.get_nowait()
|
|
437
|
+
if not future.done():
|
|
438
|
+
future.set_exception(error)
|
|
439
|
+
except asyncio.QueueEmpty:
|
|
440
|
+
break
|
|
441
|
+
|
|
442
|
+
async def _initialize_owner(self) -> bool:
|
|
443
|
+
"""Initialize the owner task and signal readiness.
|
|
444
|
+
|
|
445
|
+
Returns:
|
|
446
|
+
bool: True when initialization fails and the loop should stop.
|
|
447
|
+
"""
|
|
448
|
+
try:
|
|
449
|
+
await self._initialize_impl()
|
|
450
|
+
except Exception as e:
|
|
451
|
+
self._owner_exception = e
|
|
452
|
+
self._owner_ready.set()
|
|
453
|
+
return True
|
|
454
|
+
|
|
455
|
+
self._owner_ready.set()
|
|
456
|
+
return False
|
|
457
|
+
|
|
458
|
+
async def _process_owner_request(
|
|
459
|
+
self,
|
|
460
|
+
func: Callable[..., Awaitable[Any]],
|
|
461
|
+
args: tuple[Any, ...],
|
|
462
|
+
future: asyncio.Future,
|
|
463
|
+
) -> bool:
|
|
464
|
+
"""Process a single queued request.
|
|
465
|
+
|
|
466
|
+
Args:
|
|
467
|
+
func: Coroutine function to execute.
|
|
468
|
+
args: Positional arguments for the function.
|
|
469
|
+
future: Future to resolve with the result or exception.
|
|
470
|
+
|
|
471
|
+
Returns:
|
|
472
|
+
bool: True if the request was skipped due to cancellation.
|
|
473
|
+
"""
|
|
474
|
+
if future.cancelled():
|
|
475
|
+
return True
|
|
476
|
+
|
|
477
|
+
try:
|
|
478
|
+
result = await func(*args)
|
|
479
|
+
except asyncio.CancelledError as e:
|
|
480
|
+
# Owner task was cancelled - resolve future to prevent hanging caller
|
|
481
|
+
if not future.cancelled():
|
|
482
|
+
future.set_exception(e)
|
|
483
|
+
raise
|
|
484
|
+
except Exception as e:
|
|
485
|
+
if not future.cancelled():
|
|
486
|
+
future.set_exception(e)
|
|
487
|
+
else:
|
|
488
|
+
if not future.cancelled():
|
|
489
|
+
future.set_result(result)
|
|
490
|
+
return False
|
|
491
|
+
|
|
492
|
+
async def _run_in_owner(
|
|
493
|
+
self,
|
|
494
|
+
func: Callable[..., Awaitable[Any]],
|
|
495
|
+
*args: Any,
|
|
496
|
+
shutdown: bool = False,
|
|
497
|
+
ensure_initialized: bool = True,
|
|
498
|
+
) -> Any:
|
|
499
|
+
"""Execute a coroutine on the owner task.
|
|
500
|
+
|
|
501
|
+
Args:
|
|
502
|
+
func: Coroutine function to execute.
|
|
503
|
+
*args: Positional arguments to pass to func.
|
|
504
|
+
shutdown: Whether this request should shut down the owner loop.
|
|
505
|
+
ensure_initialized: Whether to initialize the owner task if needed.
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
Any: The result of the coroutine call.
|
|
509
|
+
|
|
510
|
+
Raises:
|
|
511
|
+
ConnectionError: If the owner task died or session is shutting down.
|
|
512
|
+
"""
|
|
513
|
+
if ensure_initialized:
|
|
514
|
+
await self.initialize()
|
|
515
|
+
else:
|
|
516
|
+
# For non-init calls (like disconnect), check if owner is alive
|
|
517
|
+
if self._owner_task is None or self._owner_task.done():
|
|
518
|
+
return await func(*args)
|
|
519
|
+
try:
|
|
520
|
+
await asyncio.wait_for(self._owner_ready.wait(), timeout=self._timeout)
|
|
521
|
+
except TimeoutError as e:
|
|
522
|
+
# Owner task is stuck, cancel it and raise
|
|
523
|
+
if self._owner_task and not self._owner_task.done():
|
|
524
|
+
self._owner_task.cancel()
|
|
525
|
+
raise ConnectionError(
|
|
526
|
+
f"Session for {self.server_name} initialization timed out after {self._timeout}s"
|
|
527
|
+
) from e
|
|
528
|
+
if self._owner_exception:
|
|
529
|
+
# Propagate the error instead of silently returning None
|
|
530
|
+
raise ConnectionError(
|
|
531
|
+
f"Session for {self.server_name} failed: {self._owner_exception}"
|
|
532
|
+
) from self._owner_exception
|
|
533
|
+
|
|
534
|
+
# Check if owner task died after initialization (race condition guard)
|
|
535
|
+
if self._owner_task is None or self._owner_task.done():
|
|
536
|
+
raise ConnectionError(f"Session for {self.server_name} is no longer active")
|
|
537
|
+
|
|
538
|
+
loop = asyncio.get_running_loop()
|
|
539
|
+
future: asyncio.Future = loop.create_future()
|
|
540
|
+
await self._request_queue.put((func, args, future, shutdown))
|
|
541
|
+
return await future
|
|
542
|
+
|
|
543
|
+
async def _initialize_impl(self) -> None:
|
|
544
|
+
"""Initialize the underlying MCP session on the owner task."""
|
|
545
|
+
if self._initialized:
|
|
546
|
+
return
|
|
547
|
+
|
|
548
|
+
try:
|
|
549
|
+
logger.info(f"Initializing persistent session for {self.server_name}")
|
|
550
|
+
|
|
551
|
+
# Start connection manager
|
|
552
|
+
read_stream, write_stream = await self.connection_manager.start()
|
|
553
|
+
|
|
554
|
+
# Create client session
|
|
555
|
+
self.client_session = ClientSession(read_stream, write_stream)
|
|
556
|
+
await self.client_session.__aenter__()
|
|
557
|
+
|
|
558
|
+
# MCP handshake
|
|
559
|
+
result = await self.client_session.initialize()
|
|
560
|
+
logger.debug(f"MCP handshake complete for {self.server_name}: {result.capabilities}")
|
|
561
|
+
|
|
562
|
+
# Discover and cache tools
|
|
563
|
+
if result.capabilities.tools:
|
|
564
|
+
tools_result = await self.client_session.list_tools()
|
|
565
|
+
self.tools = tools_result.tools if tools_result else []
|
|
566
|
+
self._filtered_tools_cache = None # Invalidate cache when tools change
|
|
567
|
+
logger.info(f"Cached {len(self.tools)} tools for {self.server_name}")
|
|
568
|
+
else:
|
|
569
|
+
logger.info(f"No tools available for {self.server_name}")
|
|
570
|
+
|
|
571
|
+
# Warn once per initialization if allowed_tools references unknown names
|
|
572
|
+
if self._allowed_tools_set:
|
|
573
|
+
self._warn_on_unknown_allowed_tools(list(self._allowed_tools_set), self.tools)
|
|
574
|
+
|
|
575
|
+
# Discover resources (for future use)
|
|
576
|
+
if result.capabilities.resources:
|
|
577
|
+
try:
|
|
578
|
+
resources_result = await self.client_session.list_resources()
|
|
579
|
+
if resources_result and resources_result.resources:
|
|
580
|
+
logger.debug(f"Found {len(resources_result.resources)} resources for {self.server_name}")
|
|
581
|
+
except Exception:
|
|
582
|
+
logger.debug(f"Could not list resources for {self.server_name}, skipping")
|
|
583
|
+
|
|
584
|
+
self._initialized = True
|
|
585
|
+
logger.info(f"Session initialization complete for {self.server_name}")
|
|
586
|
+
|
|
587
|
+
except Exception as e:
|
|
588
|
+
logger.error(f"Failed to initialize session for {self.server_name}: {e}", exc_info=True)
|
|
589
|
+
await self._cleanup_on_error()
|
|
590
|
+
raise ConnectionError(f"Failed to initialize MCP session for {self.server_name}: {str(e)}") from e
|
|
591
|
+
|
|
592
|
+
async def _disconnect_impl(self) -> None:
|
|
593
|
+
"""Disconnect the underlying MCP session on the owner task."""
|
|
594
|
+
try:
|
|
595
|
+
# Close client session
|
|
596
|
+
if self.client_session:
|
|
597
|
+
try:
|
|
598
|
+
await self.client_session.__aexit__(None, None, None)
|
|
599
|
+
except Exception as e:
|
|
600
|
+
logger.warning(f"Error closing client session for {self.server_name}: {e}")
|
|
601
|
+
self.client_session = None
|
|
602
|
+
|
|
603
|
+
# Stop connection manager
|
|
604
|
+
await self.connection_manager.stop()
|
|
605
|
+
|
|
606
|
+
except Exception as e:
|
|
607
|
+
logger.error(f"Error during disconnect for {self.server_name}: {e}")
|
|
608
|
+
finally:
|
|
609
|
+
self._initialized = False
|
|
610
|
+
self.tools.clear()
|
|
611
|
+
self._filtered_tools_cache = None # Clear cache on disconnect
|
|
612
|
+
logger.info(f"Session disconnected for {self.server_name}")
|
|
@@ -2,6 +2,7 @@ from _typeshed import Incomplete
|
|
|
2
2
|
from aip_agents.mcp.client.connection_manager import MCPConnectionManager as MCPConnectionManager
|
|
3
3
|
from aip_agents.mcp.utils.config_validator import validate_allowed_tools_list as validate_allowed_tools_list
|
|
4
4
|
from aip_agents.utils.logger import get_logger as get_logger
|
|
5
|
+
from collections.abc import Awaitable as Awaitable
|
|
5
6
|
from gllm_tools.mcp.client.config import MCPConfiguration
|
|
6
7
|
from mcp import ClientSession
|
|
7
8
|
from mcp.types import CallToolResult, Tool as Tool
|
|
@@ -90,6 +91,7 @@ class PersistentMCPSession:
|
|
|
90
91
|
"""Disconnect session gracefully.
|
|
91
92
|
|
|
92
93
|
This method cleans up all resources and connections.
|
|
94
|
+
Always succeeds, even if the session was already in an error state.
|
|
93
95
|
"""
|
|
94
96
|
@property
|
|
95
97
|
def is_initialized(self) -> bool:
|
|
@@ -98,6 +100,13 @@ class PersistentMCPSession:
|
|
|
98
100
|
Returns:
|
|
99
101
|
bool: True if initialized and connected, False otherwise
|
|
100
102
|
"""
|
|
103
|
+
@property
|
|
104
|
+
def allowed_tools(self) -> list[str] | None:
|
|
105
|
+
"""Return the configured allowed tools, sorted if present.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
Sorted list of allowed tool names, or None if unrestricted.
|
|
109
|
+
"""
|
|
101
110
|
def update_allowed_tools(self, allowed_tools: list[str] | None) -> bool:
|
|
102
111
|
"""Update the list of allowed tools for this session.
|
|
103
112
|
|
|
@@ -12,10 +12,11 @@ from collections.abc import AsyncIterator
|
|
|
12
12
|
from enum import StrEnum
|
|
13
13
|
from typing import Any, Protocol
|
|
14
14
|
|
|
15
|
+
import httpx
|
|
15
16
|
from gllm_tools.mcp.client.config import MCPConfiguration
|
|
16
17
|
from mcp.client.sse import sse_client
|
|
17
18
|
from mcp.client.stdio import StdioServerParameters, stdio_client
|
|
18
|
-
from mcp.client.streamable_http import
|
|
19
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
19
20
|
|
|
20
21
|
from aip_agents.utils.logger import get_logger
|
|
21
22
|
|
|
@@ -142,6 +143,27 @@ class SSETransport(Transport):
|
|
|
142
143
|
class HTTPTransport(Transport):
|
|
143
144
|
"""Streamable HTTP transport handler."""
|
|
144
145
|
|
|
146
|
+
def __init__(self, server_name: str, config: MCPConfiguration) -> None:
|
|
147
|
+
"""Initialize the HTTP transport.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
server_name (str): Name of the MCP server.
|
|
151
|
+
config (MCPConfiguration): Configuration for the transport.
|
|
152
|
+
"""
|
|
153
|
+
super().__init__(server_name, config)
|
|
154
|
+
self._http_client: httpx.AsyncClient | None = None
|
|
155
|
+
|
|
156
|
+
async def close(self) -> None:
|
|
157
|
+
"""Clean up the transport connection and any owned HTTP client."""
|
|
158
|
+
await super().close()
|
|
159
|
+
if self._http_client:
|
|
160
|
+
try:
|
|
161
|
+
await self._http_client.aclose()
|
|
162
|
+
except Exception as e:
|
|
163
|
+
logger.warning(f"Error during HTTP client cleanup for {self.server_name}: {e}")
|
|
164
|
+
finally:
|
|
165
|
+
self._http_client = None
|
|
166
|
+
|
|
145
167
|
async def connect(self) -> tuple[AsyncIterator[bytes], AsyncIterator[bytes], TransportContext]:
|
|
146
168
|
"""Connect using streamable HTTP transport.
|
|
147
169
|
|
|
@@ -163,11 +185,20 @@ class HTTPTransport(Transport):
|
|
|
163
185
|
headers = _sanitize_headers(self.config)
|
|
164
186
|
logger.debug(f"Attempting streamable HTTP connection to {url} with headers: {list(headers.keys())}")
|
|
165
187
|
try:
|
|
166
|
-
|
|
188
|
+
http_client = httpx.AsyncClient(timeout=httpx.Timeout(timeout), headers=headers)
|
|
189
|
+
self._http_client = http_client
|
|
190
|
+
self.ctx = streamable_http_client(url=url, http_client=http_client)
|
|
167
191
|
read_stream, write_stream, _ = await self.ctx.__aenter__()
|
|
168
192
|
logger.info(f"Connected to {self.server_name} via HTTP")
|
|
169
193
|
return read_stream, write_stream, self.ctx
|
|
170
194
|
except Exception as e:
|
|
195
|
+
if self._http_client:
|
|
196
|
+
try:
|
|
197
|
+
await self._http_client.aclose()
|
|
198
|
+
except Exception as close_exc:
|
|
199
|
+
logger.warning(f"Error during HTTP client cleanup for {self.server_name}: {close_exc}")
|
|
200
|
+
finally:
|
|
201
|
+
self._http_client = None
|
|
171
202
|
raise ConnectionError(f"HTTP connection failed for {self.server_name}: {str(e)}") from e
|
|
172
203
|
|
|
173
204
|
|
|
@@ -77,6 +77,15 @@ class SSETransport(Transport):
|
|
|
77
77
|
|
|
78
78
|
class HTTPTransport(Transport):
|
|
79
79
|
"""Streamable HTTP transport handler."""
|
|
80
|
+
def __init__(self, server_name: str, config: MCPConfiguration) -> None:
|
|
81
|
+
"""Initialize the HTTP transport.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
server_name (str): Name of the MCP server.
|
|
85
|
+
config (MCPConfiguration): Configuration for the transport.
|
|
86
|
+
"""
|
|
87
|
+
async def close(self) -> None:
|
|
88
|
+
"""Clean up the transport connection and any owned HTTP client."""
|
|
80
89
|
ctx: Incomplete
|
|
81
90
|
async def connect(self) -> tuple[AsyncIterator[bytes], AsyncIterator[bytes], TransportContext]:
|
|
82
91
|
"""Connect using streamable HTTP transport.
|