feat: auto add MCP projects servers with auth API key mode#9891
feat: auto add MCP projects servers with auth API key mode#9891edwinjosechittilappilly merged 77 commits intomainfrom
Conversation
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughImplements settings to record the actual server port, refactors MCP project utilities (host/port/SSE URL resolution and config path retrieval), adds project-scoped MCP handler methods, and auto-registers MCP servers upon project creation when enabled by settings. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant CLI as CLI/Entrypoint
participant Server as Langflow Server
participant Settings as SettingsService
User->>CLI: Start server (port P requested)
CLI->>Server: Resolve available port (may adjust P)
Server-->>CLI: Final port = PF
CLI->>Settings: settings.current_port = PF
Note right of Settings: Records actual listening port
CLI->>Server: Continue startup (protocol, DB, routes)
Server-->>User: Server ready on host:PF
sequenceDiagram
autonumber
actor Client as API Client
participant API as Projects API
participant Settings as SettingsService
participant Keys as API Key Service
participant MCP as MCP Registry
participant SSE as get_project_sse_url
Client->>API: Create project
API-->>Client: Project created
API->>Settings: Check add_projects_to_mcp_servers
alt Enabled
API->>Keys: Create API key
API->>API: Encrypt project auth settings (API key)
API->>SSE: Compute project SSE URL (host/port via settings.current_port)
API->>MCP: update_server(name, command, env/headers incl. API key & SSE URL)
MCP-->>API: Registered/updated
else Disabled
Note over API: Skip MCP registration
end
sequenceDiagram
autonumber
actor MCPClient as MCP Client
participant ProjectSrv as ProjectMCPServer
participant Core as Core Handlers
MCPClient->>ProjectSrv: listTools/readResource/callTool (project-scoped)
ProjectSrv->>Core: Delegate to existing handlers with project_id
Core-->>ProjectSrv: Results
ProjectSrv-->>MCPClient: Response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/lfx/src/lfx/services/settings/base.py (1)
217-218: Make current_port ephemeral (avoid persisting to YAML).current_port is runtime-only. Exclude it from model_dump to prevent leaking transient state into saved configs.
- current_port: int | None = None + current_port: int | None = Field(default=None, exclude=True)src/backend/base/langflow/api/v1/projects.py (1)
86-125: Auto‑register MCP servers: tweak server name length and consider backgrounding.
- Off‑by‑one in truncation: subtract len('lf-') so the total length respects MAX_MCP_SERVER_NAME_LENGTH exactly.
- Optional: run the registration in a background task to avoid adding latency to project creation (keep current try/except).
- server_name = f"lf-{sanitize_mcp_name(new_project.name)[: (MAX_MCP_SERVER_NAME_LENGTH - 4)]}" + server_name = f"lf-{sanitize_mcp_name(new_project.name)[: (MAX_MCP_SERVER_NAME_LENGTH - len('lf-'))]}"src/backend/base/langflow/api/v1/mcp_projects.py (1)
894-904: Prefer https in SSE URL when TLS is enabled.get_project_sse_url always builds http://…, which breaks when running with cert/key. Detect TLS from settings and set the scheme.
- base_url = f"http://{host}:{port}".rstrip("/") + protocol = "https" if getattr(settings_service.settings, "ssl_cert_file", None) and getattr( + settings_service.settings, "ssl_key_file", None + ) else "http" + base_url = f"{protocol}://{host}:{port}".rstrip("/")
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/backend/base/langflow/__main__.py(1 hunks)src/backend/base/langflow/api/v1/mcp_projects.py(3 hunks)src/backend/base/langflow/api/v1/projects.py(3 hunks)src/lfx/src/lfx/services/settings/base.py(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
{src/backend/**/*.py,tests/**/*.py,Makefile}
📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)
{src/backend/**/*.py,tests/**/*.py,Makefile}: Run make format_backend to format Python code before linting or committing changes
Run make lint to perform linting checks on backend Python code
Files:
src/backend/base/langflow/__main__.pysrc/backend/base/langflow/api/v1/projects.pysrc/backend/base/langflow/api/v1/mcp_projects.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: deon-sanchez
PR: langflow-ai/langflow#9158
File: src/backend/base/langflow/api/v1/mcp_projects.py:404-404
Timestamp: 2025-07-23T21:19:22.567Z
Learning: In langflow MCP projects configuration, prefer using dynamically computed URLs (like the `sse_url` variable) over hardcoded localhost URLs to ensure compatibility across different deployment environments.
📚 Learning: 2025-07-23T21:19:22.567Z
Learnt from: deon-sanchez
PR: langflow-ai/langflow#9158
File: src/backend/base/langflow/api/v1/mcp_projects.py:404-404
Timestamp: 2025-07-23T21:19:22.567Z
Learning: In langflow MCP projects configuration, prefer using dynamically computed URLs (like the `sse_url` variable) over hardcoded localhost URLs to ensure compatibility across different deployment environments.
Applied to files:
src/backend/base/langflow/api/v1/mcp_projects.py
🧬 Code graph analysis (3)
src/backend/base/langflow/__main__.py (1)
src/backend/base/langflow/services/deps.py (1)
get_settings_service(111-124)
src/backend/base/langflow/api/v1/projects.py (7)
src/frontend/src/constants/constants.ts (1)
MAX_MCP_SERVER_NAME_LENGTH(562-562)src/backend/base/langflow/api/v1/mcp_projects.py (1)
get_project_sse_url(890-930)src/backend/base/langflow/api/v2/mcp.py (1)
update_server(201-245)src/backend/base/langflow/services/auth/mcp_encryption.py (1)
encrypt_auth_settings(18-51)src/backend/base/langflow/services/database/models/api_key/crud.py (1)
create_api_key(24-40)src/backend/base/langflow/services/database/models/api_key/model.py (1)
ApiKeyCreate(39-47)src/backend/base/langflow/services/deps.py (2)
get_settings_service(111-124)get_storage_service(88-96)
src/backend/base/langflow/api/v1/mcp_projects.py (1)
src/backend/tests/unit/api/v2/test_mcp_servers_file.py (1)
settings_service(95-96)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (16)
- GitHub Check: Lint Backend / Run Mypy (3.10)
- GitHub Check: Lint Backend / Run Mypy (3.11)
- GitHub Check: Lint Backend / Run Mypy (3.12)
- GitHub Check: Lint Backend / Run Mypy (3.13)
- GitHub Check: Run Frontend Tests / Determine Test Suites and Shard Distribution
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 5
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 2
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 4
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 1
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 3
- GitHub Check: Test Starter Templates
- GitHub Check: Run Backend Tests / Integration Tests - Python 3.10
- GitHub Check: Ruff Style Check (3.13)
- GitHub Check: Optimize new Python code in this PR
- GitHub Check: Update Starter Projects
- GitHub Check: Run Ruff Check and Format
🔇 Additional comments (4)
src/lfx/src/lfx/services/settings/base.py (1)
268-272: LGTM: feature flag is clear and env‑wired.Consider adding this to the user‑visible settings docs/ENV list so operators know about LANGFLOW_ADD_PROJECTS_TO_MCP_SERVERS.
src/backend/base/langflow/api/v1/projects.py (1)
15-17: Imports for MCP auto‑registration look correct.No issues spotted with symbol locations or dependency direction.
Also applies to: 24-24, 26-26, 30-33, 43-43
src/backend/base/langflow/api/v1/mcp_projects.py (2)
51-53: LGTM: centralized ALL_INTERFACES_HOST.Good replacement for hardcoded "0.0.0.0".
454-456: LGTM: use ALL_INTERFACES_HOST in local IP check.Keeps logic consistent and readable.
Codecov Report❌ Patch coverage is ❌ Your project status has failed because the head coverage (47.04%) is below the target coverage (55.00%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #9891 +/- ##
==========================================
+ Coverage 23.68% 24.14% +0.45%
==========================================
Files 1090 1091 +1
Lines 39768 40014 +246
Branches 5542 5543 +1
==========================================
+ Hits 9421 9660 +239
- Misses 30176 30183 +7
Partials 171 171
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
|
Added Do Not Merge label until we determine intersection between this work and the pending release merge |
Added a TODO comment to improve the method for determining the position of the SSE URL in the argument list within validate_mcp_server_for_project.
…-ai/langflow into lf-auto-add-mcp-servers
| assert str(test_project.id) in result.conflict_message | ||
|
|
||
| # Cleanup - delete the server | ||
| await client.delete(f"/api/v2/mcp/servers/{server_name}", headers={"x-api-key": created_api_key.api_key}) |
There was a problem hiding this comment.
nit: could put the delete into a fixture so we don't forget it in any test
There was a problem hiding this comment.
Can we connect on more details, I would be happy to add but I have few queries.
| # Note: Due to database constraints, mcp_enabled defaults to False instead of None | ||
| # The auto_configure function only acts when mcp_enabled is None, so in this case | ||
| # the flow configuration won't be updated. This test verifies the function runs | ||
| # without error even when flows are already configured (mcp_enabled=False). |
There was a problem hiding this comment.
Should this be True instead of None? Not sure I understand the None aspect otherwise.
…tings pages for testing purposes 🔧 (frontend): add convertTestName utility function for converting test names to lowercase with hyphens 🔧 (frontend): add cleanOldFolders utility function to remove old folders in testing environment 🔧 (frontend): add navigateSettingsPages utility function to navigate to specific settings pages in testing
…flow into lf-auto-add-mcp-servers
…havior ✨ (use-patch-flows-mcp.ts): add retry: 0 option to improve mutation behavior ✨ (use-patch-install-mcp.ts): add retry: 0 option to improve mutation behavior ✨ (use-patch-mcp-server.ts): add retry: 0 option to improve mutation behavior 📝 (mcp-server-starter-projects.spec.ts): add test to prevent adding duplicate mcp servers from starter projects
…orTimeout to 5000ms for stability ⬆️ (starter-projects.spec.ts): adjust timeout value to 5000 * 3 for better performance and reliability
⚡️ Codeflash found optimizations for this PR📄 12% (0.12x) speedup for
|
|


This pull request introduces significant improvements to the MCP (Multi-Component Project) server configuration and API utilities in the backend. The main changes include refactoring and centralizing MCP utility functions, enhancing the auto-configuration process for starter projects, and improving runtime port handling for better compatibility. These updates result in cleaner code organization, easier maintenance, and more robust handling of project/server relationships.
MCP Server Configuration and Starter Projects:
auto_configure_starter_projects_mcp,get_project_sse_url, andget_url_by_osutility functions tolangflow.api.utils.mcp, centralizing MCP logic and enabling automatic MCP server setup for starter projects per user at startup. [1] [2] [3] [4]validate_mcp_server_for_projectto robustly check for server/project conflicts and ensure correct server assignment, preventing accidental overwrites or mismatches.API Utilities Refactoring:
langflow.api.utilsto re-export all core utilities for backward compatibility and improved code organization, including explicit__all__exports for IDE/documentation support.langflow.api.utils.mcp) with clear exports for MCP-related helper functions.Runtime Port Handling:
Codebase Cleanup and Consistency:
get_project_sse_urlandget_url_by_osfrommcp_projects.py, replacing them with imports from the new MCP utilities module for consistency and maintainability. [1] [2]ALL_INTERFACES_HOSTconstant throughout the codebase for clarity and consistency. [1] [2]Logging and Debugging Enhancements:
These changes collectively improve the reliability, maintainability, and scalability of MCP server management and API utilities in the project.