Skip to content

Conversation

edwinjosechittilappilly
Copy link
Collaborator

@edwinjosechittilappilly edwinjosechittilappilly commented Sep 17, 2025

This pull request introduces enhancements to the project creation workflow and server configuration management, focusing on automatic MCP server registration for new projects, improved handling of server port settings, and better code maintainability. The changes ensure that new projects are more seamlessly integrated into the MCP ecosystem, with secure API key authentication and accurate server connection details.

Project creation & MCP server integration:

  • Automatically registers a newly created project as an MCP server for the user if add_projects_to_mcp_servers is enabled, including secure API key generation, encrypted authentication settings, and server configuration updates in the user's _mcp_servers.json file.
  • Adds the add_projects_to_mcp_servers setting to Settings, allowing control over automatic MCP server registration via environment variable.

Server port and connection management:

  • Adds current_port to the Settings model to track the actual port Langflow is running on after resolving conflicts.
  • Updates the main entrypoint to store the actual running port in settings.current_port after checking for port availability.
  • In SSE URL generation, uses current_port if available, and always substitutes 0.0.0.0 with localhost for client connections to avoid bind/connect confusion.

Code maintainability and clarity:

  • Introduces the constant ALL_INTERFACES_HOST (0.0.0.0) for clarity and replaces hardcoded values in IP checks and host selection logic. [1] [2]
  • Refactors imports and dependencies to support new features, such as get_project_sse_url, update_server, and utility functions for MCP server management. [1] [2]

Summary by CodeRabbit

  • New Features

    • Automatically registers newly created projects as MCP servers when enabled.
    • Adds project-scoped MCP endpoints to list tools/resources, read resources, and call tools.
    • New settings: track the actual runtime port and toggle auto-added projects to MCP servers.
  • Bug Fixes

    • More reliable SSE URLs: correctly resolves host/port, handles 0.0.0.0 by using localhost, and improves WSL detection.
    • Accurately reflects the final server port in settings after conflict resolution.

Copy link
Contributor

coderabbitai bot commented Sep 17, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Implements 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

Cohort / File(s) Summary
Settings additions
src/lfx/src/lfx/services/settings/base.py
Adds Settings.current_port (int|None) and Settings.add_projects_to_mcp_servers (bool).
Server startup port resolution
src/backend/base/langflow/__main__.py
After resolving the listening port, persists it to settings.current_port before proceeding.
MCP projects utilities and endpoints
src/backend/base/langflow/api/v1/mcp_projects.py
Introduces ALL_INTERFACES_HOST; updates is_local_ip usage; refactors get_project_sse_url to derive host/port from settings with current_port fallback and WSL handling; adds async get_config_path(client) for platform-specific config locations; extends ProjectMCPServer with project-scoped handlers: list tools, list prompts, list resources, read resource, and call tool.
Project creation auto MCP registration
src/backend/base/langflow/api/v1/projects.py
After project creation, when add_projects_to_mcp_servers is true: creates API key, encrypts auth settings to API-key mode, computes project SSE URL, builds mcp-proxy config, sanitizes/limits server name, and registers/updates the MCP server; errors are logged without blocking.

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
Loading
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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

enhancement, size:XL, lgtm

Suggested reviewers

  • lucaseduoli
  • ogabrielluiz
  • phact

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly captures the primary change—automatic registration of MCP project servers using API-key authentication—and uses a conventional "feat:" prefix; it is specific and directly related to the PR's main behavior. This makes it clear to reviewers what the most important change is without listing implementation details.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 859f8da and 420dd6a.

📒 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__.py
  • src/backend/base/langflow/api/v1/projects.py
  • src/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.

Comment on lines +344 to +346
# Store the actual port being used in settings
get_settings_service().settings.current_port = port

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix port propagation across processes (spawn) to avoid wrong SSE URLs.

When the configured port is occupied and a free one is chosen, only current_port is set in the parent. On macOS (spawn) and some setups, workers may not see this and fall back to stale settings.port, producing bad SSE URLs in MCP configs.

Apply both assignments (and export env) before starting the server:

-        # Store the actual port being used in settings
-        get_settings_service().settings.current_port = port
+        # Store the actual port being used in settings (propagate to workers/spawned processes)
+        settings_service = get_settings_service()
+        settings_service.settings.current_port = port
+        settings_service.settings.port = port
+        os.environ["LANGFLOW_PORT"] = str(port)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Store the actual port being used in settings
get_settings_service().settings.current_port = port
# Store the actual port being used in settings (propagate to workers/spawned processes)
settings_service = get_settings_service()
settings_service.settings.current_port = port
settings_service.settings.port = port
os.environ["LANGFLOW_PORT"] = str(port)
🤖 Prompt for AI Agents
In src/backend/base/langflow/__main__.py around lines 344 to 346, when the
chosen port differs from the configured one only current_port is set, causing
spawned worker processes to see stale settings.port and produce wrong SSE URLs;
set both get_settings_service().settings.port and
get_settings_service().settings.current_port to the chosen port and export it to
the environment (e.g., os.environ["PORT"] = str(port)) before starting the
server so child processes inherit the correct port.

Copy link

codecov bot commented Sep 17, 2025

Codecov Report

❌ Patch coverage is 39.70588% with 82 lines in your changes missing coverage. Please review.
✅ Project coverage is 23.00%. Comparing base (a755f3d) to head (546f20f).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/backend/base/langflow/api/v1/mcp_projects.py 40.00% 66 Missing ⚠️
src/backend/base/langflow/api/v1/projects.py 36.00% 16 Missing ⚠️

❌ Your project check has failed because the head coverage (46.60%) is below the target coverage (55.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #9891      +/-   ##
==========================================
+ Coverage   22.86%   23.00%   +0.13%     
==========================================
  Files        1085     1085              
  Lines       39733    39866     +133     
  Branches     5420     5420              
==========================================
+ Hits         9084     9170      +86     
- Misses      30494    30541      +47     
  Partials      155      155              
Flag Coverage Δ
backend 46.60% <39.70%> (+0.15%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/backend/base/langflow/__main__.py 42.85% <100.00%> (+0.12%) ⬆️
src/backend/base/langflow/api/v1/projects.py 28.63% <36.00%> (+0.91%) ⬆️
src/backend/base/langflow/api/v1/mcp_projects.py 26.11% <40.00%> (+4.09%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
22.7% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant