feat: add MCP (Model Context Protocol) support

Add comprehensive MCP integration using langchain-mcp-adapters to enable
pluggable external tools from MCP servers.

Features:
- MCP server configuration via mcp_config.json
- Automatic lazy initialization for seamless use in both FastAPI and LangGraph Studio
- Support for multiple MCP servers (filesystem, postgres, github, brave-search, etc.)
- Environment variable resolution in configuration
- Tool caching mechanism for optimal performance
- Complete documentation and setup guide

Implementation:
- Add src/mcp module with client, tools, and cache components
- Integrate MCP config loading in AppConfig
- Update tool system to include MCP tools automatically
- Add eager initialization in FastAPI lifespan handler
- Add lazy initialization fallback for LangGraph Studio

Dependencies:
- Add langchain-mcp-adapters>=0.1.0

Documentation:
- Add MCP_SETUP.md with comprehensive setup guide
- Update CLAUDE.md with MCP system architecture
- Update config.example.yaml with MCP configuration notes
- Update README.md with MCP setup instructions

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hetaoBackend
2026-01-19 18:57:16 +08:00
parent 21f35b1d3c
commit 74d4a16492
19 changed files with 1044 additions and 5 deletions

View File

@@ -1,17 +1,47 @@
import logging
from langchain.tools import BaseTool
from src.config import get_app_config
from src.reflection import resolve_variable
from src.tools.builtins import ask_clarification_tool, present_file_tool
logger = logging.getLogger(__name__)
BUILTIN_TOOLS = [
present_file_tool,
ask_clarification_tool,
]
def get_available_tools(groups: list[str] | None = None) -> list[BaseTool]:
"""Get all available tools from config"""
def get_available_tools(groups: list[str] | None = None, include_mcp: bool = True) -> list[BaseTool]:
"""Get all available tools from config.
Note: MCP tools should be initialized at application startup using
`initialize_mcp_tools()` from src.mcp module.
Args:
groups: Optional list of tool groups to filter by.
include_mcp: Whether to include tools from MCP servers (default: True).
Returns:
List of available tools.
"""
config = get_app_config()
loaded_tools = [resolve_variable(tool.use, BaseTool) for tool in config.tools if groups is None or tool.group in groups]
return loaded_tools + BUILTIN_TOOLS
# Get cached MCP tools if enabled
mcp_tools = []
if include_mcp and config.mcp and config.mcp.get_enabled_servers():
try:
from src.mcp.cache import get_cached_mcp_tools
mcp_tools = get_cached_mcp_tools()
if mcp_tools:
logger.debug(f"Using {len(mcp_tools)} cached MCP tool(s)")
except ImportError:
logger.warning("MCP module not available. Install 'langchain-mcp-adapters' package to enable MCP tools.")
except Exception as e:
logger.error(f"Failed to get cached MCP tools: {e}")
return loaded_tools + BUILTIN_TOOLS + mcp_tools