Files
deer-flow/backend/src/gateway/app.py
hetaoBackend 74d4a16492 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>
2026-01-19 18:58:13 +08:00

78 lines
2.1 KiB
Python

import logging
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from src.gateway.config import get_gateway_config
from src.gateway.routers import artifacts, models, proxy
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Application lifespan handler."""
config = get_gateway_config()
logger.info(f"Starting API Gateway on {config.host}:{config.port}")
logger.info(f"Proxying to LangGraph server at {config.langgraph_url}")
# Initialize MCP tools at startup
try:
from src.mcp import initialize_mcp_tools
await initialize_mcp_tools()
except Exception as e:
logger.warning(f"Failed to initialize MCP tools: {e}")
yield
logger.info("Shutting down API Gateway")
# Close the shared HTTP client
await proxy.close_http_client()
def create_app() -> FastAPI:
"""Create and configure the FastAPI application.
Returns:
Configured FastAPI application instance.
"""
app = FastAPI(
title="DeerFlow API Gateway",
description="API Gateway for DeerFlow - proxies to LangGraph Server and provides custom endpoints",
version="0.1.0",
lifespan=lifespan,
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
# Models API is mounted at /api/models
app.include_router(models.router)
# Artifacts API is mounted at /api/threads/{thread_id}/artifacts
app.include_router(artifacts.router)
# Proxy router handles all LangGraph paths (must be last due to catch-all)
app.include_router(proxy.router)
@app.get("/health")
async def health_check() -> dict:
"""Health check endpoint."""
return {"status": "healthy", "service": "deer-flow-gateway"}
return app
# Create app instance for uvicorn
app = create_app()