Fix Claude Desktop loading: lazy NAS connection on first tool call
Previously the server blocked at startup waiting for query_api_info()
and login() before starting the MCP protocol. Claude Desktop has a short
initialization timeout and dropped the server before the handshake started.
Changes:
- DsmClient: add _ensure_initialized() with asyncio.Lock for thread-safe
lazy init; called automatically at the start of request(), upload_text(),
and download_text() on the first use.
- cli.py serve: remove upfront query_api_info() and auth.login() calls;
the server now starts immediately ("MCP server ready" on stderr) and
connects to the NAS on the first tool invocation.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -98,6 +98,8 @@ class DsmClient:
|
||||
self._sid: str | None = None
|
||||
self._auth_manager: AuthManager | None = None
|
||||
self._reauth_lock = asyncio.Lock()
|
||||
self._init_lock = asyncio.Lock()
|
||||
self._initialized = False
|
||||
logger.debug(
|
||||
"DsmClient: base_url=%s verify_ssl=%s timeout=%d",
|
||||
self._base_url,
|
||||
@@ -118,6 +120,24 @@ class DsmClient:
|
||||
"""Register the AuthManager for automatic re-login on session errors."""
|
||||
self._auth_manager = auth_manager
|
||||
|
||||
async def _ensure_initialized(self) -> None:
|
||||
"""Connect to NAS and authenticate on first use (lazy init).
|
||||
|
||||
Subsequent calls are no-ops. Thread-safe via asyncio.Lock.
|
||||
"""
|
||||
if self._initialized:
|
||||
return
|
||||
async with self._init_lock:
|
||||
if self._initialized: # re-check inside lock
|
||||
return
|
||||
logger.debug("Lazy init: querying API info from %s", self._base_url)
|
||||
await self.query_api_info()
|
||||
if self._auth_manager:
|
||||
logger.debug("Lazy init: authenticating")
|
||||
self._sid = await self._auth_manager.login(self)
|
||||
self._initialized = True
|
||||
logger.debug("Lazy init complete")
|
||||
|
||||
async def __aenter__(self) -> DsmClient:
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
@@ -204,6 +224,7 @@ class DsmClient:
|
||||
Raises:
|
||||
SynologyError: On API errors.
|
||||
"""
|
||||
await self._ensure_initialized()
|
||||
http = self._get_http()
|
||||
|
||||
if api not in self._api_cache:
|
||||
@@ -278,6 +299,7 @@ class DsmClient:
|
||||
Response data dict.
|
||||
"""
|
||||
api = "SYNO.FileStation.Upload"
|
||||
await self._ensure_initialized()
|
||||
http = self._get_http()
|
||||
|
||||
if api not in self._api_cache:
|
||||
@@ -328,6 +350,7 @@ class DsmClient:
|
||||
File content as string.
|
||||
"""
|
||||
api = "SYNO.FileStation.Download"
|
||||
await self._ensure_initialized()
|
||||
http = self._get_http()
|
||||
|
||||
if api not in self._api_cache:
|
||||
|
||||
Reference in New Issue
Block a user