Skip to content

feat(mcp): oauth#208

Merged
cgoinglove merged 39 commits into
mainfrom
feat/mpc-oauth
Aug 4, 2025
Merged

feat(mcp): oauth#208
cgoinglove merged 39 commits into
mainfrom
feat/mpc-oauth

Conversation

@cgoinglove

Copy link
Copy Markdown
Collaborator

No description provided.

cgoinglove and others added 11 commits August 2, 2025 12:45
…enhance logging

- Removed redundant initialization call for MCP manager in the `register` function.
- Added a new `waitInitialized` method to ensure MCP clients manager is initialized before operations.
- Enhanced logging with a unique identifier for better traceability.
- Introduced `MemoryMCPConfigStorage` for in-memory configuration management, including methods for saving, loading, and deleting configurations.
- Added tests for `MemoryMCPConfigStorage` to ensure functionality and reliability.
…ance clarity

- Revised the agent generation prompt to improve clarity and effectiveness.
- Streamlined the process into clear steps, focusing on core intent extraction, persona design, and instruction architecture.
- Added performance optimization strategies and output generation specifications.
- Ensured all output content aligns with user language requests for better usability.
- Updated environment variables in `.env.example` and `README.md` to reflect the new Exa AI API.
- Refactored web search components and tools to utilize Exa AI, including response handling and schema definitions.
- Enhanced workflow examples to align with the new Exa API structure.
- Adjusted node executor to support Exa AI tools for improved search capabilities.
…ization tools

- Added a new `createTable` tool for generating interactive tables with sorting, filtering, and search capabilities.
- Updated existing tools and documentation to reflect the new table functionality.
- Enhanced the `RandomDataGeneratorExample` to include table creation in its workflow.
- Modified various components to support the new table feature, including dynamic imports and UI adjustments.

Co-authored-by: choi sung keun <86150470+cgoinglove@users.noreply.github.com>
… functionality

- Updated the layout of the Interactive Table component to include additional padding and a more structured design.
- Improved the search and export functionality by ensuring the dropdown menus for column visibility and export options are clearly defined.
- Maintained existing features while enhancing the overall user experience and visual consistency.
@vercel

vercel Bot commented Aug 2, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
mcp-client-chatbot ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 4, 2025 4:06pm

@github-actions

github-actions Bot commented Aug 2, 2025

Copy link
Copy Markdown
Contributor
Messages
📖 ✅ PR title follows Conventional Commit format!

Generated by 🚫 dangerJS against ae3b134

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary of Changes

Hello @cgoinglove, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request primarily focuses on enhancing the documentation related to the project's built-in data visualization tools. It provides a more comprehensive and detailed explanation of the interactive table features and chart generation capabilities. Note: The pull request title 'feat(mpc): oauth' appears to be a mismatch with the actual changes, which are purely documentation updates.

Highlights

  • Documentation Enhancement: Updated CLAUDE.md and README.md to provide a more detailed and structured description of the built-in data visualization tools.
  • Interactive Tables Features: Added comprehensive details about the advanced functionalities of interactive tables, including sorting, filtering, global search with highlighting, CSV/Excel export, column management, pagination, and data type support.
  • Chart Generation Clarification: Clarified the capabilities of chart generation tools, specifically mentioning bar, line, and pie charts.
  • Lazy-loaded Excel Export: Highlighted the implementation of lazy-loaded Excel export using a CDN-based xlsx library for optimal bundle size.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new interactive table component and updates the documentation to reflect this and other data visualization capabilities. The pull request title should be updated to accurately reflect the changes, such as feat(ui): add interactive data table.

Comment thread CLAUDE.md
Comment on lines +207 to +212
- **Interactive Tables**: Feature-rich tables with sorting, filtering, search, highlighting, pagination, and CSV/Excel export
- **Charts**: Generation of bar, line, and pie charts
- Tools generate parameters that render React components
- Components located in `@src/components/tool-invocation/`
- Dynamic imports used in `@src/components/message-parts.tsx` for rendering
- Lazy-loaded Excel export using CDN-based xlsx library for optimal bundle size

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The detail about lazy-loading the Excel library is specific to the Interactive Tables feature. For better clarity and structure, I suggest nesting this information under the 'Interactive Tables' item. This makes it clear which feature benefits from this optimization, as it doesn't apply to the other visualization tools.

Suggested change
- **Interactive Tables**: Feature-rich tables with sorting, filtering, search, highlighting, pagination, and CSV/Excel export
- **Charts**: Generation of bar, line, and pie charts
- Tools generate parameters that render React components
- Components located in `@src/components/tool-invocation/`
- Dynamic imports used in `@src/components/message-parts.tsx` for rendering
- Lazy-loaded Excel export using CDN-based xlsx library for optimal bundle size
- **Interactive Tables**: Feature-rich tables with sorting, filtering, search, highlighting, pagination, and CSV/Excel export
- Lazy-loaded Excel export using CDN-based xlsx library for optimal bundle size

Comment thread README.md
#### 📊 Data Visualization Tools

**Interactive Tables**: Create feature-rich data tables with advanced functionality:
- **Sorting & Filtering**: Sort by any column, filter data in real-time

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The current implementation in interactive-table.tsx provides a global search that filters data, but not per-column filtering. To set accurate user expectations, it would be clearer to specify that filtering is done via a global search.

Suggested change
- **Sorting & Filtering**: Sort by any column, filter data in real-time
- **Sorting & Filtering**: Sort by any column, filter data in real-time using global search

@brrock

brrock commented Aug 3, 2025

Copy link
Copy Markdown
Contributor

Progress? @cgoinglove

@cgoinglove

Copy link
Copy Markdown
Collaborator Author

@brrock 70%

@brrock

brrock commented Aug 3, 2025

Copy link
Copy Markdown
Contributor

Cool

@cgoinglove

Copy link
Copy Markdown
Collaborator Author

The draft has been completed, but there are still parts that need to be tested and modified.

The linear oauth at https://mcp.linear.app/sse is working properly.

Since this is not a completed PR, there may be changes to the DB, so when testing this PR, please use a development database such as pnpm docker:pg.

@cgoinglove

Copy link
Copy Markdown
Collaborator Author

/gemini summary

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

I've added comprehensive OAuth 2.0 support for Model Context Protocol (MCP) servers, which allows for more secure and streamlined integration with external services. This feature includes new API routes to manage the OAuth flow and significant updates to the user interface to guide users through the authorization process. Additionally, I've refined the documentation to better describe the enhanced data visualization tools available.

Highlights

  • OAuth 2.0 Integration: I've implemented OAuth 2.0 support for Model Context Protocol (MCP) servers, enabling secure authorization flows for remote MCP instances. This includes handling authorization code exchange and token management.
  • New OAuth Callback Endpoint: I've introduced a new API endpoint (/api/mcp/oauth/callback) to specifically handle the redirection and processing of OAuth authorization responses from MCP servers. This endpoint manages success and error scenarios during the authentication process.
  • UI Enhancements for Authorization State: I've updated the user interface components, particularly the MCP card, to reflect and manage the authorization status of connected MCP servers. This includes displaying an 'authorizing' state, providing a dedicated 'Authorize' button, and showing relevant alerts to guide the user through the OAuth flow.
  • Documentation Updates for Data Visualization: I've significantly enhanced the documentation in CLAUDE.md and README.md to accurately reflect the new data visualization capabilities, including interactive tables with advanced features like sorting, filtering, and Excel export, as well as improved chart generation.
Changelog
  • CLAUDE.md
    • Updated the description of built-in tools to clarify data visualization capabilities, specifically detailing interactive tables with sorting, filtering, search, highlighting, pagination, and CSV/Excel export.
    • Added information about lazy-loaded Excel export using a CDN-based xlsx library for optimal bundle size.
    • Refined the description of chart generation to include bar, line, and pie charts.
  • README.md
    • Expanded the data visualization section to provide more detailed descriptions of interactive tables, including features like sorting, filtering, search, highlighting, export options, column management, pagination, and data type support.
    • Clarified the chart generation capabilities, specifying bar, line, and pie charts.
    • Updated the general description of available tools.
  • src/app/api/mcp/actions.ts
    • Modified the saveMcpClientAction to return the client object after persistence.
    • Added a new authorizeMcpClientAction to handle the authorization flow for MCP clients, including refreshing the client and retrieving the authorization URL.
  • src/app/api/mcp/oauth/callback/route.ts
    • Added a new API route (/api/mcp/oauth/callback) to handle OAuth callback responses.
    • Implemented logic to process authorization codes and states, exchange them for tokens, and store them.
    • Included HTML responses for success and various error scenarios (e.g., missing parameters, invalid state, authentication failure), with JavaScript to post messages back to the opener window and close the popup.
  • src/app/api/mcp/route.ts
    • Modified the POST endpoint to handle new MCP server configurations.
    • Introduced logic to check if OAuth authorization is required for a new client and return an appropriate 401 response with the authorization URL and a specific OAUTH_REQUIRED_CODE.
  • src/components/mcp-card.tsx
    • Imported KeyRoundIcon and authorizeMcpClientAction for OAuth functionality.
    • Updated error message handling to support string errors.
    • Added a needsAuthorization state to control UI elements based on the client's authorization status.
    • Implemented a handleAuthorize callback to initiate the OAuth flow.
    • Added an 'Authorize' button with a KeyRoundIcon and a vertical separator in the card header, visible when authorization is needed.
    • Disabled the 'Edit' and 'Test Tools' buttons when the client requires authorization.
    • Added an Alert component at the bottom of the card, prompting the user to authorize the MCP server when needsAuthorization is true.
    • Adjusted the ErrorAlert component to allow for pre-wrapped and breakable error messages.
  • src/components/mcp-editor.tsx
    • Imported mcpOAuthRequiredToast for handling OAuth-related toasts.
    • Modified the handleSave function to check for an OAUTH_REQUIRED error code from the server response. If detected, it triggers the mcpOAuthRequiredToast with the provided authorization URL.
  • src/components/ui/shared-toast.tsx
    • Added a new mcpOAuthRequiredToast function to manage the OAuth authentication flow. This function opens a new window for the OAuth URL, listens for success or error messages via postMessage, and provides toast notifications for the authentication process.
  • src/hooks/use-state-with-browserstorage.ts
    • Added the `
    • use client
    • ` directive to ensure this hook runs on the client side.
  • src/lib/ai/mcp/create-mcp-client.ts
    • Removed direct import of Tool and tool from ai as tool creation is now handled differently.
    • Updated CONNET_TIMEOUT for Vercel environment.
    • Modified the MCPClient constructor to accept an id parameter.
    • Added status getter to reflect the client's connection and authorization state (loading, authorizing, connected, disconnected).
    • Introduced authorizationUrl property and getAuthorizationUrl() method to manage OAuth authorization URLs.
    • Added finishAuth() method to complete the OAuth authorization code exchange.
    • Implemented createOAuthProvider() to dynamically create a PgOAuthClientProvider for remote MCP servers, handling the onRedirectToAuthorization callback.
    • Updated the connect() method to integrate OAuth flow, including handling OAuthAuthorizationRequiredError and falling back to SSE transport if Streamable HTTP fails.
    • Simplified disconnect() to handle client closing.
    • Added updateToolInfo() to refresh the list of available tools from the connected client.
    • Modified callTool() to throw an error if authorization is required.
    • Introduced isOAuthAuthorizationRequired() helper to check for OAuth-related errors.
    • Added OAuthAuthorizationRequiredError class for specific OAuth flow errors.
    • Updated createMCPClient factory function to accept the id parameter.
  • src/lib/ai/mcp/create-mcp-clients-manager.test.ts
    • Updated calls to mockCreateMCPClient in tests to include the new id parameter, aligning with the updated createMCPClient signature.
  • src/lib/ai/mcp/create-mcp-clients-manager.ts
    • Updated addClient and persistClient methods to pass the id to createMCPClient.
    • Modified getTools to iterate over client.toolInfo and construct VercelAIMcpTool objects, including jsonSchema for parameters.
    • Simplified refreshClient to directly fetch the server config from storage and re-add the client.
  • src/lib/ai/mcp/pg-oauth-provider.ts
    • Added a new file pg-oauth-provider.ts which implements OAuthClientProvider.
    • This provider manages OAuth authentication state and tokens using PostgreSQL, handling client information, token storage, PKCE code verifier, and redirection for authorization.
  • src/lib/ai/workflow/executor/workflow-executor.test.ts
    • Added mocks for lib/ai/mcp/mcp-manager and server-only to allow tests to run without server-side dependencies.
  • src/lib/const.ts
    • Added BASE_URL constant to dynamically determine the application's base URL.
    • Introduced OAUTH_REQUIRED_CODE constant for specific OAuth error handling.
  • src/lib/db/migrations/pg/0009_neat_ultimates.sql
    • Added a new database migration to create the mcp_oauth_session table. This table stores OAuth session data, including mcp_server_id, server_url, client_info, tokens, code_verifier, and state.
  • src/lib/db/migrations/pg/meta/0009_snapshot.json
    • Updated the database schema snapshot to include the new mcp_oauth_session table and its associated columns, indexes, and foreign keys.
  • src/lib/db/migrations/pg/meta/_journal.json
    • Updated the migration journal to include the new 0009_neat_ultimates migration entry.
  • src/lib/db/pg/repositories/mcp-oauth-repository.pg.ts
    • Added a new file mcp-oauth-repository.pg.ts which provides a PostgreSQL-based implementation for McpOAuthRepository.
    • This repository includes functions to get, save (upsert), and delete OAuth session data for MCP servers, supporting retrieval by mcpServerId and state.
  • src/lib/db/pg/schema.pg.ts
    • Added the McpOAuthSessionSchema to define the database table for storing MCP OAuth session information, including fields for client info, tokens, code verifier, and state.
  • src/lib/db/repository.ts
    • Exported the newly created pgMcpOAuthRepository as mcpOAuthRepository.
  • src/lib/utils.ts
    • Slightly modified the isLocked getter in the Locker class for boolean coercion.
Activity
  • The Vercel bot provided an update on the build status for the mcp-client-chatbot project.
  • The DangerJS bot confirmed that the PR title follows the Conventional Commit format.
  • brrock inquired about the progress of the pull request.
  • I responded to brrock, indicating that the pull request was 70% complete.
  • brrock acknowledged the progress.
  • I provided an update stating that the draft was completed, but still required testing and modifications. I also confirmed that the linear OAuth at https://mcp.linear.app/sse was working correctly and advised using a development database for testing due to potential future DB changes.
  • I requested a summary from the Gemini model.

…provements

- Updated the MCP page to sort the MCP list by status, prioritizing 'authorizing' status.
- Reduced the refresh interval for the MCP list from 10 seconds to 5 seconds.
- Improved the layout of the MCP card component for better content visibility and overflow handling.
- Added a name property to the PgOAuthClientProvider for better logging context.
- Added logging for the count of MCP tools alongside MCP clients in the chat route.
- Updated the state management in the useMcpList hook to filter allowed MCP servers based on the fetched data, improving data consistency.
- Moved the unlocking of the locker and tool info update to the finally block for better error management.
- Added logging for tool info updates to enhance visibility into the MCPClient's operations.
@brrock brrock linked an issue Aug 4, 2025 that may be closed by this pull request
…components

- Enhanced logging in the chat route to handle undefined values for allowed tools, ensuring accurate logging output.
- Updated the initial state in the store to include predefined allowed app default toolkits, improving state management.
- Adjusted the store's partialization logic to filter allowed app default toolkits based on defined values, enhancing data integrity.
- Eliminated debug and info logging statements in the PgOAuthClientProvider class to streamline the code and reduce verbosity.
- Maintained functionality while improving code clarity and maintainability.
commit 410ad4b
Author: choi sung keun <86150470+cgoinglove@users.noreply.github.com>
Date:   Mon Aug 4 23:31:40 2025 +0900

    refactor: remove unnecessary logging in PgOAuthClientProvider

    - Eliminated debug and info logging statements in the PgOAuthClientProvider class to streamline the code and reduce verbosity.
    - Maintained functionality while improving code clarity and maintainability.

commit 3d003e0
Author: choi sung keun <86150470+cgoinglove@users.noreply.github.com>
Date:   Mon Aug 4 23:29:57 2025 +0900

    refactor: improve logging and state initialization in chat and store components

    - Enhanced logging in the chat route to handle undefined values for allowed tools, ensuring accurate logging output.
    - Updated the initial state in the store to include predefined allowed app default toolkits, improving state management.
    - Adjusted the store's partialization logic to filter allowed app default toolkits based on defined values, enhancing data integrity.

commit a656275
Author: choi sung keun <86150470+cgoinglove@users.noreply.github.com>
Date:   Mon Aug 4 22:56:54 2025 +0900

    refactor: improve error handling and logging in MCPClient

    - Moved the unlocking of the locker and tool info update to the finally block for better error management.
    - Added logging for tool info updates to enhance visibility into the MCPClient's operations.

commit d4c8ce1
Author: choi sung keun <86150470+cgoinglove@users.noreply.github.com>
Date:   Mon Aug 4 22:48:06 2025 +0900

    refactor: enhance logging and state management in MCP components

    - Added logging for the count of MCP tools alongside MCP clients in the chat route.
    - Updated the state management in the useMcpList hook to filter allowed MCP servers based on the fetched data, improving data consistency.

commit 487137e
Merge: 7e31bf8 4dea9a7
Author: choi sung keun <86150470+cgoinglove@users.noreply.github.com>
Date:   Mon Aug 4 22:18:45 2025 +0900

    Merge branch 'feat/mpc-oauth' into custom-main

commit 7e31bf8
Author: cgoing <neo.cgoing@gmail.com>
Date:   Mon Aug 4 16:40:05 2025 +0900

    refactor: update MCP client handling in OAuth callback

    - Changed the method to refresh the MCP client in the OAuth callback to ensure the latest client status is retrieved.
    - Updated the client addition logic in MCPClientsManager to await the completion of the addClient method, ensuring proper client management.

commit 1b9eabf
Author: cgoing <neo.cgoing@gmail.com>
Date:   Mon Aug 4 15:56:14 2025 +0900

    fff

commit 45e869e
Author: cgoing <neo.cgoing@gmail.com>
Date:   Mon Aug 4 15:48:41 2025 +0900

    Revert "asd"

    This reverts commit 2410dfd.

commit 2410dfd
Author: cgoing <neo.cgoing@gmail.com>
Date:   Mon Aug 4 15:41:15 2025 +0900

    asd
- Changed the method for obtaining the MCP client in the OAuth callback from refreshClient to getClient to ensure accurate client status retrieval.
- This adjustment enhances the reliability of client management within the OAuth flow.
- Replaced the refreshClient method with getClient in the OAuth callback to improve accuracy in client status retrieval.
- This change enhances the reliability of client management within the OAuth flow.
- Introduced a new function to create OAuth response pages, improving code organization and readability.
- Updated error and success response handling in the OAuth callback to utilize the new response creation function, ensuring consistent messaging and styling.
- Improved logging for client refresh operations in the MCPClientsManager to provide clearer context during client updates.
- Updated the logging mechanism in the OAuth callback to provide clearer success and error messages.
- Introduced a new logger configuration for consistent message formatting.
- Enhanced the visibility of OAuth callback events for better debugging and monitoring.
…olSelectDropdown

- Updated MCPCard and ToolSelectDropdown components to use ShieldAlertIcon instead of KeyRoundIcon for improved visual consistency.
- Added authorization handling in ToolSelectDropdown, displaying an alert when authorization is required.
- Adjusted connection timeout in create-mcp-client.ts for better performance in Vercel environment.
- Eliminated the logging of the authorization URL in the MCPClient class to reduce verbosity and improve code clarity.
- Maintained the functionality of OAuth authorization handling while streamlining the logging process.
- Replaced the direct call to getOAuthSessionByState with a new method getAuthData to enhance code clarity and maintainability.
- Ensured that the functionality of retrieving the OAuth code verifier remains intact while simplifying the implementation.
…-client.ts

- Updated the connection timeout from 12000ms to 30000ms for improved performance in Vercel deployments.
- This change aims to enhance the reliability of client connections under varying network conditions.
- Changed from Promise.allSettled to Promise.all for loading client configurations, ensuring that all client addition operations are awaited before proceeding.
- This adjustment improves error handling and ensures that all clients are processed concurrently.
@cgoinglove

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces OAuth support for MCP servers, which is a major and well-implemented feature. The changes span the entire stack, from new database tables for OAuth sessions to UI components that handle the authorization flow.

Overall, the implementation is robust, covering security considerations like using the state parameter to prevent CSRF and checking event.origin in postMessage handlers. The backend logic correctly handles the OAuth callback, token exchange, and updates the client status accordingly. The UI has also been thoughtfully updated to guide the user through the authorization process when required.

My main feedback focuses on improving maintainability by reducing code duplication and simplifying complex logic. I've identified a few areas where the code can be refactored for better clarity and long-term health.

Comment on lines +85 to +158
const handleAuthorize = useCallback(
() =>
pipeProcessing(() =>
authorizeMcpClientAction(id).then((authUrl) => {
if (!authUrl) throw new Error("Not Authorizing");
return new Promise((resolve, reject) => {
const authWindow = window.open(
authUrl,
"oauth",
"width=600,height=800,scrollbars=yes,resizable=yes",
);
if (!authWindow) {
return reject(
new Error("Please allow popups for OAuth authentication"),
);
}

let messageHandlerRegistered = false;
let intervalId: NodeJS.Timeout | null = null;

// Clean up function
const cleanup = () => {
if (messageHandlerRegistered) {
window.removeEventListener("message", messageHandler);
messageHandlerRegistered = false;
}
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
};

// Message handler for postMessage communication
const messageHandler = (event: MessageEvent) => {
// Security: only accept messages from same origin
if (event.origin !== window.location.origin) {
return;
}

if (event.data.type === "MCP_OAUTH_SUCCESS") {
cleanup();
if (authWindow && !authWindow.closed) {
authWindow.close();
}
resolve(true);
} else if (event.data.type === "MCP_OAUTH_ERROR") {
cleanup();
if (authWindow && !authWindow.closed) {
authWindow.close();
}
const errorMessage =
event.data.error_description ||
event.data.error ||
"Authentication failed";
reject(new Error(errorMessage));
}
};

// Register message event listener
window.addEventListener("message", messageHandler);
messageHandlerRegistered = true;

// Backup: Poll for manual window close (in case postMessage fails)
intervalId = setInterval(() => {
if (authWindow.closed) {
cleanup();
resolve(true);
}
}, 1000);
});
}),
),
[id],
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

This handleAuthorize function contains complex logic for handling the OAuth popup window, including postMessage communication and a polling fallback. I've noticed this exact logic is duplicated in src/components/mcp-editor.tsx and src/components/tool-select-dropdown.tsx.

To improve maintainability and reduce code duplication, I strongly recommend extracting this logic into a reusable custom hook (e.g., useOAuthPopup) or a utility function. This would centralize the logic, make it easier to test, and ensure any future changes only need to be made in one place.

For example, a hook could look like this:

const { openAuthPopup, isAuthorizing } = useOAuthPopup();

const handleAuthorize = useCallback(() => {
  pipeProcessing(() => openAuthPopup(id));
}, [id, openAuthPopup, pipeProcessing]);

Comment on lines +50 to +52
${Object.entries(postMessageData)
.map(([key, value]) => `${key}: '${value}'`)
.join(", ")}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The current method of constructing the postMessage data by mapping object entries to a string is a bit fragile. It assumes all values in postMessageData are strings and wraps them in single quotes. If a boolean or number is passed, it will be converted to a string (e.g., true becomes 'true').

While this works for the current implementation, a more robust approach would be to use JSON.stringify on the data object. This ensures that data types are preserved correctly and makes the code more resilient to future changes in postMessageData.

          .map(([key, value]) => `${key}: ${JSON.stringify(value)})`)
          .join(", ")}

await this.storage.init(this);
const configs = await this.storage.loadAll();
await Promise.allSettled(
await Promise.all(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using Promise.all here means that if any single client fails to initialize (e.g., due to a misconfiguration), the entire init process for the manager will fail.

Given that MCP servers are independent, it would be more resilient to use Promise.allSettled. This would allow the manager to initialize successfully even if some clients fail, logging the errors for later inspection without bringing down the whole system. The previous implementation used allSettled, and it seems more appropriate for this use case.

Suggested change
await Promise.all(
await Promise.allSettled(

@cgoinglove cgoinglove merged commit 136aded into main Aug 4, 2025
5 checks passed
@cgoinglove cgoinglove deleted the feat/mpc-oauth branch August 4, 2025 16:41
cgoinglove pushed a commit that referenced this pull request Aug 4, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.20.0](v1.19.1...v1.20.0)
(2025-08-04)


### Features

* add qwen3 coder to models file for openrouter
([#206](#206))
([3731d00](3731d00))
* improve authentication configuration and social login handling
([#211](#211))
([cd25937](cd25937))
* introduce interactive table creation and enhance visualization tools
([#205](#205))
([623a736](623a736))
* **mcp:** oauth
([#208](#208))
([136aded](136aded))
* **web-search:** replace Tavily API with Exa AI integration
([#204](#204))
([7140487](7140487))


### Bug Fixes

* implement responsive horizontal layout for chat mention input with
improved UX And generate Agent Prompt
([43ec980](43ec980))
* **mcp:** Safe MCP manager init logic for the Vercel environment
([#202](#202))
([708fdfc](708fdfc))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
rockstarhub28 added a commit to rockstarhub28/better-chatbot that referenced this pull request Dec 24, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.20.0](keinsaasforever/better-chatbot@v1.19.1...v1.20.0)
(2025-08-04)


### Features

* add qwen3 coder to models file for openrouter
([#206](keinsaasforever/better-chatbot#206))
([3731d00](keinsaasforever/better-chatbot@3731d00))
* improve authentication configuration and social login handling
([#211](keinsaasforever/better-chatbot#211))
([cd25937](keinsaasforever/better-chatbot@cd25937))
* introduce interactive table creation and enhance visualization tools
([#205](keinsaasforever/better-chatbot#205))
([623a736](keinsaasforever/better-chatbot@623a736))
* **mcp:** oauth
([#208](keinsaasforever/better-chatbot#208))
([136aded](keinsaasforever/better-chatbot@136aded))
* **web-search:** replace Tavily API with Exa AI integration
([#204](keinsaasforever/better-chatbot#204))
([7140487](keinsaasforever/better-chatbot@7140487))


### Bug Fixes

* implement responsive horizontal layout for chat mention input with
improved UX And generate Agent Prompt
([43ec980](keinsaasforever/better-chatbot@43ec980))
* **mcp:** Safe MCP manager init logic for the Vercel environment
([#202](keinsaasforever/better-chatbot#202))
([708fdfc](keinsaasforever/better-chatbot@708fdfc))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
CryptoWizardTeam added a commit to CryptoWizardTeam/ai-chatbot-2 that referenced this pull request Mar 14, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.20.0](keinsaasforever/better-chatbot@v1.19.1...v1.20.0)
(2025-08-04)


### Features

* add qwen3 coder to models file for openrouter
([#206](keinsaasforever/better-chatbot#206))
([3731d00](keinsaasforever/better-chatbot@3731d00))
* improve authentication configuration and social login handling
([#211](keinsaasforever/better-chatbot#211))
([cd25937](keinsaasforever/better-chatbot@cd25937))
* introduce interactive table creation and enhance visualization tools
([#205](keinsaasforever/better-chatbot#205))
([623a736](keinsaasforever/better-chatbot@623a736))
* **mcp:** oauth
([#208](keinsaasforever/better-chatbot#208))
([136aded](keinsaasforever/better-chatbot@136aded))
* **web-search:** replace Tavily API with Exa AI integration
([#204](keinsaasforever/better-chatbot#204))
([7140487](keinsaasforever/better-chatbot@7140487))


### Bug Fixes

* implement responsive horizontal layout for chat mention input with
improved UX And generate Agent Prompt
([43ec980](keinsaasforever/better-chatbot@43ec980))
* **mcp:** Safe MCP manager init logic for the Vercel environment
([#202](keinsaasforever/better-chatbot#202))
([708fdfc](keinsaasforever/better-chatbot@708fdfc))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add OAuth Support for MCP Connections in mcp-client-chatbot

3 participants