Skip to content

feat: add OAuth 2.0 support for MCP servers - #10527

Open
stevessr wants to merge 4 commits into
AstrBotDevs:masterfrom
stevessr:feat/mcp-oauth2
Open

stevessr wants to merge 4 commits into
AstrBotDevs:masterfrom
stevessr:feat/mcp-oauth2

Conversation

@stevessr

@stevessr stevessr commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Adds OAuth 2.0 support for MCP HTTP servers so AstrBot can connect to protected MCP endpoints using authorization-code or client-credentials flows. This includes dashboard authorization, callback handling, token storage/refresh, and shared OAuth client defaults.

Modifications / 改动点

  • Added MCP OAuth providers, persistent token storage, metadata discovery, authorization flow, and HTTP connectivity probing in astrbot/core/agent/mcp_oauth.py and integrated auth into MCP transports.
  • Added dashboard API/service support and MCP server dialog authorization/status UI.
  • Added shared MCP OAuth client settings and callback configuration, preserving the existing general callback address; documented MCP OAuth usage in docs/zh/use/mcp.md and docs/en/use/mcp.md.
  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

Automated verification completed:

  • cd dashboard && pnpm exec vue-tsc --noEmit — passed.
  • cd dashboard && pnpm exec vite build — passed (existing warning about an unresolved VoceChat image URL).

Suggested manual verification: configure a Streamable HTTP MCP server with OAuth 2.0, start authorization from the MCP server dialog, complete the provider login, then confirm the flow status becomes authorized and the server can list tools.

Screenshot: not captured. The local dashboard responds at http://localhost:3001, but the available browser-control connection failed while opening the page, so manual browser verification and screenshot capture remain outstanding. No live OAuth provider login was attempted.


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above. / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
  • 📚 Checked affected WebUI docs/screenshots; the relevant Chinese and English MCP usage docs were updated. No existing navigation guide/screenshot required changes because this adds settings without renaming or moving the prior settings entry. / 已检查受影响的 WebUI 文档和截图;已更新中英文 MCP 使用文档。此改动未重命名或移动原设置入口,无需调整既有导航说明或截图。
  • 🤓 No new dependencies introduced. / 未引入新依赖。
  • 😮 My changes do not introduce malicious code. / 我的更改没有引入恶意代码。

Summary by Sourcery

Enable AstrBot to authenticate with protected HTTP MCP servers through OAuth 2.0 and manage the authorization lifecycle from the dashboard.

New Features:

  • Add OAuth 2.0 authentication for remote HTTP MCP servers using authorization-code and client-credentials flows.
  • Provide dashboard controls for starting authorization, completing callbacks, viewing authorization status, and presenting login URLs or QR codes.
  • Support OAuth metadata discovery, persistent token and client-state storage, token refresh, and authenticated MCP connectivity probing.

Bug Fixes:

  • Prevent OAuth configuration and runtime status fields from being persisted as MCP server connection settings.
  • Handle disconnected dashboard requests without returning an internal error response.

Enhancements:

  • Add shared MCP OAuth client defaults and callback configuration that integrate with the existing public callback address.
  • Expose OAuth authorization state through MCP server management services and display it in the dashboard.
  • Document OAuth-enabled MCP server configuration and authorization workflows in English and Chinese.

Documentation:

  • Document authorization-code and client-credentials OAuth 2.0 configurations and WebUI login steps for MCP servers in English and Chinese documentation.

Tests:

  • Verify dashboard type checking and production builds.

Copilot AI balanced review requested due to automatic review settings October 12, 2026 09:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread astrbot/core/agent/mcp_oauth.py Fixed
Comment thread astrbot/dashboard/api/tools.py Fixed

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 10 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/agent/mcp_oauth.py" line_range="55" />
<code_context>
+        "authorization_code"
+    )
+    client_id: str | None = None
+    client_secret: str | None = None
+    token_endpoint_auth_method: (
+        Literal["none", "client_secret_post", "client_secret_basic"] | None
</code_context>
<issue_to_address>
**OAuth client secrets are exposed**

When an MCP server has `oauth2.client_secret` configured and a caller with the `mcp` API-key scope lists servers, `ToolsService.get_mcp_servers` includes the secret in its response, so the caller receives credentials they can reuse.

Remove or redact `oauth2.client_secret` from the server-list response.
</issue_to_address>

### Comment 2
<location path="astrbot/core/agent/mcp_client.py" line_range="544" />
<code_context>
-            success, error_msg = await _quick_test_mcp_connection(cfg)
-            if not success:
-                raise Exception(error_msg)
+            auth = await create_mcp_http_auth(cfg)
+
+            if not has_mcp_oauth_config(cfg):
</code_context>
<issue_to_address>
**Shared OAuth settings are not reused**

When a server relies on shared OAuth defaults for settings omitted from its own `oauth2` config, `MCPClient._do_connect` and `get_mcp_oauth_state` use the unmerged config, while authorization uses the merged config. Runtime and status checks therefore use a different token-storage fingerprint; shared client credentials can also fail validation, leaving the server unable to authenticate.

Apply the same shared OAuth defaults when creating runtime auth and checking OAuth status as the authorization flow uses.

Also at `astrbot/dashboard/services/tools_service.py:90`, `astrbot/core/agent/mcp_oauth.py:178-179`, `astrbot/core/agent/mcp_oauth.py:603`, `astrbot/core/agent/mcp_oauth.py:690-692`, `astrbot/core/provider/func_tool_manager.py:897-898`, `astrbot/dashboard/api/tools.py:217-226`.
</issue_to_address>

### Comment 3
<location path="astrbot/core/agent/mcp_oauth.py" line_range="101" />
<code_context>
+) -> str:
+    oauth_config = get_mcp_oauth_config(config)
+    return (
+        oauth_config.redirect_uri
+        if oauth_config and oauth_config.redirect_uri
+        else f"{callback_base_url.rstrip('/')}/mcp/oauth/callback"
</code_context>
<issue_to_address>
**Custom redirect prevents authorization**

When `oauth2.redirect_uri` points to a different callback path than `/mcp/oauth/callback`, `get_mcp_oauth_redirect_uri` sends the provider to a URI the dashboard does not handle, so the authorization flow cannot receive its callback and does not complete.

Restrict configured redirect URIs to the registered callback route or add a handler for the configured URI.

Also at `astrbot/dashboard/api/tools.py:515`, `astrbot/core/agent/mcp_oauth.py:102-103`.
</issue_to_address>

### Comment 4
<location path="astrbot/core/agent/mcp_oauth.py" line_range="760" />
<code_context>
+        probe_session_id = None
+        if transport_type == "streamable_http":
+            response = await client.post(
+                url,
+                headers={
+                    **headers,
</code_context>
<issue_to_address>
**SSE authorization probes time out**

When an OAuth-protected SSE endpoint keeps its event stream open, `probe_mcp_http_oauth_connection` uses `client.get()` for the SSE transport, which buffers the response body before checking its status. The open stream therefore times out and OAuth authorization fails.

Probe SSE endpoints without buffering the open response body.
</issue_to_address>

### Comment 5
<location path="astrbot/core/agent/mcp_oauth.py" line_range="114" />
<code_context>
+
+    default_redirect_uri = f"{callback_base}/mcp/oauth/callback"
+    mcp_callback_base = str(config.get("mcp_oauth_callback_base") or "").rstrip("/")
+    if not mcp_callback_base or mcp_callback_base == default_redirect_uri:
+        config["mcp_oauth_callback_base"] = callback_base
+
</code_context>
<issue_to_address>
**Callback changes leave stale redirects**

When the general callback address changes after `mcp_oauth_callback_base` was automatically populated, `sync_default_mcp_oauth_callback_base` compares the stored base URL with a full redirect URI that includes `/mcp/oauth/callback`. The comparison fails, leaving MCP OAuth redirects pointed at the old address.

Compare against the previous base URL or track whether the MCP callback base is still automatically managed.

Also at `astrbot/dashboard/services/config_service.py:784`.
</issue_to_address>

### Comment 6
<location path="astrbot/core/agent/mcp_oauth.py" line_range="881" />
<code_context>
+        try:
+            done, pending = await asyncio.wait(
+                {wait_url_task, wait_done_task},
+                timeout=15,
+                return_when=asyncio.FIRST_COMPLETED,
+            )
</code_context>
<issue_to_address>
**Slow providers cannot start authorization**

When metadata discovery or client registration takes longer than 15 seconds, `start_authorization` cancels the flow task after 15 seconds even though OAuth provider operations use a configurable timeout that defaults to 300 seconds. A slow but reachable provider therefore fails before it can provide the authorization URL.

Use the configured OAuth timeout for authorization preparation instead of the fixed 15-second limit.
</issue_to_address>

### Comment 7
<location path="dashboard/src/components/extension/McpServersSection.vue" line_range="1005-1008" />
<code_context>
     if (this.refreshInterval) {
       clearInterval(this.refreshInterval);
     }
+    this.stopOauthPolling();
   },
   watch: {
</code_context>
<issue_to_address>
**Authorized servers remain disconnected**

When an active server failed startup while authorization was missing and the user then authorizes it, the dashboard reports OAuth success but does not reconnect or initialize the MCP client. The server remains disconnected and its tools stay unavailable.

Reconnect or initialize the active MCP server after authorization completes successfully.

Also at `astrbot/core/agent/mcp_oauth.py:821`, `dashboard/src/components/extension/McpServersSection.vue:955`.
</issue_to_address>

### Comment 8
<location path="astrbot/core/agent/mcp_oauth.py" line_range="801" />
<code_context>
+                if flow.created_at < threshold
+            ]
+            for flow_id in expired_ids:
+                expired_states = [
+                    state
+                    for state, state_flow_id in self._state_to_flow_id.items()
</code_context>
<issue_to_address>
**Expired flows leave tasks running**

When an authorization flow remains unfinished past its 15-minute TTL, `_prune_flows` removes expired flows from its maps without cancelling their tasks. Those tasks remain blocked waiting for callbacks, retaining flow and provider objects as abandoned authorizations accumulate.

Cancel each expired flow task when pruning its flow.

Also at `astrbot/core/agent/mcp_oauth.py:808`.
</issue_to_address>

### Comment 9
<location path="astrbot/core/agent/mcp_oauth.py" line_range="821" />
<code_context>
+            return {}
+        try:
+            return json.loads(self.storage_path.read_text(encoding="utf-8"))
+        except Exception as exc:  # noqa: BLE001
+            logger.warning(
+                "Failed to load MCP OAuth storage %s: %s",
</code_context>
<issue_to_address>
**Probe failure contradicts saved authorization**

When token exchange succeeds but the subsequent MCP connectivity probe fails, the OAuth provider saves tokens during token exchange, before `_run_flow` probes the MCP endpoint. If that probe fails, `_run_flow` marks the flow failed but leaves the tokens in storage, so the dashboard reports failure while the server's OAuth state reports authorized.

Report token authorization separately from probe connectivity, or clear/restore tokens consistently when the overall flow is marked failed.
</issue_to_address>

### Comment 10
<location path="astrbot/dashboard/api/tools.py" line_range="229" />
<code_context>
+    }
+    server_name = request.query_params.get("name")
+
+    return await _run(
+        lambda: service.start_mcp_oauth_authorization(
+            config,
</code_context>
<issue_to_address>
**OAuth failures escape API handling**

When OAuth setup fails or a client requests a status for a missing or expired flow, `_run` only converts `ToolsServiceError`, but authorization startup can raise `MCPOAuthError` directly and status lookup can raise `KeyError`. Those failures escape the dashboard's normal API error handling and become unstructured server errors instead of usable OAuth error responses.

Translate OAuth manager errors into `ToolsServiceError` or handle them explicitly in the dashboard endpoints.

Also at `astrbot/dashboard/api/tools.py:241`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 10 findings to address first, and a faulty OAuth implementation could accept or persist tokens incorrectly, expose MCP credentials, or grant access to a protected MCP server under the wrong authorization flow. Reverting stops the new behavior, but tokens already issued or access already obtained would outlive the revert and require revocation or cleanup.

Blocking findings: astrbot/core/agent/mcp_oauth.py:55, astrbot/core/agent/mcp_client.py:544, astrbot/core/agent/mcp_oauth.py:101, astrbot/core/agent/mcp_oauth.py:760, astrbot/core/agent/mcp_oauth.py:114, and 5 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

"authorization_code"
)
client_id: str | None = None
client_secret: str | None = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 High · OAuth client secrets are exposed

When an MCP server has oauth2.client_secret configured and a caller with the mcp API-key scope lists servers, ToolsService.get_mcp_servers includes the secret in its response, so the caller receives credentials they can reuse.

Remove or redact oauth2.client_secret from the server-list response.

Prompt for AI agents
In `astrbot/core/agent/mcp_oauth.py` at line 55:

**OAuth client secrets are exposed**

When an MCP server has `oauth2.client_secret` configured and a caller with the `mcp` API-key scope lists servers, `ToolsService.get_mcp_servers` includes the secret in its response, so the caller receives credentials they can reuse.

Remove or redact `oauth2.client_secret` from the server-list response.

Comment thread astrbot/core/agent/mcp_client.py Resolved
Comment thread astrbot/core/agent/mcp_oauth.py Resolved
Comment thread astrbot/core/agent/mcp_oauth.py Resolved
Comment thread astrbot/core/agent/mcp_oauth.py Resolved
Comment thread astrbot/core/agent/mcp_oauth.py Resolved
Comment on lines +1005 to +1008
this.stopOauthPolling();
this.addServerDialogMessage = this.tm('messages.oauthAuthorized');
this.showSuccess(this.tm('messages.oauthAuthorized'));
} else if (this.oauthFlowStatus === 'failed') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 High · Authorized servers remain disconnected

When an active server failed startup while authorization was missing and the user then authorizes it, the dashboard reports OAuth success but does not reconnect or initialize the MCP client. The server remains disconnected and its tools stay unavailable.

Reconnect or initialize the active MCP server after authorization completes successfully.

Also at astrbot/core/agent/mcp_oauth.py:821, dashboard/src/components/extension/McpServersSection.vue:955.

Prompt for AI agents
In `dashboard/src/components/extension/McpServersSection.vue` at lines 1005-1008:

**Authorized servers remain disconnected**

When an active server failed startup while authorization was missing and the user then authorizes it, the dashboard reports OAuth success but does not reconnect or initialize the MCP client. The server remains disconnected and its tools stay unavailable.

Reconnect or initialize the active MCP server after authorization completes successfully.

Also at `astrbot/core/agent/mcp_oauth.py:821`, `dashboard/src/components/extension/McpServersSection.vue:955`.

if flow.created_at < threshold
]
for flow_id in expired_ids:
expired_states = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · Expired flows leave tasks running

When an authorization flow remains unfinished past its 15-minute TTL, _prune_flows removes expired flows from its maps without cancelling their tasks. Those tasks remain blocked waiting for callbacks, retaining flow and provider objects as abandoned authorizations accumulate.

Cancel each expired flow task when pruning its flow.

Also at astrbot/core/agent/mcp_oauth.py:808.

Prompt for AI agents
In `astrbot/core/agent/mcp_oauth.py` at line 801:

**Expired flows leave tasks running**

When an authorization flow remains unfinished past its 15-minute TTL, `_prune_flows` removes expired flows from its maps without cancelling their tasks. Those tasks remain blocked waiting for callbacks, retaining flow and provider objects as abandoned authorizations accumulate.

Cancel each expired flow task when pruning its flow.

Also at `astrbot/core/agent/mcp_oauth.py:808`.

Comment thread astrbot/core/agent/mcp_oauth.py Resolved
}
server_name = request.query_params.get("name")

return await _run(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · OAuth failures escape API handling

When OAuth setup fails or a client requests a status for a missing or expired flow, _run only converts ToolsServiceError, but authorization startup can raise MCPOAuthError directly and status lookup can raise KeyError. Those failures escape the dashboard's normal API error handling and become unstructured server errors instead of usable OAuth error responses.

Translate OAuth manager errors into ToolsServiceError or handle them explicitly in the dashboard endpoints.

Also at astrbot/dashboard/api/tools.py:241.

Prompt for AI agents
In `astrbot/dashboard/api/tools.py` at line 229:

**OAuth failures escape API handling**

When OAuth setup fails or a client requests a status for a missing or expired flow, `_run` only converts `ToolsServiceError`, but authorization startup can raise `MCPOAuthError` directly and status lookup can raise `KeyError`. Those failures escape the dashboard's normal API error handling and become unstructured server errors instead of usable OAuth error responses.

Translate OAuth manager errors into `ToolsServiceError` or handle them explicitly in the dashboard endpoints.

Also at `astrbot/dashboard/api/tools.py:241`.

- Apply shared OAuth defaults (mcp_oauth_* global config) when creating
  runtime auth and checking OAuth status, matching the authorization
  flow, so all paths derive the same token-storage fingerprint
- Ignore configured redirect_uri values whose path is not the registered
  /mcp/oauth/callback dashboard route instead of sending the provider to
  an unhandled callback
- Follow callback_api_base changes for auto-populated
  mcp_oauth_callback_base by comparing against the previous base
- Probe SSE/streamable-HTTP endpoints with streaming requests so an open
  event-stream body is never buffered until timeout
- Restore pre-flow token storage when an OAuth flow fails after token
  exchange, keeping dashboard status and OAuth state consistent
- Use the configured OAuth timeout for authorization preparation instead
  of a fixed 15s limit
… ru-RU

- ja-JP: add OAuth 2.0 buttons/status/dialog texts, oauth messages,
  dialogs.syncProvider section, mcp_oauth_* config metadata, and the MCP
  settings group
- en-US: add missing dialogs.syncProvider section
- ru-RU: add dialogs.syncProvider section, mcp_oauth_* config metadata,
  and the MCP settings group
- npm run i18n:check now passes for all four locales (4180 keys each)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

3 participants