|
| 1 | +"""Async operations management for FastMCP servers.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import secrets |
| 7 | +import time |
| 8 | +from collections.abc import Callable |
| 9 | +from dataclasses import dataclass |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +import mcp.types as types |
| 13 | +from mcp.types import AsyncOperationStatus |
| 14 | + |
| 15 | + |
| 16 | +@dataclass |
| 17 | +class AsyncOperation: |
| 18 | + """Represents an async tool operation.""" |
| 19 | + |
| 20 | + token: str |
| 21 | + tool_name: str |
| 22 | + arguments: dict[str, Any] |
| 23 | + session_id: str |
| 24 | + status: AsyncOperationStatus |
| 25 | + created_at: float |
| 26 | + keep_alive: int |
| 27 | + result: types.CallToolResult | None = None |
| 28 | + error: str | None = None |
| 29 | + |
| 30 | + @property |
| 31 | + def is_expired(self) -> bool: |
| 32 | + """Check if operation has expired based on keepAlive.""" |
| 33 | + if self.status in ("completed", "failed", "canceled"): |
| 34 | + return time.time() > (self.created_at + self.keep_alive) |
| 35 | + return False |
| 36 | + |
| 37 | + @property |
| 38 | + def is_terminal(self) -> bool: |
| 39 | + """Check if operation is in a terminal state.""" |
| 40 | + return self.status in ("completed", "failed", "canceled", "unknown") |
| 41 | + |
| 42 | + |
| 43 | +class AsyncOperationManager: |
| 44 | + """Manages async tool operations with token-based tracking.""" |
| 45 | + |
| 46 | + def __init__(self, *, token_generator: Callable[[str], str] | None = None): |
| 47 | + self._operations: dict[str, AsyncOperation] = {} |
| 48 | + self._cleanup_task: asyncio.Task[None] | None = None |
| 49 | + self._cleanup_interval = 60 # Cleanup every 60 seconds |
| 50 | + self._token_generator = token_generator or self._default_token_generator |
| 51 | + |
| 52 | + def _default_token_generator(self, session_id: str) -> str: |
| 53 | + """Default token generation using random tokens.""" |
| 54 | + return secrets.token_urlsafe(32) |
| 55 | + |
| 56 | + def generate_token(self, session_id: str) -> str: |
| 57 | + """Generate a token.""" |
| 58 | + return self._token_generator(session_id) |
| 59 | + |
| 60 | + def create_operation( |
| 61 | + self, |
| 62 | + tool_name: str, |
| 63 | + arguments: dict[str, Any], |
| 64 | + session_id: str, |
| 65 | + keep_alive: int = 3600, |
| 66 | + ) -> AsyncOperation: |
| 67 | + """Create a new async operation.""" |
| 68 | + token = self.generate_token(session_id) |
| 69 | + operation = AsyncOperation( |
| 70 | + token=token, |
| 71 | + tool_name=tool_name, |
| 72 | + arguments=arguments, |
| 73 | + session_id=session_id, |
| 74 | + status="submitted", |
| 75 | + created_at=time.time(), |
| 76 | + keep_alive=keep_alive, |
| 77 | + ) |
| 78 | + self._operations[token] = operation |
| 79 | + return operation |
| 80 | + |
| 81 | + def get_operation(self, token: str) -> AsyncOperation | None: |
| 82 | + """Get operation by token.""" |
| 83 | + return self._operations.get(token) |
| 84 | + |
| 85 | + def mark_working(self, token: str) -> bool: |
| 86 | + """Mark operation as working.""" |
| 87 | + operation = self._operations.get(token) |
| 88 | + if not operation: |
| 89 | + return False |
| 90 | + |
| 91 | + # Can only transition to working from submitted |
| 92 | + if operation.status != "submitted": |
| 93 | + return False |
| 94 | + |
| 95 | + operation.status = "working" |
| 96 | + return True |
| 97 | + |
| 98 | + def complete_operation(self, token: str, result: types.CallToolResult) -> bool: |
| 99 | + """Complete operation with result.""" |
| 100 | + operation = self._operations.get(token) |
| 101 | + if not operation: |
| 102 | + return False |
| 103 | + |
| 104 | + # Can only complete from submitted or working states |
| 105 | + if operation.status not in ("submitted", "working"): |
| 106 | + return False |
| 107 | + |
| 108 | + operation.status = "completed" |
| 109 | + operation.result = result |
| 110 | + return True |
| 111 | + |
| 112 | + def fail_operation(self, token: str, error: str) -> bool: |
| 113 | + """Fail operation with error.""" |
| 114 | + operation = self._operations.get(token) |
| 115 | + if not operation: |
| 116 | + return False |
| 117 | + |
| 118 | + # Can only fail from submitted or working states |
| 119 | + if operation.status not in ("submitted", "working"): |
| 120 | + return False |
| 121 | + |
| 122 | + operation.status = "failed" |
| 123 | + operation.error = error |
| 124 | + return True |
| 125 | + |
| 126 | + def get_operation_result(self, token: str) -> types.CallToolResult | None: |
| 127 | + """Get result for completed operation.""" |
| 128 | + operation = self._operations.get(token) |
| 129 | + if not operation or operation.status != "completed": |
| 130 | + return None |
| 131 | + return operation.result |
| 132 | + |
| 133 | + def cancel_operation(self, token: str) -> bool: |
| 134 | + """Cancel operation.""" |
| 135 | + operation = self._operations.get(token) |
| 136 | + if not operation: |
| 137 | + return False |
| 138 | + |
| 139 | + # Can only cancel from submitted or working states |
| 140 | + if operation.status not in ("submitted", "working"): |
| 141 | + return False |
| 142 | + |
| 143 | + operation.status = "canceled" |
| 144 | + return True |
| 145 | + |
| 146 | + def remove_operation(self, token: str) -> bool: |
| 147 | + """Remove operation by token.""" |
| 148 | + return self._operations.pop(token, None) is not None |
| 149 | + |
| 150 | + def cleanup_expired_operations(self) -> int: |
| 151 | + """Remove expired operations and return count removed.""" |
| 152 | + expired_tokens = [token for token, op in self._operations.items() if op.is_expired] |
| 153 | + |
| 154 | + for token in expired_tokens: |
| 155 | + del self._operations[token] |
| 156 | + |
| 157 | + return len(expired_tokens) |
| 158 | + |
| 159 | + def get_session_operations(self, session_id: str) -> list[AsyncOperation]: |
| 160 | + """Get all operations for a session.""" |
| 161 | + return [op for op in self._operations.values() if op.session_id == session_id] |
| 162 | + |
| 163 | + def cancel_session_operations(self, session_id: str) -> int: |
| 164 | + """Cancel all operations for a session.""" |
| 165 | + session_ops = self.get_session_operations(session_id) |
| 166 | + canceled_count = 0 |
| 167 | + |
| 168 | + for op in session_ops: |
| 169 | + if not op.is_terminal: |
| 170 | + op.status = "canceled" |
| 171 | + canceled_count += 1 |
| 172 | + |
| 173 | + return canceled_count |
| 174 | + |
| 175 | + async def start_cleanup_task(self) -> None: |
| 176 | + """Start the background cleanup task.""" |
| 177 | + if self._cleanup_task is not None: |
| 178 | + return |
| 179 | + |
| 180 | + self._cleanup_task = asyncio.create_task(self._cleanup_loop()) |
| 181 | + |
| 182 | + async def stop_cleanup_task(self) -> None: |
| 183 | + """Stop the background cleanup task.""" |
| 184 | + if self._cleanup_task is not None: |
| 185 | + self._cleanup_task.cancel() |
| 186 | + try: |
| 187 | + await self._cleanup_task |
| 188 | + except asyncio.CancelledError: |
| 189 | + pass |
| 190 | + self._cleanup_task = None |
| 191 | + |
| 192 | + async def _cleanup_loop(self) -> None: |
| 193 | + """Background cleanup loop.""" |
| 194 | + while True: |
| 195 | + try: |
| 196 | + await asyncio.sleep(self._cleanup_interval) |
| 197 | + self.cleanup_expired_operations() |
| 198 | + except asyncio.CancelledError: |
| 199 | + break |
| 200 | + except Exception: |
| 201 | + # Log error but continue cleanup loop |
| 202 | + pass |
0 commit comments