Skip to content

Conversation

@mfortman11
Copy link
Collaborator

@mfortman11 mfortman11 commented Aug 21, 2025

Updates MCP Composer auth to be limited to oauth and api key

Feature flag is set by setting env LANGFLOW_FEATURE_MCP_COMPOSER = true

Summary by CodeRabbit

  • Refactor

    • Simplified authentication options: removed Basic, Bearer, and IAM. UI and settings now support only API Key and OAuth.
    • Streamlined MCP server setup: always uses mcp-proxy and no longer injects OAuth-related environment variables.
    • Authentication header generation now supports only API Key.
  • Chores

    • Cleaned up deprecated flags and configuration paths related to MCP Composer and OAuth env handling.

@mfortman11 mfortman11 requested a review from lucaseduoli August 21, 2025 22:04
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 21, 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

Backend and frontend remove support for Basic, Bearer, and IAM authentication, narrowing to apikey and oauth schemas/UI, while MCP runtime paths drop feature-flag branching and OAuth env propagation. MCP invocation is unified to mcp-proxy with SSE URL. Frontend MCP server JSON and header generation now only handle apikey.

Changes

Cohort / File(s) Summary
Backend: MCP config install
src/backend/base/langflow/api/v1/mcp_projects.py
Removed FEATURE_FLAGS import and branching; always builds mcp-proxy command with sse_url; removed OAuth env/args handling.
Backend: Auth schema
src/backend/base/langflow/api/v1/schemas.py
AuthSettings restricts auth_type to "none", "apikey", "oauth"; removed username, password, bearer_token, iam_endpoint fields.
Frontend: Auth modal
src/frontend/src/modals/authModal/index.tsx
Removed UI/logic for Basic, Bearer, IAM; retained API Key and OAuth fields; dropped related state syncing and save mappings.
Frontend: MCP Server Tab
src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx
getAuthHeaders now supports only apikey; removed OAuth env vars builder; MCP_SERVER_JSON always uses "mcp-proxy"; removed OAuth env insertion.
Frontend: Auth utils
src/frontend/src/utils/mcpUtils.ts
Trimmed AuthMethodId to NONE, API_KEY, OAUTH; removed BASIC, BEARER, IAM and their entries from AUTH_METHODS.

Sequence Diagram(s)

sequenceDiagram
  participant UI as Frontend UI
  participant BE as Backend API
  participant MCP as mcp-proxy

  Note over UI,BE: Install MCP config (unified flow)
  UI->>BE: POST /mcp/install (project, sse_url, auth_settings)
  BE->>BE: Build args: ["mcp-proxy", "--sse-url", sse_url]
  BE-->>MCP: Invoke process with args (no OAuth env)
  MCP-->>BE: Response/status
  BE-->>UI: Installation result
Loading
sequenceDiagram
  participant UI as MCP Server Tab
  participant Util as getAuthHeaders

  Note over UI,Util: Auth header generation
  UI->>Util: getAuthHeaders(currentAuthSettings)
  alt auth_type == "apikey"
    Util-->>UI: { "x-api-key": api_key }
  else
    Util-->>UI: {}
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

refactor, size:M

Suggested reviewers

  • lucaseduoli
  • ogabrielluiz
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch composer-auth-updates

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the refactor Maintenance tasks and housekeeping label Aug 21, 2025
@github-actions github-actions bot added refactor Maintenance tasks and housekeeping and removed refactor Maintenance tasks and housekeeping labels Aug 21, 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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/backend/base/langflow/api/v1/mcp_projects.py (1)

368-406: WSL path leaves args undefined — runtime error when building MCP config

When is_wsl is True, args is never set; later server_config references args, causing an UnboundLocalError. Set args after the WSL URL adjustment so it’s always initialized.

Apply:

         os_type = platform.system()
         command = "uvx"
 
         # Check if running on WSL (will appear as Linux but with Microsoft in release info)
         is_wsl = os_type == "Linux" and "microsoft" in platform.uname().release.lower()
 
         if is_wsl:
             logger.debug("WSL detected, using Windows-specific configuration")
@@
                 except OSError as e:
                     logger.warning("Failed to get WSL IP address: %s. Using default URL.", str(e))
-        else:
-            args = ["mcp-proxy", sse_url]
+        # Initialize args after potential WSL sse_url adjustment
+        args = ["mcp-proxy", sse_url]
 
         if os_type == "Windows":
             command = "cmd"
             args = ["/c", "uvx", *args]
             logger.debug("Windows detected, using cmd command")
🧹 Nitpick comments (3)
src/backend/base/langflow/api/v1/schemas.py (1)

447-459: Add lightweight validation to enforce required fields for each auth type

To prevent misconfiguration getting persisted (e.g., auth_type="apikey" without api_key, or incomplete OAuth config), add a model-level validator.

Apply within class AuthSettings:

 class AuthSettings(BaseModel):
     """Model representing authentication settings for MCP."""
 
     auth_type: Literal["none", "apikey", "oauth"] = "none"
     api_key: SecretStr | None = None
@@
     oauth_mcp_scope: str | None = None
     oauth_provider_scope: str | None = None
+
+    @model_validator(mode="after")
+    def _validate_auth(self):
+        if self.auth_type == "apikey":
+            if not self.api_key or not self.api_key.get_secret_value().strip():
+                raise ValueError("api_key is required when auth_type is 'apikey'.")
+        if self.auth_type == "oauth":
+            required = ["oauth_client_id", "oauth_client_secret", "oauth_auth_url", "oauth_token_url"]
+            missing = [f for f in required if not getattr(self, f)]
+            if missing:
+                raise ValueError(f"Missing OAuth fields: {', '.join(missing)}")
+        return self

And ensure the import is available:

from pydantic import model_validator
src/backend/base/langflow/api/v1/mcp_projects.py (1)

346-349: Use 403 Forbidden for non-local install attempts

Returning 500 (server error) hides the access semantics and confuses clients. 403 better reflects “you’re not allowed from this origin.”

-    if not is_local_ip(client_ip):
-        raise HTTPException(status_code=500, detail="MCP configuration can only be installed from a local connection")
+    if not is_local_ip(client_ip):
+        raise HTTPException(status_code=403, detail="MCP configuration can only be installed from a local connection")
src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx (1)

253-283: Prefer building the config as an object and JSON.stringify it

String interpolation for JSON is brittle (e.g., commas, quoting). Construct the object and call JSON.stringify to remove this entire class of issues.

Example sketch:

const serverName = `lf-${parseString(folderName ?? "project", [
  "snake_case",
  "no_blank",
  "lowercase",
]).slice(0, MAX_MCP_SERVER_NAME_LENGTH - 4)}`;

const args = [
  ...(selectedPlatform === "windows" ? ["/c", "uvx"] : selectedPlatform === "wsl" ? ["uvx"] : []),
  "mcp-proxy",
  ...(ENABLE_MCP_COMPOSER
    ? currentAuthSettings?.auth_type === "apikey" && (currentAuthSettings.api_key || "YOUR_API_KEY")
      ? ["--headers", "x-api-key", String(currentAuthSettings.api_key || "YOUR_API_KEY")]
      : []
    : isAutoLogin ? [] : ["--headers", "x-api-key", String(apiKey || "YOUR_API_KEY")]
  ),
  apiUrl,
];

const mcpConfig = {
  mcpServers: {
    [serverName]: {
      command:
        selectedPlatform === "windows"
          ? "cmd"
          : selectedPlatform === "wsl"
          ? "wsl"
          : "uvx",
      args,
    },
  },
};

const MCP_SERVER_JSON = JSON.stringify(mcpConfig, null, 2);
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2475e5a and 6147e47.

📒 Files selected for processing (5)
  • src/backend/base/langflow/api/v1/mcp_projects.py (1 hunks)
  • src/backend/base/langflow/api/v1/schemas.py (1 hunks)
  • src/frontend/src/modals/authModal/index.tsx (0 hunks)
  • src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx (2 hunks)
  • src/frontend/src/utils/mcpUtils.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • src/frontend/src/utils/mcpUtils.ts
  • src/frontend/src/modals/authModal/index.tsx
🧰 Additional context used
📓 Path-based instructions (2)
{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/api/v1/mcp_projects.py
  • src/backend/base/langflow/api/v1/schemas.py
src/frontend/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend_development.mdc)

src/frontend/src/**/*.{ts,tsx,js,jsx}: All frontend TypeScript and JavaScript code should be located under src/frontend/src/ and organized into components, pages, icons, stores, types, utils, hooks, services, and assets directories as per the specified directory layout.
Use React 18 with TypeScript for all UI components in the frontend.
Format all TypeScript and JavaScript code using the make format_frontend command.
Lint all TypeScript and JavaScript code using the make lint command.

Files:

  • src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx
🧠 Learnings (1)
📚 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 (1)
src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx (1)
src/frontend/src/customization/feature-flags.ts (1)
  • ENABLE_MCP_COMPOSER (20-21)
🔇 Additional comments (3)
src/backend/base/langflow/api/v1/schemas.py (1)

447-447: Auth types correctly narrowed; no legacy auth types detected

I ran the suggested ripgrep sweep across the repository for the removed auth types (“basic”, “bearer”, “iam”) and fields (“username”, “password”, “bearer_token”, “iam_endpoint”) and found only non-auth usages (e.g. “Basic Prompting” in tests, AWS CDK IAM constructs, and standard Authorization: Bearer headers). There are no stale references in the API schemas or auth logic.

• Patterns searched:
\b(basic|bearer|iam)\b
\b(username|password|bearer_token|iam_endpoint)\b

• No matches in src/backend/base/langflow/api/v1/schemas.py or related auth modules.
• Remaining occurrences are unrelated to Composer’s auth surface (tutorial markdown, testing fixtures, AWS infra).

All set to merge.

src/backend/base/langflow/api/v1/mcp_projects.py (1)

360-366: Good: dynamic SSE URL with host/port (consistent with past guidance)

Constructing sse_url from runtime settings avoids hardcoded localhost pitfalls and works across deployments.

src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx (1)

243-248: AuthSettingsType.api_key is a plain string
Verified that in src/frontend/src/types/mcp/index.ts, api_key?: string is defined (not a wrapped/SecretStr type), so it will render correctly. No further changes needed—LGTM.

Copy link
Collaborator

@jordanrfrazier jordanrfrazier left a comment

Choose a reason for hiding this comment

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

bot comment seems valid

@github-actions github-actions bot added the lgtm This PR has been approved by a maintainer label Aug 22, 2025
@github-actions github-actions bot added refactor Maintenance tasks and housekeeping and removed refactor Maintenance tasks and housekeeping labels Aug 22, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Aug 22, 2025

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 4%
4.07% (1041/25557) 1.98% (384/19350) 1.95% (108/5527)

Unit Test Results

Tests Skipped Failures Errors Time
527 0 💤 0 ❌ 0 🔥 8.285s ⏱️

@codecov
Copy link

codecov bot commented Aug 22, 2025

Codecov Report

❌ Patch coverage is 25.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 33.98%. Comparing base (59937ee) to head (96f16dd).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ainPage/pages/homePage/components/McpServerTab.tsx 0.00% 2 Missing ⚠️
src/backend/base/langflow/api/v1/mcp_projects.py 0.00% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (25.00%) is below the target coverage (40.00%). You can increase the patch coverage or adjust the target coverage.
❌ Your project status has failed because the head coverage (3.80%) is below the target coverage (10.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #9487      +/-   ##
==========================================
+ Coverage   33.96%   33.98%   +0.02%     
==========================================
  Files        1195     1195              
  Lines       55823    55753      -70     
  Branches     5370     5332      -38     
==========================================
- Hits        18960    18949      -11     
+ Misses      36793    36734      -59     
  Partials       70       70              
Flag Coverage Δ
backend 56.83% <50.00%> (-0.01%) ⬇️
frontend 3.80% <0.00%> (+<0.01%) ⬆️

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

Files with missing lines Coverage Δ
src/backend/base/langflow/api/v1/schemas.py 96.06% <100.00%> (-0.07%) ⬇️
src/frontend/src/modals/authModal/index.tsx 0.00% <ø> (ø)
src/frontend/src/utils/mcpUtils.ts 0.00% <ø> (ø)
src/backend/base/langflow/api/v1/mcp_projects.py 27.80% <0.00%> (+0.60%) ⬆️
...ainPage/pages/homePage/components/McpServerTab.tsx 0.00% <0.00%> (ø)

... and 3 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 refactor Maintenance tasks and housekeeping and removed refactor Maintenance tasks and housekeeping labels Aug 22, 2025
@sonarqubecloud
Copy link

@mfortman11 mfortman11 merged commit fd9f8c5 into main Aug 22, 2025
73 of 75 checks passed
@mfortman11 mfortman11 deleted the composer-auth-updates branch August 22, 2025 01:57
lucaseduoli pushed a commit that referenced this pull request Aug 22, 2025
* Update auth to just api and oauth

* schema push

* pr comment fix
lucaseduoli pushed a commit that referenced this pull request Aug 25, 2025
* Update auth to just api and oauth

* schema push

* pr comment fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm This PR has been approved by a maintainer refactor Maintenance tasks and housekeeping

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants