Repository navigation
feat(connectors): per-agent MCP tool-visibility activations (#1005) - #1219
Conversation
|
@claude review this PR. |
itomek
left a comment
There was a problem hiding this comment.
@alexey-tyurin — thorough, well-tested PR. The activations design cleanly mirrors the grants ledger (mode 0600, atomic writes, per-process lock), the MCP-only guard is enforced at the shared api.py layer every caller flows through, and the filter is wired into ChatAgent's tool registration with a guard test for the identity stamp. Closes #1005 with docs and 24 new tests. Approving.
Two follow-ups — please track in a follow-up PR or file issues so they aren't lost:
-
SSE only fires from the HTTP router.
connector.activation.changedis emitted from the PUT/DELETE handlers, but CLI/SDK toggles write the same ledger silently — so an open Settings tab won't reflect a CLI-driven change until the user navigates away and back. Worth routing CLI writes through the router, or adding a file-watcher onactivations.json. -
The "Active for" panel filters by
REQUIRED_CONNECTORS. The UI only surfaces agents that declare the connector inREQUIRED_CONNECTORS, sobuiltin:chatnever appears even though activations work for it via CLI/SDK and the runtime filter honors them — a UI/runtime mismatch worth widening for MCP-consuming agents that load servers from~/.gaia/mcp_servers.json.
Generated by Claude Code
|
Thanks for the thorough review and approval, @itomek — really appreciate it. Filed both follow-ups so they don't get lost: #1226 — emit connector.activation.changed for CLI/SDK activation writes so the Settings tab stays in sync with CLI toggles |
…ation writes (amd#1226) (amd#1309) <!-- Thanks for contributing to GAIA! Every PR must reference a GitHub issue — see CONTRIBUTING.md (https://github.com/amd/gaia/blob/main/CONTRIBUTING.md) if you don't have one yet. --> ## Summary CLI and SDK activation toggles now drive the same live `connector.activation.changed` SSE update that the HTTP router already emitted, so the Agent UI's "Active for" panel reflects them without a manual refresh. ## Why Activation writes from `gaia connectors activations activate/deactivate` (CLI) and direct SDK calls landed in `~/.gaia/connectors/activations.json` **silently** — only the HTTP `PUT/DELETE` handlers emitted `connector.activation.changed`. With the Agent UI Settings tab open, a CLI-driven toggle took effect on disk but the panel kept showing stale state until the user navigated away and back to force a refetch, making CLI ↔ UI workflows confusing. This was filed as an explicit follow-up on amd#1219. ## Linked issue Closes amd#1226 ## Changes - **Centralized the emit (`src/gaia/connectors/api.py`).** `activate()` / `deactivate()` now emit `connector.activation.changed` (`{connector_id, agent_id, active}`) after the ledger write, so HTTP, SDK, and any in-process caller all notify through one path — mirroring how amd#1219 centralized the MCP-only guard in `api.py`. - **New `emit_change()` helper (`src/gaia/connectors/events.py`).** A sync, loop-aware fire-and-forget wrapper so synchronous callers (`api`, CLI) can publish without being async. Inside the server loop it schedules on that loop and fans out to SSE subscribers; in a bare process it runs against the registered emitter (the no-op logging emitter). Failures are logged, never swallowed. - **Server-side ledger watcher (`src/gaia/connectors/activation_watcher.py`, new).** The CLI runs in a separate process from the UI server, where the SSE bus lives. A background watcher polls `activations.json`, diffs against a snapshot, and emits one event per changed `(connector, agent)` pair (~1 s) so cross-process CLI/SDK writes reach connected UI clients. In-process writes call `note_local_write(...)` to advance the snapshot per-pair, so they don't double-emit — and a concurrent change to a *different* pair is still caught. - **Watcher lifecycle (`src/gaia/ui/server.py`).** Started/stopped in the FastAPI lifespan, mirroring the existing `DocumentMonitor`. - **Router cleanup + guard fix (`src/gaia/ui/routers/connectors.py`).** Removed the now-duplicate inline emits from `PUT/DELETE`; `DELETE` now routes through `api.deactivate` instead of the bare ledger call, closing a pre-existing MCP-only-guard bypass on that route. - **Tests.** New `tests/unit/connectors/test_activation_watcher.py` (diff, poll-emit, dedup, don't-mask-other-pair) and extended `tests/unit/connectors/test_activation_api.py` (CLI→SSE path: emits on success, nothing on failure/rejection). - **Docs (`docs/sdk/infrastructure/connectors.mdx`).** Updated the activation SSE section to describe the centralized emit + watcher. No frontend changes — `useConnectorsSSE.ts` already consumes `connector.activation.changed`. ## Test plan - [x] `python util/lint.py --all` — all quality checks pass (Black, isort, Pylint, Flake8 green; pre-existing MyPy/Bandit/agent-convention warnings only, none in touched files). - [x] `python -m pytest tests/unit/connectors/test_activation_api.py tests/unit/connectors/test_activation_watcher.py tests/unit/connectors/test_router_connectors.py` — 77 passed. - [x] `python -m pytest tests/unit/connectors/` — 436 passed, 3 skipped. - [x] Manual cross-process live update: start the UI server, open Settings → Connectors → expand an MCP connector's "Active for"; in a second terminal run `gaia connectors activations activate mcp-github builtin:connectors-demo --scopes use` → panel flips to active with no refresh; `gaia connectors activations deactivate mcp-github builtin:connectors-demo` → flips back live. ## Follow-ups (not in this PR — gaps found while doing this work) - **`DispatchQueue` worker logs after the test stream closes (pre-existing).** Any UI test that boots a `TestClient` prints repeated `--- Logging error --- ValueError: I/O operation on closed file` blocks pointing at `src/gaia/ui/server.py:267` (`_import_modules` logging the faiss-load line). Root cause: `DispatchQueue.shutdown` (`src/gaia/ui/dispatch.py:104-105`) calls `self._executor.shutdown(wait=False)`, so a boot-init worker thread (the slow `faiss` import) is still running and logs after pytest closed the captured stream. Cosmetic (tests pass, exit 0) and reproduces on `main` with this PR stashed. **Suggested fix:** have `shutdown` drain in-flight boot jobs with a bounded wait, e.g. `await loop.run_in_executor(None, lambda: self._executor.shutdown(wait=True, cancel_futures=True))` under a timeout, so no worker logs post-teardown. - **`StarletteDeprecationWarning: Using httpx with starlette.testclient is deprecated; install httpx2` (pre-existing, repo-wide).** Emitted by any test using the shared `ui_api_client` `TestClient` fixture (origin `tests/conftest.py:355`); pytest dedupes it to a single "1 warning" line. Not introduced here (reproduces on `main` with this PR stashed). **Suggested fix:** bump to `httpx2` per Starlette's guidance, or add a scoped `filterwarnings` entry in `pyproject.toml`. ## Checklist - [x] I have linked a GitHub issue above (`Closes amd#1226`). - [x] I have described **why** this change is being made, not just what changed. - [x] I have run linting and tests locally (`python util/lint.py --all`, `pytest tests/unit/`). - [x] I have updated documentation if user-visible behavior changed (see [CONTRIBUTING.md](../CONTRIBUTING.md)). Co-authored-by: Alexey Tyurin <>
…nel (amd#1227) (amd#1310) <!-- Thanks for contributing to GAIA! Every PR must reference a GitHub issue — see CONTRIBUTING.md (https://github.com/amd/gaia/blob/main/CONTRIBUTING.md) if you don't have one yet. --> ## Summary Widens the Settings → Connectors **"Active for"** panel so it lists agents that consume MCP servers *dynamically* (like the chat agent), not only agents that statically declare `REQUIRED_CONNECTORS`. The chat agent now appears as an activatable target for MCP-only connectors loaded from `~/.gaia/mcp_servers.json`. ## Why Before this change, the "Active for" panel only listed agents whose class declared the connector in `REQUIRED_CONNECTORS`. The chat agent (`builtin:chat`) declares none for MCP servers — it loads them at runtime and already gates their tools through the activation ledger (`_active_mcp_servers` → `MCPClientManager.servers_for_agent` → `is_agent_active`). So a user could activate `builtin:chat` for an MCP connector via the CLI/SDK and it worked, but the Settings UI never showed the chat agent as eligible — a UI-only user had no way to toggle it. The runtime was correct; the panel just couldn't see these agents. This PR closes that surfacing gap by adding a `CONSUMES_MCP_SERVERS` capability flag that flows from the agent class through the registry and API to the frontend, exactly the way `REQUIRED_CONNECTORS` already does. No activation, ledger, or SSE logic changes — those already work end-to-end (amd#1005, amd#1226). Follow-up to amd#1219, which introduced per-agent MCP tool-visibility activations. ## Linked issue Closes amd#1227 ## Changes - **New capability flag, surfaced like `REQUIRED_CONNECTORS`:** `Agent.CONSUMES_MCP_SERVERS` ClassVar (`False` by default), set `True` on `ChatAgent`. The registry carries it as `AgentRegistration.consumes_mcp_servers` — hardcoded for the built-in chat (its lazy factory must not import the chat module at discovery time; a guard test keeps the two in sync) and read via class introspection on the custom-agent discovery path, so builder-scaffolded MCP agents surface automatically too. - **API exposure:** `AgentInfo.consumes_mcp_servers` (Pydantic) + the `/api/agents` serializer (`_reg_to_info`), and the matching TypeScript `AgentInfo` field. - **Frontend:** `ConnectorsSection.tsx` computes a separate, wider `activatableAgents` set for the "Active for" block (an agent is eligible if it declares the connector **or** sets `consumes_mcp_servers`); the "Per-agent grants" credential section is unchanged. `AgentActivationCard` no longer bails when an agent has no static requirement, and its one-click auto-grant falls back to the canonical MCP `use` scope for dynamic consumers (named constant, not a magic string). - **Docs:** `docs/sdk/infrastructure/connectors.mdx` documents the new `CONSUMES_MCP_SERVERS` flag in the agent-author guide and adds a "Which agents appear in the Active for panel" section covering both inclusion patterns. - **Tests:** base default, chat flag, class↔registration consistency guard, "no other built-in consumes MCP", custom-agent round-trip (`True` and default `False`), `AgentInfo` round-trip, and `_reg_to_info` exposure for a consumer vs a non-consumer. ## Test plan - [x] `python util/lint.py --all` — Black/isort clean, no new critical errors. - [x] `pytest tests/unit/test_agent_required_connectors.py tests/unit/test_agent_hub_api.py -q` — 30 passed. - [x] `pytest tests/unit/connectors/ -q` — 429 passed, 3 skipped (no regressions). - [x] `cd src/gaia/apps/webui && npm run build` — `tsc && vite build` clean. - [x] **Manual golden path:** add an MCP server to `~/.gaia/mcp_servers.json` and configure it as an MCP connector → `gaia chat --ui` → Settings → Connectors → open the MCP tile. Confirm **Chat** now appears under "Active for"; toggle it ON. Verify `gaia connectors activations list <connector_id>` shows `builtin:chat: active` and the toggle survives a page reload (SSE refresh). Toggle OFF and confirm deactivation. Confirm an OAuth connector still shows **no** "Active for" section. ## Checklist - [x] I have linked a GitHub issue above (`Closes #N` / `Fixes #N` / `Refs #N`). - [x] I have described **why** this change is being made, not just what changed. - [x] I have run linting and tests locally (`python util/lint.py --all`, `pytest tests/unit/`). - [x] I have updated documentation if user-visible behavior changed (see [CONTRIBUTING.md](../CONTRIBUTING.md)). --------- Co-authored-by: Alexey Tyurin <>
amd#1586) ## Summary `_load_embedder()` now issues a **model-scoped** Lemonade `/unload` (embedder only) instead of a global one, so the chat model is no longer evicted when RAG first loads its embedder. ## Why When the doc agent did its first RAG work, `_load_embedder()` called a **global** `/unload` to force a fresh embedder load. That global unload also evicted the **chat model**, so the next generation turn cold-reloaded it (~100–150 s on the reporter's M2 Max) — slow enough to hit Lemonade's 120 s read-timeout and time out an entire eval scenario (`smart_discovery` produced **0 judged turns**). Lemonade can hold the chat model and embedder at once; the code only ever meant to refresh the *embedder*. The chat-model reload was pure collateral damage. ## Linked issue Closes amd#1544 ## Changes - `lemonade_client.py` — `unload_model()` gains an optional `model_name`; when given it sends `{"model_name": ...}` so Lemonade unloads only that model, and `self.model` is cleared only on a global unload or when it matches. No arg = global, preserving every existing caller (chat preflight, init, UI eviction). - `base_client.py` / `providers/lemonade.py` — widen the `unload_model` signature to match and pass through. - `rag/sdk.py` — `_load_embedder()` does a scoped unload of the embedder then reloads it; removed the two broad `except Exception: … continue` swallows so a real embedder failure surfaces instead of silently pretending RAG is ready (no-silent-fallbacks). Stale docstring corrected. - Tests — scoped-vs-global `/unload` payload test (`test_lemonade_client.py`); RAG cold-start regression asserting the embedder unload is scoped and the chat model is never globally unloaded (`test_rag.py`). ## Test plan <!-- Full tests/unit/ is not run because tests/unit/test_file_tools.py hangs (see amd#1219); the files below are the ones this change affects. --> - [x] `python util/lint.py --all` — black + isort clean. - [x] `pytest tests/test_rag.py tests/test_lemonade_client.py tests/unit/test_chat_preflight.py -k "not Integration"` — **118 passed**. (The `TestLemonadeClientIntegration` cases require a Windows/NPU Hybrid model and only run on that hardware.) - [x] New regression tests pass: `test_load_embedder_scoped_unload_keeps_chat_model_resident` (test_rag.py), `test_unload_model_scoped_vs_global` (test_lemonade_client.py). - [x] On-machine eval (M2 Max): `_load_embedder` logs `"chat model left resident"`; `smart_discovery` is now **judged** instead of 0-turn timeout; per-turn TTFT stays ≤60 s (e.g. a 3.3 s TTFT immediately after an embedder load) with no ~100 s chat-model cold reload. Headline scorecard vs the committed baseline is **not** comparable on this hardware — the baseline was generated on ~6.5× faster (NPU) hardware (122.9 tok/s / 0.31 s TTFT vs 18.9 tok/s / 20.8 s TTFT). ## Checklist - [x] I have linked a GitHub issue above (`Closes amd#1544`). - [x] I have described **why** this change is being made, not just what changed. - [x] I have run linting and selected unit tests locally (`python util/lint.py --all`; `pytest tests/test_rag.py tests/test_lemonade_client.py tests/unit/test_chat_preflight.py -k "not Integration"`). Full `tests/unit/` is not run because `tests/unit/test_file_tools.py` hangs — see amd#1219. - [ ] I have updated documentation if user-visible behavior changed — N/A, internal model-lifecycle fix with no user-facing surface change. --------- Co-authored-by: Alexey Tyurin <> Co-authored-by: kovtcharov-amd <[email protected]> Co-authored-by: Tomasz Iniewicz <[email protected]>
Summary
Per-agent MCP tool-visibility activations, layered on top of the PR #926 connectors framework. Users now have two independent axes of control: grants (credential access, already shipped) and activations (which MCP-server tools land in an agent's prompt). Activations default to OFF — explicit opt-in per
(connector, agent).Why
Today, every granted MCP connector's tools surface to every agent that holds a grant. A
ChatAgentwith several MCP servers granted sees ~30 extra tool descriptions in its system prompt — bloating context and degrading small-model tool selection. Issue #1005 asks for a separate signal between "this agent is allowed to use this connector" (grant) and "this agent currently sees its tools" (activation). Activation also gives users a least-privilege opt-in posture: a granted-but-inactive agent cannot select the tools at all, even if a prompt-injection tried to coax it into trying.Activations apply to MCP-server connectors only. OAuth connectors (Google, etc.) reach providers through native Python
@toolfunctions that callget_credential_syncdirectly — there is no MCP tool surface for activations to gate. Per-agent control of OAuth access stays on the per-scope grant toggles already shipped by #926. Callingactivate()/deactivate()for an OAuth connector is rejected at every boundary (HTTP 400, SDKConfigurationError, CLI exit 3); the UI hides the "Active for" section on OAuth tiles for the same reason.Linked issue
Closes #1005
Changes
src/gaia/connectors/activations.py— ledger at~/.gaia/connectors/activations.json, mode 0600, atomic-replace writes, per-process write lock, corruption recovery with actionablermhint. Mirrorsgrants.pyone-to-one in structure and rigour. Low-level API namedactivate_agent/deactivate_agent/is_agent_active/list_agent_activations/revoke_all_activations_for— matches thegrants.pynaming pattern (grant_agent,revoke_agent_grant).versionfield so future evolution has a forward-compat lever from day one:{ "version": 1, "activations": { "<connector_id>": { "<namespaced_agent_id>": true } } }[agent_id]-list values; this PR ships the object form so per-pair lookups are O(1) and a futurefalsevalue can carry meaning if needed.src/gaia/connectors/api.py— public orchestration helpersactivate/deactivate.activateauto-grants using the agent's declaredREQUIRED_CONNECTORSscopes when no prior grant exists (one-click convenience). MCP-only type guard at this layer — every caller (HTTP, CLI, SDK) flows through it. Auto-imports the catalog so bare-CLI callers can't trip "Unknown connector 'mcp-github'" on a cold REGISTRY.src/gaia/mcp/client/mcp_client_manager.py— newtools_for_agent(agent_id)andservers_for_agent(agent_id). Pure filter over the existing per-server tool catalogue. Withagent_id=None(CLI/debug context) the unfiltered list is returned — activations only gate the agent-tool path.src/gaia/agents/base/agent.py—_active_mcp_servers(manager)helper consumed by ChatAgent's_register_tools. Built-in@tool-decorated functions bypass the filter entirely — activations are an MCP-connector concept, not a Python-decorator one.src/gaia/agents/chat/agent.py+src/gaia/agents/registry.py+src/gaia/ui/_chat_helpers.py—ChatAgentConfig.namespaced_agent_idplus an early-init stamp so_register_toolssees the correct identity. Necessary because the registry wrapper used to stamp_gaia_namespaced_agent_idafter__init__returned — meaning the filter never actually fired for any UI Chat session. The wrapper now also injects via kwarg, and_chat_helpersstamps the config before each direct construction. Source-grep guard test catches any future directChatAgent(config)site that forgets the stamp.src/gaia/ui/routers/connectors.py—PUT/DELETE /api/connectors/{id}/activations/{agent_id:path}(CSRF-guarded, type-checked, SSE-emitting).GET /api/connectors/{id}/activations. Existing connector summary gains anactivations: Dict[str, bool]field.src/gaia/connectors/cli.py—gaia connectors activations {list|activate|deactivate}with--scopesfor explicit auto-grant overrides and--jsonfor machine-readable output. Same exit-code map as the rest ofgaia connectors(0/1/2/3/5).mcp_server.pydisconnect paths — re-adding a connector_id never silently inherits prior tool visibility.src/gaia/apps/webui/src/components/ConnectorsSection.tsx— new "Active for" subsection rendered only whenconnector.type === 'mcp_server'. NewAgentActivationCardmirrors the existing scope-grant card with a single toggle. Optimistic update + rollback on error. Live updates viauseConnectorsSSE.tests/unit/connectors/test_activations.py(file mode, atomicity, corruption, namespacing),test_activation_api.py(orchestration + rejection + cold-start regression),test_disconnect_clears_activations.py(wipe symmetry), router/CLI/E2E extensions, andtests/unit/agents/test_tool_visibility_filter.py(the canonical filter probe). Plustests/unit/chat/ui/test_chat_helpers.py::TestStampBuiltinChatIdentity— four tests including a source-grep structural guard.docs/sdk/infrastructure/connectors.mdx; revocation table updated indocs/security/connections.mdx. Both explicitly call out the MCP-only scope of activations.Why this matters
ChatAgentwith mcp-github granted + activated for it gets the 26 GitHub tools in its prompt; without activation, those 26 lines never enter the prompt. Small-model tool-call accuracy improves directly with prompt density reduction.mcp-githubto ChatAgent so the credential is available, but leave activation off so a routine "summarise this document" turn cannot reach amcp_github_create_pull_requesttool even if the model wanted to call it.(connector, agent)from Settings → Connectors → "Active for".TestActivationsMultiCallerSmokeproves it.Test plan
python util/lint.py --all— clean.python -m pytest tests/unit/connectors/ tests/unit/agents/test_tool_visibility_filter.py tests/unit/chat/ui/test_chat_helpers.py— 480 passed, 3 skipped.cd src/gaia/apps/webui && ./node_modules/.bin/tsc --noEmit— zero errors.gaia connectors activations activate google builtin:connectors-demo --scopes openid # exit 3; stderr: "Configuration error: Activations apply to MCP-server connectors only…"PUT /api/connectors/google/activations/builtin:chat→ 400; CSRF still wins (no header → 403); unknown connector → 404.mcp_github_*tools when activated, says "I don't have any GitHub MCP tools" when not.mcp-githubfor two agents and disconnecting via UI, both~/.gaia/connectors/grants.jsonand~/.gaia/connectors/activations.jsonare empty formcp-github.gaia eval agent --category rag_quality --agent-type doc) — 100% pass (7/7), avg score 9.4. The diff vs. the committed baseline reports +33%/+1.2 but the two scorecards share zero scenarios (baseline pre-dates the current scenario set), so the relevant signal is the absolute number — no regression introduced.Follow-ups (not in this PR — will file as separate issues)
connector.activation.changedonly fires from the HTTP router's PUT/DELETE handlers. CLI / SDK toggles write the same ledger but emit nothing, so an open Settings tab won't reflect CLI-driven state changes until the user navigates away/back. Two reasonable fixes: (a) have the CLI POST through the router instead of calling the SDK directly, or (b) add a file-watcher onactivations.jsonthat emits SSE on change.REQUIRED_CONNECTORS. The UI surfaces only agents that declare the connector in theirREQUIRED_CONNECTORSclass attribute. Formcp-githubthat's onlyConnectors Demo—Chat(builtin:chat) does not appear even though activations can be set for it via CLI/SDK and the runtime filter honours them. Worth widening the panel for MCP-consuming agents that load servers from~/.gaia/mcp_servers.json.tests/unit/test_file_tools.pyhangs. Running the full unit suite (pytest tests/unit/) hangs on this file. Pre-existing — not introduced by this PR — but worth a separate bug..env.exampleandLEMONADE_BASE_URL. Both this repo's and a sibling checkout's.env.examplestill pinLEMONADE_BASE_URL=http://localhost:8000/api/v1, the pre-v10.1 port. Anyone copying.env.example→.envagainst Lemonade v10.1+ gets a silent connection-refused that surfaces as "Lemonade server is not running" — actionable error wording would help, but updating.env.exampleto13305(or removing the line so the built-in default applies) is the cleanest fix.lemonade_manager.py:353logs that exact string whenhealth_checkraises, without naming the URL it tried. Includingstatus.url+status.errorwould have surfaced the wrong-port mismatch immediately.tests/fixtures/eval_baselines/gemma-4-e4b-d71cd914/scorecard_rag_quality.jsonwas captured against a now-removed scenario list. A refresh with--save-baselinewould make future deltas meaningful.CONTRIBUTING.mdis silent on fork workflow. Step 2 says "Branch offmain" without mentioning that external contributors need to fork first (only AMD maintainers have direct push access). A one-line clarification would help the next external contributor avoid the same "Permission to amd/gaia.git denied" surprise.Checklist
Closes #1005).python util/lint.py --all,pytest tests/unit/connectors/ …).docs/sdk/infrastructure/connectors.mdxanddocs/security/connections.mdxupdated.