Files
Wenxi 1e15e42f71 fix(mcp): publish connection changes only after validation (#16418)
## Description

Validate MCP authentication and tool discovery before saving a new
connection or changing an existing connection. Failed attempts leave the
saved URL, credentials, and tools unchanged.

Save validated settings, credentials, tools, and requested Chat/Craft
choices in one transaction. Reject stale policy/configuration edits
while allowing ordinary token refresh. Preserve registered OAuth client
settings and safely reuse an unexpired grant without rotating its
refresh token during validation. Support SSE discovery with the
exchanged bearer. Preserve omitted transports and valid grants without
expiry. Lock policy and default Chat rows before the final stale-edit
check, using the shared locking helper from main.

Tool discovery now returns a structured authentication error for
upstream HTTP 401 responses, including nested transport failures. Setup
and saved-connection refresh share this mapping. Runtime credential
rejection handling keeps the original transport errors. Async setup
handlers await publication in a worker thread so database lock waits do
not block the event loop.

## How Has This Been Tested?

MCP and route unit tests passed, including SSE discovery, failed
publication, safe token reuse, and immutable credential snapshots.
Python typing, lint, formatting, and route permission checks passed.

All 11 PostgreSQL setup/edit regression tests passed locally after the
final fixture corrections. They cover failed publication, stale edits,
OAuth registration metadata, and preservation of refreshed credentials.
The expanded MCP, runtime, and route suite passed 375 tests. An
unauthenticated request to the live GitHub MCP endpoint confirmed a
sanitized 401 response without database writes. All 17 focused setup API
tests pass after the worker-thread change, including both publication
paths. CI is rerunning on the updated commit. Live provider sign-in
remains unverified.

## Additional Options

- [ ] [Optional] Please cherry-pick this PR to the latest release
version.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **New Features**
- Added an MCP setup workflow to validate server settings, authenticate
connections, discover tools, and review configuration before publishing.
- Added OAuth authorization and callback support, including reuse of
valid saved grants.
- Setup changes are published atomically, protecting existing
configurations when validation, authentication, or discovery fails.
- Added safeguards against stale concurrent edits overwriting newer
configuration changes.

- **Bug Fixes**
- Improved MCP authentication error handling, including clearer handling
of unauthorized responses during tool discovery.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-10-21 23:21:13 +00:00
..