Repository navigation
Conversation
There was a problem hiding this comment.
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
| "authorization_code" | ||
| ) | ||
| client_id: str | None = None | ||
| client_secret: str | None = None |
There was a problem hiding this comment.
🟠 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.| this.stopOauthPolling(); | ||
| this.addServerDialogMessage = this.tm('messages.oauthAuthorized'); | ||
| this.showSuccess(this.tm('messages.oauthAuthorized')); | ||
| } else if (this.oauthFlowStatus === 'failed') { |
There was a problem hiding this comment.
🟠 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 = [ |
There was a problem hiding this comment.
🟡 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`.| } | ||
| server_name = request.query_params.get("name") | ||
|
|
||
| return await _run( |
There was a problem hiding this comment.
🟡 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)
0c23ee2 to
75e5fe8
Compare
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 / 改动点
astrbot/core/agent/mcp_oauth.pyand integrated auth into MCP transports.docs/zh/use/mcp.mdanddocs/en/use/mcp.md.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 / 检查清单
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:
Bug Fixes:
Enhancements:
Documentation:
Tests: