sync update from LAN repo (source dhk-1 @ 3b1ec5b4)
This commit is contained in:
1 parent
da6521b6cb
commit
264e2200d6
995 files changed
+148105
-13399
No files matched your search
@@ -3,6 +3,9 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
|
||||
from langchain_core.tools import BaseTool
|
||||
|
||||
@@ -12,6 +15,40 @@ _mcp_tools_cache: list[BaseTool] | None = None
|
||||
_cache_initialized = False
|
||||
_initialization_lock = asyncio.Lock()
|
||||
_config_mtime: float | None = None # Track config file modification time
|
||||
_owner_initialization_loop: ContextVar[asyncio.AbstractEventLoop | None] = ContextVar("mcp_initialization_loop", default=None)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mcp_initialization_loop(loop: asyncio.AbstractEventLoop) -> Iterator[None]:
|
||||
"""Keep MCP discovery on the owning request loop during background builds.
|
||||
|
||||
The factory's synchronous worker may wait for discovery, but the gateway
|
||||
loop remains free to run other requests and owns the shared async lock.
|
||||
"""
|
||||
token = _owner_initialization_loop.set(loop)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_owner_initialization_loop.reset(token)
|
||||
|
||||
|
||||
def _initialize_on_owner_loop(loop: asyncio.AbstractEventLoop) -> list[BaseTool]:
|
||||
try:
|
||||
# Submitting to an inactive loop would leave future.result() waiting
|
||||
# forever. Do not fall back to another loop for explicitly owned work.
|
||||
if loop.is_closed() or not loop.is_running():
|
||||
raise RuntimeError("MCP initialization owner loop is not running")
|
||||
initialization = initialize_mcp_tools()
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(initialization, loop)
|
||||
except BaseException:
|
||||
initialization.close()
|
||||
raise
|
||||
future.result()
|
||||
except Exception:
|
||||
logger.exception("Failed to lazy-initialize MCP tools on the owner loop")
|
||||
return []
|
||||
return _mcp_tools_cache or []
|
||||
|
||||
|
||||
def _get_config_mtime() -> float | None:
|
||||
@@ -102,6 +139,14 @@ def get_cached_mcp_tools() -> list[BaseTool]:
|
||||
|
||||
if not _cache_initialized:
|
||||
logger.info("MCP tools not initialized, performing lazy initialization...")
|
||||
owner_loop = _owner_initialization_loop.get()
|
||||
if owner_loop is not None:
|
||||
try:
|
||||
current_loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
current_loop = None
|
||||
if current_loop is not owner_loop:
|
||||
return _initialize_on_owner_loop(owner_loop)
|
||||
try:
|
||||
# Try to initialize in the current event loop
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
Reference in new issue
Block a user