mirror of
https://gitee.com/wanwujie/deer-flow
synced 2026-04-12 01:54:45 +08:00
* refactor: extract shared utils to break harness→app cross-layer imports Move _validate_skill_frontmatter to src/skills/validation.py and CONVERTIBLE_EXTENSIONS + convert_file_to_markdown to src/utils/file_conversion.py. This eliminates the two reverse dependencies from client.py (harness layer) into gateway/routers/ (app layer), preparing for the harness/app package split. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: split backend/src into harness (deerflow.*) and app (app.*) Physically split the monolithic backend/src/ package into two layers: - **Harness** (`packages/harness/deerflow/`): publishable agent framework package with import prefix `deerflow.*`. Contains agents, sandbox, tools, models, MCP, skills, config, and all core infrastructure. - **App** (`app/`): unpublished application code with import prefix `app.*`. Contains gateway (FastAPI REST API) and channels (IM integrations). Key changes: - Move 13 harness modules to packages/harness/deerflow/ via git mv - Move gateway + channels to app/ via git mv - Rename all imports: src.* → deerflow.* (harness) / app.* (app layer) - Set up uv workspace with deerflow-harness as workspace member - Update langgraph.json, config.example.yaml, all scripts, Docker files - Add build-system (hatchling) to harness pyproject.toml - Add PYTHONPATH=. to gateway startup commands for app.* resolution - Update ruff.toml with known-first-party for import sorting - Update all documentation to reflect new directory structure Boundary rule enforced: harness code never imports from app. All 429 tests pass. Lint clean. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: add harness→app boundary check test and update docs Add test_harness_boundary.py that scans all Python files in packages/harness/deerflow/ and fails if any `from app.*` or `import app.*` statement is found. This enforces the architectural rule that the harness layer never depends on the app layer. Update CLAUDE.md to document the harness/app split architecture, import conventions, and the boundary enforcement test. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: add config versioning with auto-upgrade on startup When config.example.yaml schema changes, developers' local config.yaml files can silently become outdated. This adds a config_version field and auto-upgrade mechanism so breaking changes (like src.* → deerflow.* renames) are applied automatically before services start. - Add config_version: 1 to config.example.yaml - Add startup version check warning in AppConfig.from_file() - Add scripts/config-upgrade.sh with migration registry for value replacements - Add `make config-upgrade` target - Auto-run config-upgrade in serve.sh and start-daemon.sh before starting services - Add config error hints in service failure messages Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix comments * fix: update src.* import in test_sandbox_tools_security to deerflow.* Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: handle empty config and search parent dirs for config.example.yaml Address Copilot review comments on PR #1131: - Guard against yaml.safe_load() returning None for empty config files - Search parent directories for config.example.yaml instead of only looking next to config.yaml, fixing detection in common setups Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: correct skills root path depth and config_version type coercion - loader.py: fix get_skills_root_path() to use 5 parent levels (was 3) after harness split, file lives at packages/harness/deerflow/skills/ so parent×3 resolved to backend/packages/harness/ instead of backend/ - app_config.py: coerce config_version to int() before comparison in _check_config_version() to prevent TypeError when YAML stores value as string (e.g. config_version: "1") - tests: add regression tests for both fixes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: update test imports from src.* to deerflow.*/app.* after harness refactor Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
139 lines
4.5 KiB
Python
139 lines
4.5 KiB
Python
"""Cache for MCP tools to avoid repeated loading."""
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
|
|
from langchain_core.tools import BaseTool
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_mcp_tools_cache: list[BaseTool] | None = None
|
|
_cache_initialized = False
|
|
_initialization_lock = asyncio.Lock()
|
|
_config_mtime: float | None = None # Track config file modification time
|
|
|
|
|
|
def _get_config_mtime() -> float | None:
|
|
"""Get the modification time of the extensions config file.
|
|
|
|
Returns:
|
|
The modification time as a float, or None if the file doesn't exist.
|
|
"""
|
|
from deerflow.config.extensions_config import ExtensionsConfig
|
|
|
|
config_path = ExtensionsConfig.resolve_config_path()
|
|
if config_path and config_path.exists():
|
|
return os.path.getmtime(config_path)
|
|
return None
|
|
|
|
|
|
def _is_cache_stale() -> bool:
|
|
"""Check if the cache is stale due to config file changes.
|
|
|
|
Returns:
|
|
True if the cache should be invalidated, False otherwise.
|
|
"""
|
|
global _config_mtime
|
|
|
|
if not _cache_initialized:
|
|
return False # Not initialized yet, not stale
|
|
|
|
current_mtime = _get_config_mtime()
|
|
|
|
# If we couldn't get mtime before or now, assume not stale
|
|
if _config_mtime is None or current_mtime is None:
|
|
return False
|
|
|
|
# If the config file has been modified since we cached, it's stale
|
|
if current_mtime > _config_mtime:
|
|
logger.info(f"MCP config file has been modified (mtime: {_config_mtime} -> {current_mtime}), cache is stale")
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
async def initialize_mcp_tools() -> list[BaseTool]:
|
|
"""Initialize and cache MCP tools.
|
|
|
|
This should be called once at application startup.
|
|
|
|
Returns:
|
|
List of LangChain tools from all enabled MCP servers.
|
|
"""
|
|
global _mcp_tools_cache, _cache_initialized, _config_mtime
|
|
|
|
async with _initialization_lock:
|
|
if _cache_initialized:
|
|
logger.info("MCP tools already initialized")
|
|
return _mcp_tools_cache or []
|
|
|
|
from deerflow.mcp.tools import get_mcp_tools
|
|
|
|
logger.info("Initializing MCP tools...")
|
|
_mcp_tools_cache = await get_mcp_tools()
|
|
_cache_initialized = True
|
|
_config_mtime = _get_config_mtime() # Record config file mtime
|
|
logger.info(f"MCP tools initialized: {len(_mcp_tools_cache)} tool(s) loaded (config mtime: {_config_mtime})")
|
|
|
|
return _mcp_tools_cache
|
|
|
|
|
|
def get_cached_mcp_tools() -> list[BaseTool]:
|
|
"""Get cached MCP tools with lazy initialization.
|
|
|
|
If tools are not initialized, automatically initializes them.
|
|
This ensures MCP tools work in both FastAPI and LangGraph Studio contexts.
|
|
|
|
Also checks if the config file has been modified since last initialization,
|
|
and re-initializes if needed. This ensures that changes made through the
|
|
Gateway API (which runs in a separate process) are reflected in the
|
|
LangGraph Server.
|
|
|
|
Returns:
|
|
List of cached MCP tools.
|
|
"""
|
|
global _cache_initialized
|
|
|
|
# Check if cache is stale due to config file changes
|
|
if _is_cache_stale():
|
|
logger.info("MCP cache is stale, resetting for re-initialization...")
|
|
reset_mcp_tools_cache()
|
|
|
|
if not _cache_initialized:
|
|
logger.info("MCP tools not initialized, performing lazy initialization...")
|
|
try:
|
|
# Try to initialize in the current event loop
|
|
loop = asyncio.get_event_loop()
|
|
if loop.is_running():
|
|
# If loop is already running (e.g., in LangGraph Studio),
|
|
# we need to create a new loop in a thread
|
|
import concurrent.futures
|
|
|
|
with concurrent.futures.ThreadPoolExecutor() as executor:
|
|
future = executor.submit(asyncio.run, initialize_mcp_tools())
|
|
future.result()
|
|
else:
|
|
# If no loop is running, we can use the current loop
|
|
loop.run_until_complete(initialize_mcp_tools())
|
|
except RuntimeError:
|
|
# No event loop exists, create one
|
|
asyncio.run(initialize_mcp_tools())
|
|
except Exception as e:
|
|
logger.error(f"Failed to lazy-initialize MCP tools: {e}")
|
|
return []
|
|
|
|
return _mcp_tools_cache or []
|
|
|
|
|
|
def reset_mcp_tools_cache() -> None:
|
|
"""Reset the MCP tools cache.
|
|
|
|
This is useful for testing or when you want to reload MCP tools.
|
|
"""
|
|
global _mcp_tools_cache, _cache_initialized, _config_mtime
|
|
_mcp_tools_cache = None
|
|
_cache_initialized = False
|
|
_config_mtime = None
|
|
logger.info("MCP tools cache reset")
|