Skip to content

fix(connectors): MCP single-writer enforcement + security hardening (#976) - #998

Merged
itomek merged 1 commit into
mainfrom
feat/976-mcp-single-writer-security
May 8, 2026
Merged

itomek merged 1 commit into
mainfrom
feat/976-mcp-single-writer-security

Conversation

@itomek

@itomek itomek commented May 8, 2026

Copy link
Copy Markdown
Collaborator

Closes #976. Part of #927.

Three vulnerabilities shipped on main that this PR fixes:

  1. Dual-writer / plaintext secret leak — MCPConfig.add_server, POST /api/mcp/servers, and gaia mcp add all wrote mcp_servers.json directly, bypassing the keyring. API keys ended up plaintext on disk. Now McpServerHandler.configure() is the sole writer; everything else is read-only or deleted.

  2. Keyring exfiltration at MCP spawn time — _resolve_keyring_refs accepted any service string in a $keyring reference. A corrupted mcp_servers.json could carry "Chrome Safe Storage:Chrome:..." and inject another app's secrets into a spawned MCP subprocess env. Now any service other than gaia.connections is rejected before keyring.get_password is called.

  3. Silent grant inheritance on reconnect — disconnect() cleared keyring entries but left grants.json intact. Re-adding a connector with the same id silently re-attached prior agent consents — a real bypass. Both McpServerHandler and OAuthPkceHandler now call revoke_all_grants_for(connector_id) on disconnect.

Plus: rehype-raw in MessageBubble.tsx allowed LLM-generated <script> tags and javascript: URLs to execute in the Electron renderer. Replaced with SAFE_DISALLOWED_ELEMENTS + safeUrlTransform (new src/utils/markdown.ts).

Catalog reduction

The 22-entry MCP catalog is reduced to 5 tested entries: mcp-github, mcp-filesystem, mcp-fetch, mcp-memory, mcp-git. The other 17 had zero test or doc coverage and are deleted. Users who want the deleted servers use the custom MCP path (tracked in #977).

Test plan

# New regression guards (22 new tests across 3 new files)
pytest tests/unit/connectors/test_catalog_ledger.py -v         # catalog ledger: 4 pass, 5 skip
pytest tests/unit/connectors/test_no_dual_writer.py -v         # dual-writer guard: 9 pass
pytest tests/unit/connectors/test_disconnect_clears_grants.py -v  # grant cleanup: 4 pass

# Keyring security (service pinning + fail-closed)
pytest tests/unit/connectors/test_mcp_server.py::TestResolveKeyringRefs -v  # 6 pass

# Full connectors suite
pytest tests/unit/connectors/ -q  # 305 pass, 5 skip, 1 pre-existing failure (test_oauth_pkce unrelated)

# Verify deletions
grep "rehype-raw" src/gaia/apps/webui/package.json            # nothing
grep -c "ConnectorSpec(" src/gaia/connectors/catalog/mcp_servers.py  # 5
python -m gaia.cli mcp --help                                  # no add/remove subcommands

…976)

Closes #976. Part of #927.

Before this change, three code paths independently wrote `~/.gaia/mcp_servers.json`,
two of them bypassing the keyring and storing API keys as plaintext. A compromised
MCP server entry could also exfiltrate arbitrary keyring secrets at spawn time,
disconnecting a connector left prior agent grants intact for re-use, and LLM output
in the Electron renderer could inject `<script>` tags via `rehype-raw`.

Changes:
- Delete `MCPConfig.add_server`, `remove_server`, `_save` — config.py is now read-only;
  `McpServerHandler.configure()` is the sole writer of mcp_servers.json
- Delete `POST /api/mcp/servers`, `DELETE /api/mcp/servers/{name}`, enable/disable, and
  `GET /api/mcp/catalog` from mcp.py; delete corresponding dead stubs from api.ts
- Remove `gaia mcp add` and `gaia mcp remove` CLI subcommands (runtime commands kept)
- Pin `_resolve_keyring_refs` to service `gaia.connections`; raise `ConnectorsError`
  (not `RuntimeError`) on foreign service or missing entry, with an actionable message
- Wipe all agent grants (`revoke_all_grants_for`) in both `McpServerHandler.disconnect`
  and `OAuthPkceHandler.disconnect` — prevents silent grant inheritance on reconnect
- Harden file permissions: `chmod 0600` on `mcp_servers.json` and `grants.json` after
  every atomic write
- Reduce MCP catalog from 22 to 5 tested entries (mcp-github, mcp-filesystem, mcp-fetch,
  mcp-memory, mcp-git); delete 17 untested entries that had zero test/doc coverage
- Replace `rehype-raw` with hardened `SAFE_DISALLOWED_ELEMENTS` + `safeUrlTransform` in
  MessageBubble; new `src/utils/markdown.ts` centralises the safe rendering policy

Tests: 3 new test files (22 tests) — catalog ledger, dual-writer regression guard,
disconnect-clears-grants; keyring tests extended with foreign-service refusal case.
305 connectors tests pass (1 pre-existing failure in test_oauth_pkce unrelated to this PR).
@github-actions github-actions Bot added mcp MCP integration changes cli CLI changes tests Test changes labels May 8, 2026
@itomek itomek self-assigned this May 8, 2026
itomek added a commit that referenced this pull request May 8, 2026
Closes #1004. Part of #927. Builds on #976 (PR #998).

Users can now temporarily disable a configured MCP connector without
losing its credentials or per-agent grants. Toggle off the GitHub MCP
during a sensitive code review, toggle back on without re-pasting the
PAT — credentials and agent consent persist across the round-trip.

Persistence already worked: ``mcp_servers.json`` carries a per-entry
``disabled`` flag and ``MCPClientManager.load_from_config()`` already
skips disabled entries. This PR adds the API/UI/wiring to drive it.

Backend:
- ``McpServerHandler.set_enabled(connector_id, enabled)`` flips the
  ``disabled`` flag without touching keyring or grants. Reuses #976's
  atomic-write + chmod 0600 helpers; raises ``ConnectorsError`` on
  unknown / unconfigured ids
- ``McpServerHandler.set_reload_callback`` setter so the FastAPI
  lifespan can attach a callback after the singleton handler imports
- New endpoints ``POST /api/connectors/{id}/enable`` and ``/disable``
  (CSRF-guarded, 400 on non-MCP types, 404 on unconfigured)
- New SSE events ``connector.enabled`` / ``connector.disabled``
- ``_connector_summary`` exposes ``enabled: bool`` (defaults true for
  OAuth / not-yet-configured MCP so no spurious "Disabled" pills)
- ``reload_all_session_agents_mcp`` broadcasts to every cached
  ChatAgent's per-instance MCPClientManager — wired as the handler's
  reload_callback at lifespan startup. Toggling takes effect live; no
  GAIA restart needed

Frontend:
- ``ConnectorRow.enabled: boolean`` on the wire
- ``enableConnector`` / ``disableConnector`` API helpers
- SSE consumer recognises ``'enabled' | 'disabled'`` reasons
- Toggle row in MCPServerConfigureBody (only when configured), with
  helper text when disabled. Reuses existing ``.toggle-switch`` CSS
- New ConnectorTileMenu (⋯) on each tile header for one-click
  enable/disable/disconnect without drilling in. Self-positioning
  popup, click-outside + Escape to close
- New ``.connector-status.disabled`` pill in the tile header

Tests: 30 new (12 handler + 14 router + 4 reload-wiring). Full
connectors suite: 335 pass, 5 skipped, 1 pre-existing failure
(test_oauth_pkce, unrelated).
@itomek
itomek marked this pull request as ready for review May 8, 2026 20:43
@itomek
itomek requested a review from kovtcharov-amd as a code owner May 8, 2026 20:43
@itomek
itomek enabled auto-merge May 8, 2026 20:45
@itomek
itomek added this pull request to the merge queue May 8, 2026
Merged via the queue into main with commit b8e0cfa May 8, 2026
60 of 61 checks passed
@itomek
itomek deleted the feat/976-mcp-single-writer-security branch May 8, 2026 21:18
itomek added a commit that referenced this pull request May 8, 2026
Closes #1004. Part of #927. Builds on #976 (PR #998).

Users can now temporarily disable a configured MCP connector without
losing its credentials or per-agent grants. Toggle off the GitHub MCP
during a sensitive code review, toggle back on without re-pasting the
PAT — credentials and agent consent persist across the round-trip.

Persistence already worked: ``mcp_servers.json`` carries a per-entry
``disabled`` flag and ``MCPClientManager.load_from_config()`` already
skips disabled entries. This PR adds the API/UI/wiring to drive it.

Backend:
- ``McpServerHandler.set_enabled(connector_id, enabled)`` flips the
  ``disabled`` flag without touching keyring or grants. Reuses #976's
  atomic-write + chmod 0600 helpers; raises ``ConnectorsError`` on
  unknown / unconfigured ids
- ``McpServerHandler.set_reload_callback`` setter so the FastAPI
  lifespan can attach a callback after the singleton handler imports
- New endpoints ``POST /api/connectors/{id}/enable`` and ``/disable``
  (CSRF-guarded, 400 on non-MCP types, 404 on unconfigured)
- New SSE events ``connector.enabled`` / ``connector.disabled``
- ``_connector_summary`` exposes ``enabled: bool`` (defaults true for
  OAuth / not-yet-configured MCP so no spurious "Disabled" pills)
- ``reload_all_session_agents_mcp`` broadcasts to every cached
  ChatAgent's per-instance MCPClientManager — wired as the handler's
  reload_callback at lifespan startup. Toggling takes effect live; no
  GAIA restart needed

Frontend:
- ``ConnectorRow.enabled: boolean`` on the wire
- ``enableConnector`` / ``disableConnector`` API helpers
- SSE consumer recognises ``'enabled' | 'disabled'`` reasons
- Toggle row in MCPServerConfigureBody (only when configured), with
  helper text when disabled. Reuses existing ``.toggle-switch`` CSS
- New ConnectorTileMenu (⋯) on each tile header for one-click
  enable/disable/disconnect without drilling in. Self-positioning
  popup, click-outside + Escape to close
- New ``.connector-status.disabled`` pill in the tile header

Tests: 30 new (12 handler + 14 router + 4 reload-wiring). Full
connectors suite: 335 pass, 5 skipped, 1 pre-existing failure
(test_oauth_pkce, unrelated).
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request May 11, 2026
) (amd#1018)

Closes amd#1004. Part of amd#927. **Builds on PR amd#998 — please merge that
first.**

Users can now temporarily disable a configured MCP connector without
losing its credentials or per-agent grants. Concrete user flow: toggle
off GitHub MCP during a sensitive code review → toggle back on without
re-pasting the PAT or re-granting agents.

The `disabled` flag was already persisted in `mcp_servers.json` and
`MCPClientManager.load_from_config()` already skipped disabled entries.
This PR adds the API/UI/live-reload wiring to drive it.

## What lands

- **Toggle row** in the connector detail view (above credentials), only
when configured. Shows helper text when off.
- **Tile-level overflow menu** (⋯) for one-click
enable/disable/disconnect without drilling in.
- **Tile status pill** flips to a warm-muted "Disabled" state (distinct
from cool-muted "Not configured" so users see at a glance these are
different states).
- **`POST /api/connectors/{id}/enable`** and `/disable` (CSRF-guarded,
400 on non-MCP types, 404 on unconfigured ids).
- **Live reload** — the lifespan wires a broadcast helper that calls
`manager.reload()` on every cached ChatAgent's per-instance
`MCPClientManager`. Toggling takes effect without restarting GAIA.

## Test plan

- [ ] `python -m pytest tests/unit/connectors/test_enable_disable.py -v`
— 12 handler tests pass
- [ ] `python -m pytest
tests/unit/connectors/test_router_connectors.py::TestEnableDisable -v` —
8 router tests pass
- [ ] `python -m pytest
tests/unit/connectors/test_handler_reload_wired.py -v` — 4 wiring tests
pass
- [ ] Manual: configure `mcp-github` with a PAT → ChatAgent uses tools →
click ⋯ on the GitHub tile → Disable → ChatAgent no longer sees GitHub
tools (no restart) → Enable → tools return → restart GAIA → state
persists.
- [ ] `cd src/gaia/apps/webui && npx tsc --noEmit && npm run build`
- [ ] `python util/lint.py --all`
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request May 12, 2026
…md#1035)

## Why this matters

Before: Code Quality CI fails on every PR with \`F401 'os' imported but
unused\` at
\`tests/unit/connectors/test_disconnect_clears_grants.py:18\`.
Introduced incidentally by amd#998. Blocks amd#1026 and any subsequent PR from
going green.

After: import removed, flake8 exits clean.

## Test plan

- [x] \`flake8 src/ tests/ --max-line-length=88
--extend-ignore=E203,W503,E501,F541,W291,W293,E402,F841,E722\` → 0
errors
@itomek itomek mentioned this pull request May 14, 2026
5 of 6 tasks
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request May 15, 2026
## Why this matters

v0.18.0 ships agent memory v2 (hybrid-search second brain with LLM
extraction and observability dashboard), ChatAgent split into three
composable agents (Chat/FileIO/DocumentQA), parallel tool calls, and a
Telegram adapter scaffold — plus fixes the RAG-on-PDF timeout with Gemma
4 that broke document Q&A since v0.17.6 and adds CI gates that enforce
RAG quality baselines on every future PR.

Full notes: `docs/releases/v0.18.0.mdx`.

## What's New

- **Agent memory v2** ([amd#606](amd#606)) —
Hybrid semantic + keyword search, LLM extraction, observability
dashboard via SSE streaming
([amd#1032](amd#1032)). Per-user isolation
enforced; extraction runs async so it doesn't add latency.
- **ChatAgent split** ([amd#979](amd#979)) —
`ChatAgent`, `FileIOAgent`, and `DocumentQAAgent` replace the monolithic
class; each composable via `tools=`. Backward-compatible shim preserved.
- **Parallel tool calls** ([amd#946](amd#946))
— Multiple `tool_calls` from a single LLM turn are executed
concurrently, cutting round-trips for multi-tool workflows.
- **Telegram adapter scaffold, Phase 0**
([amd#951](amd#951)) — `gaia telegram
start|stop|status`, per-user session isolation, `[telegram]` extras.
Phase 1 (message handling + allowed-users gate) tracked in
[amd#889](amd#889).
- **Connectors: per-MCP toggle + single-writer enforcement**
([amd#1018](amd#1018),
[amd#998](amd#998)) — Disable individual MCP
servers without removing them; concurrent writes serialised with
actionable errors on contention.
- **File navigation, web browsing, and write security**
([amd#495](amd#495)) — `FileSearchToolsMixin`,
web browsing tool, and scratchpad mixin in `KNOWN_TOOLS`; write tools
check `allowed_paths` before dispatch.
- **Email UI and policy alerts**
([amd#995](amd#995),
[amd#1039](amd#1039),
[amd#952](amd#952)) — Pre-scan triage card,
in-chat Connect, policy alert cards, and durable receipts for
confirmation-gated actions.

## Bug Fixes

- **RAG-on-PDF timeouts on Gemma 4**
([amd#1034](amd#1034), closes
[amd#1030](amd#1030)) — Prompt-size budget
check added at composition time; CI gates enforce it on every PR
([amd#1040](amd#1040)).
- **Envelope-level parse failure crashed SD recovery**
([amd#1047](amd#1047), closes
[amd#1023](amd#1023)) — Falls through to a
clean recovery path with step-1 context preserved.
- **Windows-path tool args corrupted**
([amd#1027](amd#1027)) — Backslash
normalisation now happens after argument parsing.
- **Blender `send_command` hung**
([amd#1026](amd#1026), closes
[amd#1022](amd#1022)) — Read timeout applied
to persistent-connection servers.
- **`gaia chat init` in post-install banner**
([amd#1029](amd#1029), closes
[amd#1024](amd#1024)) — Replaced with the
correct `gaia init`.
- **Keyring treated as required**
([amd#1028](amd#1028)) — Import guarded;
optional on systems without `keyring`.
- **electron-builder URLs stale**
([amd#953](amd#953)) — Three doc/installer
files updated to current download paths.

## Tooling & Docs

- **RAG eval CI gates** ([amd#1040](amd#1040),
closes [amd#1033](amd#1033)) — RAG quality
baselines + prompt-size budget enforced on every PR.
- **Fork-PR authors now receive Claude review**
([amd#932](amd#932)) —
`allowed_non_write_users: "*"` with prompt-injection mitigations
documented.
- **Eval runs mandated before merging**
([amd#1036](amd#1036)) — `CLAUDE.md` requires
`gaia eval agent` for LLM-affecting changes.
- **GAIA website** ([amd#369](amd#369)) —
[amd-gaia.ai](https://amd-gaia.ai) live.
- **Custom agent guide reorganised**
([amd#997](amd#997)), Lemonade PPA docs
([amd#801](amd#801)), broken Lemonade CLI URL
fixed ([amd#996](amd#996)), WhatsApp adapter
evaluation spec ([amd#950](amd#950)).

## Release checklist

- [x] `util/validate_release_notes.py docs/releases/v0.18.0.mdx --tag
v0.18.0` passes
- [x] `src/gaia/version.py` → `0.18.0`
- [x] `src/gaia/apps/webui/package.json` → `0.18.0`
- [x] Navbar label in `docs/docs.json` → `v0.18.0 · Lemonade 10.2.0`
- [x] All 28 commits in range (v0.17.6..HEAD) are represented in the
notes
- [ ] Review from @kovtcharov-amd addressed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI changes mcp MCP integration changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(connectors): MCP single-writer + security hardening

2 participants