Signal the context task to close and wait for cleanup.
(self)
| 215 | raise ConnectionError(f'MCP session connection lost: {exc}') from exc |
| 216 | |
| 217 | async def close(self): |
| 218 | """Signal the context task to close and wait for cleanup.""" |
| 219 | # Set the close event to signal the task to close. |
| 220 | # Even if start has not been called, we need to set the close event |
| 221 | # to signal the task to close right away. |
| 222 | async with self._task_lock: |
| 223 | self._close_event.set() |
| 224 | |
| 225 | # If start has not been called, only set the close event and return |
| 226 | if not self._task: |
| 227 | return |
| 228 | |
| 229 | if not self._ready_event.is_set(): |
| 230 | self._task.cancel() |
| 231 | |
| 232 | try: |
| 233 | await asyncio.wait_for(self._task, timeout=self._timeout) |
| 234 | except asyncio.TimeoutError: |
| 235 | logger.warning('Failed to close MCP session: task timed out') |
| 236 | self._task.cancel() |
| 237 | except asyncio.CancelledError: |
| 238 | pass |
| 239 | except Exception as e: |
| 240 | logger.warning(f'Failed to close MCP session: {e}') |
| 241 | |
| 242 | async def __aenter__(self) -> ClientSession: |
| 243 | return await self.start() |