Skip to content

feat(connections): OAuth PKCE for Google (#915, baseline for connectors framework) - #926

Merged
itomek merged 39 commits into
mainfrom
claude/gallant-wescoff-2e6e97
May 4, 2026
Merged

itomek merged 39 commits into
mainfrom
claude/gallant-wescoff-2e6e97

Conversation

@itomek

@itomek itomek commented Apr 30, 2026

Copy link
Copy Markdown
Collaborator

Closes #915 (when promoted from draft and merged).

Summary

Self-contained gaia.connections module — any GAIA caller (SDK, CLI, AgentUI) can drive the OAuth 2.0 PKCE flow for Google. Refresh tokens land in the OS keychain (macOS Keychain, Windows DPAPI, Linux SecretService); per-agent grants live in ~/.gaia/connections/grants.json; an agent can only get_access_token for scopes the user explicitly granted it.

This PR ships as draft because it is also the baseline commit for a larger Connectors framework (parent issue forthcoming) — the scope expanded after a meeting to make GAIA host many connectors with a Claude-style tile UI. The plan is at ~/.claude/plans/floating-discovering-gray.md. Keeping this PR draft so reviewers can pull the baseline (157 tests green) before the framework refactor renames gaia.connections → gaia.connectors and unifies the MCP catalog into the same surface.

Changes

  • src/gaia/connections/ — provider-agnostic core: errors, providers (Google), pkce, store (keyring with backend allowlist + tripwire), grants ledger, async token cache (double-checked locking, 60 s expiry buffer, refresh-token rotation), aiohttp loopback flow, events Protocol, public api, CLI.
  • src/gaia/agents/base/agent.py — REQUIRED_CONNECTIONS ClassVar; process_query wraps tool execution in a private _agent_context contextvar so every tool body knows its agent identity.
  • src/gaia/agents/registry.py — namespaced agent ids (builtin:* / custom:<sha256>:*); reserved-id check blocks custom agents from claiming a built-in's id.
  • src/gaia/ui/routers/connections.py — thin presentation layer: /api/connections/{catalog,configure,test,authorize,grants,events,_debug}. SSE event emitter with bounded queue. /_debug gated by GAIA_DEBUG=1.
  • src/gaia/cli.py + src/gaia/connections/cli.py — gaia connections {connect,status,disconnect,grants ...}.
  • src/gaia/apps/webui/src/components/ConnectionsSection.{tsx,css} + supporting store/hook/types — Settings → Connections panel with Connect/Disconnect + per-agent grant toggle. SSE updates the UI within ~2 s of OAuth completion.
  • docs/security/connections.mdx — threat model.
  • docs/sdk/infrastructure/connections.mdx — SDK reference with three equal-weight sections (SDK / CLI / agent author).
  • docs/runbooks/google-oauth-client.md — internal client-id rotation procedure.
  • docs/local-test/ — recipe + custom test agent for end-to-end Google OAuth verification against a personal account (gated until env var is set).

Why this matters

  • Refresh tokens never leave the OS keychain. Backend allowlist refuses PlaintextKeyring / EncryptedKeyring so a Linux user without SecretService gets an actionable error rather than silent plaintext storage.
  • Per-agent grants prevent prompt-injection-driven scope escalation: even a malicious tool body cannot get_access_token for a connector the user did not explicitly grant that agent.
  • client_id_hash tripwire invalidates stored tokens after an OAuth client rotation; users reconnect cleanly instead of using stale credentials.
  • Same primitives serve SDK, CLI, and AgentUI — proven by an explicit multi-caller equivalence integration test.

Test plan

  • python -m pytest tests/unit/connections/ tests/unit/test_agent_required_connections.py tests/integration/test_multi_caller_equivalence.py — 157 passing.
  • python -m black --check src/gaia/connections/ src/gaia/ui/routers/connections.py tests/unit/connections/ — clean.
  • python -m isort --check-only src/gaia/connections/ ... — clean.
  • cd src/gaia/apps/webui && npx tsc --noEmit — zero errors.
  • Local Google OAuth E2E against a personal account (deferred to after the connectors framework refactor, per docs/local-test/README.md).
  • Linux CI keyring matrix (in-memory backend autouse fixture covers the unit suite; gnome-keyring integration job is a follow-up).

Reviewer notes

  • The library is self-contained — every test runs without the AgentUI server and without a real keyring (in-memory backend in tests/unit/connections/conftest.py).
  • _agent_context is intentionally private (not re-exported in gaia.connections.__init__). A tool body cannot import it to forge an agent identity. Custom agents get an origin-hashed namespaced id so a custom agent declaring a built-in's AGENT_ID does not inherit prior grants.
  • Code-reviewer agent ran on the diff during development; 5 findings reported, 4 fixed (asyncio-run-in-running-loop guard on the sync wrapper, consent-denied response now serves the rejection page instead of the success page, connected_at populated from time.time() not from the absent token-response field, BuilderAgent / CodeAgent overrides updated so they cannot bypass the agent-context binding). The 5th was the v1 single-account-per-provider intentional limit — strengthened the docstring instead of changing behavior.

@github-actions github-actions Bot added documentation Documentation changes dependencies Dependency updates devops DevOps/infrastructure changes cli CLI changes tests Test changes electron Electron app changes agents labels Apr 30, 2026
Self-contained gaia.connections module: any GAIA caller (SDK, CLI, AgentUI)
can drive the OAuth 2.0 PKCE flow for Google with refresh tokens stored in
the OS keychain (macOS Keychain, Windows DPAPI, Linux SecretService) and
per-agent grants in ~/.gaia/connections/grants.json.

Layout:
- src/gaia/connections/ — provider-agnostic core (errors, providers,
  pkce, store with backend allowlist + tripwire, grants ledger, async
  token cache with double-checked locking, aiohttp loopback flow,
  events Protocol, public api, CLI).
- src/gaia/connections/providers/google.py — Google as the first concrete
  provider; reads GAIA_GOOGLE_CLIENT_ID at instantiation time.
- src/gaia/agents/base/agent.py — REQUIRED_CONNECTIONS ClassVar; the
  base process_query wraps the inner impl in a private agent_context
  contextvar so every tool body inside knows its agent identity.
- src/gaia/agents/registry.py — namespaced agent ids (builtin:* /
  custom:<sha256>:*); reserved-id check.
- src/gaia/ui/routers/connections.py — thin presentation layer over
  gaia.connections (catalog, configure, test, grants, SSE,
  /_debug gated by GAIA_DEBUG=1).
- src/gaia/cli.py — gaia connections {connect|status|disconnect|grants}.
- src/gaia/apps/webui/src/components/ConnectionsSection.tsx — Settings
  page with per-provider connect/disconnect + per-agent grant toggle;
  SSE hook updates UI within 2 s of OAuth completion.
- docs/security/connections.mdx, docs/sdk/infrastructure/connections.mdx,
  docs/runbooks/google-oauth-client.md — threat model, SDK reference,
  internal client-id rotation runbook.
- docs/local-test/ — recipe + custom test agent for end-to-end Google
  OAuth verification against a personal account.

157 tests passing (unit + integration multi-caller equivalence). Lint
clean (black, isort). Type-check clean (tsc --noEmit).

Refs #915.
@itomek
itomek force-pushed the claude/gallant-wescoff-2e6e97 branch from 255def4 to 39b31d3 Compare April 30, 2026 14:37
…eanly

The CI "Verify external URLs" job parses URLs inside markdown code spans.
When `--scopes <url>` is wrapped in a single backtick-pair, the trailing
backtick gets captured into the URL, producing a 404 on
`https://www.googleapis.com/auth/gmail.readonly\``.

Fix: keep `--scopes` and the URL in separate code spans so the URL stands
alone, matching the pattern used on lines 15–16 of the same file (which
already pass).
itomek added 10 commits April 30, 2026 13:28
Checked-in spec snapshot for the Connectors framework — the canonical
live tracking issue is #927; this document is a stable in-repo copy
for discoverability via the Mintlify Plans nav.

Mirrors the spec sections from the issue body (TL;DR, why-now, UX,
type taxonomy, module layout, public API, storage, endpoints, AgentUI
surfaces, MCP unification, out-of-scope, AC highlights) and adds a
condensed task sequence + risks/coordination block. Drops the
issue-body-only sections (Coordination row-by-row mapping, full AC
checklist, Migration / refactor of #915) — those stay on the issue
where the executor reads them.

Registered under docs.json → Plans → Agent UI, between security-model
and email-calendar-integration.

Refs #915 #927.
Module rename from #915's gaia.connections to gaia.connectors:
- git mv src/gaia/connections/ → src/gaia/connectors/
- git mv tests/unit/connections/ → tests/unit/connectors/
- git mv docs/sdk/infrastructure/connections.mdx → connectors.mdx
- Rewrite all import paths, symbol names (ConnectionsError → ConnectorsError,
  ConnectionRequirement → ConnectorRequirement, REQUIRED_CONNECTIONS → REQUIRED_CONNECTORS)
- Frontend: ConnectionsSection → ConnectorsSection, connectionsStore →
  connectorsStore, useConnectionsSSE → useConnectorsSSE
- CLI subcommand "connections" → "connectors"; APIRouter prefix /api/connectors
- Grants path ~/.gaia/connections/ → ~/.gaia/connectors/
- Keyring service name kept as "gaia.connections" per plan amendment A3

157 tests pass, tsc --noEmit clean.
Adds the typed connector manifest and id-unique registry (plan amendment A7):
- spec.py: frozen ConnectorSpec + ConfigField dataclasses for v1 types
  (oauth_pkce, mcp_server per amendment A1); validates id, type, tier, kind
- registry.py: thread-safe ConnectorRegistry; raises ValueError on duplicate
  id, RuntimeError after freeze(); REGISTRY module-level singleton
- providers/base.py: rename ConnectorRequirement.provider → .connector_id
  to match connector catalog key instead of OAuth provider id
- __init__.py: export ConfigField, ConnectorSpec, ConnectorRegistry, REGISTRY
- 28 new unit tests; 185 total, all passing
- state.py: new atomic state.json store (tempfile+os.replace, 0o600/0o700
  mode, load_state/set_connector_state/get_connector_state/clear/list_configured_ids)
  — cheap catalog status without keyring round-trips (plan amendment A12)
- grants.py: rename provider → connector_id in all function signatures and
  log messages; update schema doc comment (no migration shim per amendment A2)
- __init__.py: export state store functions
- 19 new unit tests; 204 total, all passing
…spatcher

- handler.py: structural ConnectorHandler Protocol (duck-typed, not ABC);
  register_handler() + _HANDLER_REGISTRY keyed by ConnectorType;
  get_credential dispatcher (REGISTRY lookup → grant check → handler call);
  configure / disconnect / health_check dispatcher stubs;
  get_credential_sync with running-loop guard
- 13 new unit tests covering Protocol conformance, grant blocking,
  no-handler error, all dispatch paths; 217 total passing
Wraps the existing PKCE flow (flow.py/tokens.py/store.py) under the
ConnectorHandler Protocol, completing the handler layer for oauth_pkce
connectors. Introduces the catalog package with the first built-in
entry: the Google connector spec (openid/email/profile + full workspace
scopes). 17 unit tests cover get_credential, configure (start and
complete paths), disconnect, health check, and catalog registration.
Introduces the mcp_server connector type handler and a 22-entry built-in
catalog that supersedes the read-only catalog in ui/routers/mcp.py.
Secret env vars are stored in the OS keyring under $keyring references;
mcp_servers.json holds only the references, never plaintext secrets
(plan amendment A4). MCPClient.from_config() resolves $keyring refs at
spawn time and refuses to start if any reference is dangling (A5b).
MCPClientManager.reload() hot-reloads servers after configure/disconnect
without restarting GAIA (A5). MCPConfig write methods emit
DeprecationWarning — the connectors framework is now the sole writer (A6).
Rewrites /api/connectors/* as a thin presentation layer over the
gaia.connectors dispatcher. All mutating routes require X-Gaia-UI: 1
(plan amendment A8). Backfills the same CSRF guard on /api/mcp/servers
mutating routes.

- connectors.py: catalog list/get, configure, test, disconnect, authorize,
  grants PUT/DELETE, SSE event stream, /_debug diagnostics
- mcp.py: CSRF guard on POST/DELETE/enable/disable
- test_router.py: updated to new response shapes and CSRF-aware
- test_router_connectors.py: 17 new framework-level router tests
…onnect)

Updates the connectors CLI to cover the full framework:
- list/status: shows all catalog entries with configured/not status (replaces
  OAuth-only list_connections)
- configure: delegates to the handler dispatcher via KEY=VALUE or --json
- test: runs health_check and prints OK/FAIL with detail
- disconnect: calls the handler dispatcher (replaces revoke_connection)
- connect: keeps OAuth PKCE browser flow
- grants: unchanged

Updates test_cli.py TestStatus to match new catalog-based list output.
…E smoke

Settings panel is now a full-page view inside the main content area
(plan amendment A16) rather than a modal overlay.  ConnectorsSection
is rewritten with a tile grid + in-place expandable detail view for
both OAuth PKCE and MCP server connector types.

- SettingsModal.tsx deleted (dead code — no longer imported)
- SettingsPage.tsx: full-page layout with ArrowLeft back button
- ConnectorsSection.tsx: ConnectorTile grid, OAuthConfigureBody,
  MCPServerConfigureBody, ConnectorAgentGrants; uses /api/connectors
  endpoints with CSRF header; OAuthConfigureBody refreshes tile on
  window focus after OAuth redirect
- api.ts: listConnectors, authorizeConnector, configureConnector,
  testConnector, disconnectConnector, listConnectorGrants,
  grantConnectorAgent, revokeConnectorAgentGrant; apiFetch gains
  extraHeaders param with Content-Type always winning for body reqs
- types/index.ts: ConnectorRow interface
- docs/sdk/infrastructure/connectors.mdx: updated for catalog-based
  framework (OAuth + MCP), CLI examples, agent-author guide
- tests/unit/connectors/test_e2e_smoke.py: 12 E2E smoke tests covering
  CLI→state→router vertical slice
@github-actions github-actions Bot added the mcp MCP integration changes label Apr 30, 2026
Comment thread src/gaia/connectors/flow.py Fixed
Comment thread src/gaia/connectors/handler.py Fixed
Comment thread src/gaia/connectors/oauth_pkce.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
@itomek
itomek requested a review from kovtcharov-amd as a code owner May 4, 2026 15:44
Comment thread src/gaia/connectors/handler.py Fixed
Comment thread src/gaia/connectors/store.py Fixed
Comment thread src/gaia/ui/routers/connectors.py Fixed
Comment thread src/gaia/ui/routers/connectors.py Fixed
@itomek

itomek commented May 4, 2026

Copy link
Copy Markdown
Collaborator Author

CodeQL + CI resolution summary

All outstanding alerts and review threads addressed in the latest commits:

Clear-text logging (py/clear-text-logging-sensitive-data)

  • flow.py, handler.py, oauth_pkce.py: Moved # lgtm annotations from the logger.xxx( opening line to the flagged argument line (CodeQL flags the argument expression, not the function call).
  • store.py: Removed the two logger calls entirely (load_connection tripwire warning and delete_connection debug). The raised AuthRequiredError already communicates the tripwire event; the debug log added no operational value.
  • All prior save_connection and load_connection alert threads: the save_connection debug log was removed in an earlier commit; the remaining alerts reference code that no longer exists at those line numbers and will auto-resolve.

Information exposure through exception (py/information-exposure-through-an-exception)

  • connectors.py router: Replaced logger.exception() with logger.warning(type(exc).__name__) in both list_connectors and get_connector. logger.exception propagates the full traceback — the replacement logs only the exception type, which carries no sensitive information and doesn't trigger CodeQL's data-flow model.

Weak cryptographic algorithm (py/weak-cryptographic-algorithm)

  • google.py: Moved # lgtm[py/weak-cryptographic-algorithm] from the .hexdigest() line to the hashlib.sha256( line where CodeQL flags the call. The SHA-256 here is non-cryptographic fingerprinting, not password hashing — false positive confirmed.

Merge conflict

  • Resolved conflict in agent.py (ConnectorRequirement import vs DEFAULT_MODEL_NAME re-introduction from main) in merge commit d937c63.

Doc links

  • Created missing docs/security/connections.mdx
  • Fixed broken internal link /sdk/sdks/connectors → /sdk/infrastructure/connectors
  • Fixed 404 external URLs in github.mdx and google.mdx

48 connector unit tests pass (uv run pytest tests/unit/connectors/test_store.py tests/unit/connectors/test_handler.py tests/unit/connectors/test_flow.py).

Comment thread src/gaia/connectors/flow.py Fixed
Comment thread src/gaia/connectors/handler.py Fixed
Comment thread src/gaia/connectors/oauth_pkce.py Fixed
itomek added 4 commits May 4, 2026 12:16
… failures

- Make gaia.connectors.__init__ defer the api→flow→store→keyring import
  chain via module-level __getattr__; keyring is only loaded on first
  access of an API function, not at package-import time
- Remove trivial try/except-raise blocks in tokens.py and api.py (W0706)
- Fix implicit string concatenation in cli.py (W1404)
- Add pylint: disable=unused-import to all side-effect catalog imports in
  cli.py and catalog/mcp_servers.py (W0611)
- Remove ConfigurationError from tokens.py imports (no longer used after
  removing the try/except-raise wrapping get_provider call)
…int-tracked args from log calls

- handler.py: log type(handler).__name__ instead of repr(handler) to avoid
  py/clear-text-logging-sensitive-data on the handler object
- flow.py: remove provider_id from logger.info (only scopes + flow_id logged)
- oauth_pkce.py: remove provider_id from disconnect log (connector_id sufficient)
- google.py: move lgtm annotation to resolved_id.encode() line (the exact line
  CodeQL flags for py/weak-cryptographic-algorithm)
itomek added 2 commits May 4, 2026 12:53
CRC32 is non-cryptographic, making the intent explicit and eliminating
the CodeQL py/weak-cryptographic-algorithm false positive that # lgtm
annotations were not suppressing.
Replace str(ConfigurationError) flowing into HTTP responses with a
formatted string derived from the provider ref. Full error details are
logged server-side. Eliminates CodeQL py/information-exposure-through-an-exception
medium alerts at connectors.py:326 and :401.
Comment thread src/gaia/ui/routers/connectors.py Dismissed
@itomek
itomek added this pull request to the merge queue May 4, 2026
Merged via the queue into main with commit b9166b4 May 4, 2026
43 of 44 checks passed
@itomek
itomek deleted the claude/gallant-wescoff-2e6e97 branch May 4, 2026 17:21
theonlychant pushed a commit to theonlychant/gaia that referenced this pull request May 5, 2026
…ctors framework) (amd#926)

Closes amd#915 (when promoted from draft and merged).

Self-contained `gaia.connections` module — any GAIA caller (SDK, CLI,
AgentUI) can drive the OAuth 2.0 PKCE flow for Google. Refresh tokens
land in the OS keychain (macOS Keychain, Windows DPAPI, Linux
SecretService); per-agent grants live in
`~/.gaia/connections/grants.json`; an agent can only `get_access_token`
for scopes the user explicitly granted it.

This PR ships as **draft** because it is also the **baseline commit for
a larger Connectors framework** (parent issue forthcoming) — the scope
expanded after a meeting to make GAIA host many connectors with a
Claude-style tile UI. The plan is at
`~/.claude/plans/floating-discovering-gray.md`. Keeping this PR draft so
reviewers can pull the baseline (157 tests green) before the framework
refactor renames `gaia.connections` → `gaia.connectors` and unifies the
MCP catalog into the same surface.

- **`src/gaia/connections/`** — provider-agnostic core: errors,
providers (Google), pkce, store (keyring with backend allowlist +
tripwire), grants ledger, async token cache (double-checked locking, 60
s expiry buffer, refresh-token rotation), aiohttp loopback flow, events
Protocol, public api, CLI.
- **`src/gaia/agents/base/agent.py`** — `REQUIRED_CONNECTIONS` ClassVar;
`process_query` wraps tool execution in a private `_agent_context`
contextvar so every tool body knows its agent identity.
- **`src/gaia/agents/registry.py`** — namespaced agent ids (`builtin:*`
/ `custom:<sha256>:*`); reserved-id check blocks custom agents from
claiming a built-in's id.
- **`src/gaia/ui/routers/connections.py`** — thin presentation layer:
`/api/connections/{catalog,configure,test,authorize,grants,events,_debug}`.
SSE event emitter with bounded queue. `/_debug` gated by `GAIA_DEBUG=1`.
- **`src/gaia/cli.py`** + **`src/gaia/connections/cli.py`** — `gaia
connections {connect,status,disconnect,grants ...}`.
- **`src/gaia/apps/webui/src/components/ConnectionsSection.{tsx,css}`**
+ supporting store/hook/types — Settings → Connections panel with
Connect/Disconnect + per-agent grant toggle. SSE updates the UI within
~2 s of OAuth completion.
- **`docs/security/connections.mdx`** — threat model.
- **`docs/sdk/infrastructure/connections.mdx`** — SDK reference with
three equal-weight sections (SDK / CLI / agent author).
- **`docs/runbooks/google-oauth-client.md`** — internal client-id
rotation procedure.
- **`docs/local-test/`** — recipe + custom test agent for end-to-end
Google OAuth verification against a personal account (gated until env
var is set).

- Refresh tokens never leave the OS keychain. Backend allowlist refuses
`PlaintextKeyring` / `EncryptedKeyring` so a Linux user without
SecretService gets an actionable error rather than silent plaintext
storage.
- Per-agent grants prevent prompt-injection-driven scope escalation:
even a malicious tool body cannot `get_access_token` for a connector the
user did not explicitly grant *that* agent.
- `client_id_hash` tripwire invalidates stored tokens after an OAuth
client rotation; users reconnect cleanly instead of using stale
credentials.
- Same primitives serve SDK, CLI, and AgentUI — proven by an explicit
multi-caller equivalence integration test.

- [x] `python -m pytest tests/unit/connections/
tests/unit/test_agent_required_connections.py
tests/integration/test_multi_caller_equivalence.py` — 157 passing.
- [x] `python -m black --check src/gaia/connections/
src/gaia/ui/routers/connections.py tests/unit/connections/` — clean.
- [x] `python -m isort --check-only src/gaia/connections/ ...` — clean.
- [x] `cd src/gaia/apps/webui && npx tsc --noEmit` — zero errors.
- [ ] Local Google OAuth E2E against a personal account (deferred to
after the connectors framework refactor, per
`docs/local-test/README.md`).
- [ ] Linux CI keyring matrix (in-memory backend autouse fixture covers
the unit suite; `gnome-keyring` integration job is a follow-up).

- The library is self-contained — every test runs without the AgentUI
server and without a real keyring (in-memory backend in
`tests/unit/connections/conftest.py`).
- `_agent_context` is intentionally **private** (not re-exported in
`gaia.connections.__init__`). A tool body cannot import it to forge an
agent identity. Custom agents get an origin-hashed namespaced id so a
custom agent declaring a built-in's `AGENT_ID` does not inherit prior
grants.
- Code-reviewer agent ran on the diff during development; 5 findings
reported, 4 fixed (asyncio-run-in-running-loop guard on the sync
wrapper, consent-denied response now serves the rejection page instead
of the success page, `connected_at` populated from `time.time()` not
from the absent token-response field, BuilderAgent / CodeAgent overrides
updated so they cannot bypass the agent-context binding). The 5th was
the v1 single-account-per-provider intentional limit — strengthened the
docstring instead of changing behavior.
@itomek itomek mentioned this pull request May 7, 2026
5 of 6 tasks
theonlychant pushed a commit to theonlychant/gaia that referenced this pull request May 7, 2026
## Why this matters

Ships the v0.17.6 patch: a new Email Triage Agent with Gmail (every
email body stays on local Lemonade), the OAuth PKCE foundation that
backs it, settings UI card layout, and a sweep of installer fixes that
close the remaining first-launch failures uncovered after v0.17.5.
Custom Python agents that follow the template's
`super().__init__(**kwargs)` pattern no longer crash on the first
message in the Agent UI.

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

## What's New

- **Email Triage Agent with Gmail**
([amd#965](amd#965)) — `EmailTriageAgent` with
25 tools across read / organize / reply / delete / calendar mixins.
Every email body processed locally on Lemonade; seven destructive tools
confirmation-gated; three layers of prompt-injection defense; SQLite
undo log via `DatabaseMixin`.
- **OAuth PKCE foundation for Google connections**
([amd#926](amd#926)) — Self-contained
`gaia.connections` module: refresh tokens in the OS keychain (Keychain /
DPAPI / SecretService), per-agent grants in
`~/.gaia/connections/grants.json`, async token cache with refresh
rotation. Baseline for the v0.17.7 connectors framework.
- **Settings UI card layout**
([amd#969](amd#969)) — Outlined cards with
accent left-stripe replace margin-separated blocks across all settings
sections; light + dark themes both updated.

## Bug Fixes

- **Custom Python agents crashed on first message**
([amd#974](amd#974), closes
[amd#973](amd#973)) — `python_factory` now
introspects the target class's `__init__` chain and only forwards kwargs
the chain accepts, so the bare `super().__init__(**kwargs)` template
pattern no longer crashes with `unexpected keyword argument
'rag_documents'`.
- **Windows installer failed at `ensure-uv`**
([amd#968](amd#968), closes
[amd#966](amd#966)) — `uv` binary now
bundled for `win-x64`; packaged Windows rescue installer included.
- **macOS installer failed at `ensure-uv` on clean Apple Silicon**
([amd#967](amd#967), closes
[amd#941](amd#941)) — Pinned `uv` v0.5.14
(`aarch64-apple-darwin`) shipped in the DMG; new `dmg-structural-smoke`
CI job blocks future drift.
- **AppImage users hit `gaia: command not found`**
([amd#942](amd#942), closes
[amd#782](amd#782)) — Startup writes a
`~/.local/bin/gaia` shim so `gaia` is on PATH after first launch (skips
creation if already present).
- **Windows fell back to Qwen instead of Gemma 4 default**
([amd#949](amd#949), closes
[amd#948](amd#948)) — Model-resolution logic
fixed so Gemma loads correctly on Windows.

## Tooling & Docs

- **`gaia-release` skill**
([amd#939](amd#939)) — Phased release flow
with hard gates before every irreversible step; encodes the manual
pre-tag verification that caught two release-blocking bugs in v0.17.4.
- **Internal-task issue template**
([amd#906](amd#906)) — Third issue template
for agent-assignable internal work.
- **Outlook via Power Automate plan**
([amd#954](amd#954)) — Enterprise-bypass spec
for v0.17.7 Outlook integration.
- **PR description guidance sharpened**
([amd#947](amd#947)) — `CLAUDE.md` "tight and
value-focused" rule with anti-patterns.
- **Stale `macOS uv fetch removed` orphan comment removed**
([amd#975](amd#975)).

## Thanks

External contributors in this release:

- [@theonlychant](https://github.com/theonlychant) — installer fixes
([amd#968](amd#968),
[amd#942](amd#942),
[amd#949](amd#949))
- [@BlueriteSoul](https://github.com/BlueriteSoul) — reported AppImage
`gaia: command not found`
([amd#782](amd#782))
- [@nuts23](https://github.com/nuts23) — reported Windows Gemma/Qwen
fallback ([amd#948](amd#948))

## Release checklist

- [x] `util/validate_release_notes.py docs/releases/v0.17.6.mdx --tag
v0.17.6` passes
- [x] `src/gaia/version.py` → `0.17.6`
- [x] `src/gaia/apps/webui/package.json` → `0.17.6`
- [x] Navbar label in `docs/docs.json` → `v0.17.6 · Lemonade 10.2.0`
- [x] All 14 commits in the range (v0.17.5..HEAD) are represented in the
notes
- [ ] Review from @kovtcharov-amd addressed
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request May 28, 2026
amd#1219)

<!--
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

Per-agent MCP tool-visibility activations, layered on top of the PR amd#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 `ChatAgent` with several MCP servers granted sees ~30
extra tool descriptions in its system prompt — bloating context and
degrading small-model tool selection. Issue amd#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 `@tool` functions
that call `get_credential_sync` directly — 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 amd#926. Calling `activate()` /
`deactivate()` for an OAuth connector is rejected at every boundary
(HTTP 400, SDK `ConfigurationError`, CLI exit 3); the UI hides the
"Active for" section on OAuth tiles for the same reason.

## Linked issue

Closes amd#1005

## Changes

- **New module `src/gaia/connectors/activations.py`** — ledger at
`~/.gaia/connectors/activations.json`, mode 0600, atomic-replace writes,
per-process write lock, corruption recovery with actionable `rm` hint.
Mirrors `grants.py` one-to-one in structure and rigour. Low-level API
named `activate_agent` / `deactivate_agent` / `is_agent_active` /
`list_agent_activations` / `revoke_all_activations_for` — matches the
`grants.py` naming pattern (`grant_agent`, `revoke_agent_grant`).
- **Schema includes a `version` field** so future evolution has a
forward-compat lever from day one:
  ```json
  {
    "version": 1,
    "activations": {
      "<connector_id>": {
        "<namespaced_agent_id>": true
      }
    }
  }
  ```
Issue amd#1005 sketched `[agent_id]`-list values; this PR ships the object
form so per-pair lookups are O(1) and a future `false` value can carry
meaning if needed.
- **`src/gaia/connectors/api.py`** — public orchestration helpers
`activate` / `deactivate`. `activate` auto-grants using the agent's
declared `REQUIRED_CONNECTORS` scopes 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`** — new
`tools_for_agent(agent_id)` and `servers_for_agent(agent_id)`. Pure
filter over the existing per-server tool catalogue. With `agent_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_id` plus an early-init stamp so
`_register_tools` sees the correct identity. Necessary because the
registry wrapper used to stamp `_gaia_namespaced_agent_id` *after*
`__init__` returned — meaning the filter never actually fired for any UI
Chat session. The wrapper now also injects via kwarg, and
`_chat_helpers` stamps the config before each direct construction.
Source-grep guard test catches any future direct `ChatAgent(config)`
site that forgets the stamp.
- **HTTP routes** in `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 an `activations: Dict[str, bool]`
field.
- **CLI** in `src/gaia/connectors/cli.py` — `gaia connectors activations
{list|activate|deactivate}` with `--scopes` for explicit auto-grant
overrides and `--json` for machine-readable output. Same exit-code map
as the rest of `gaia connectors` (0/1/2/3/5).
- **Disconnect wipes activations** alongside grants in `mcp_server.py`
disconnect paths — re-adding a connector_id never silently inherits
prior tool visibility.
- **Frontend**
`src/gaia/apps/webui/src/components/ConnectorsSection.tsx` — new "Active
for" subsection rendered only when `connector.type === 'mcp_server'`.
New `AgentActivationCard` mirrors the existing scope-grant card with a
single toggle. Optimistic update + rollback on error. Live updates via
`useConnectorsSSE`.
- **Tests (24 new + several migrated)** —
`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, and `tests/unit/agents/test_tool_visibility_filter.py` (the
canonical filter probe). Plus
`tests/unit/chat/ui/test_chat_helpers.py::TestStampBuiltinChatIdentity`
— four tests including a source-grep structural guard.
- **Docs** — new "Per-agent activation" section in
`docs/sdk/infrastructure/connectors.mdx`; revocation table updated in
`docs/security/connections.mdx`. Both explicitly call out the MCP-only
scope of activations.

## Why this matters

- **Smaller prompts, better tool selection.** A `ChatAgent` with
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.
- **Real least-privilege.** A user can grant `mcp-github` to ChatAgent
so the credential is available, but leave activation off so a routine
"summarise this document" turn cannot reach a
`mcp_github_create_pull_request` tool even if the model wanted to call
it.
- **Activations default OFF.** Migration story is the strictest reading
of the issue: no implicit "everything granted is now active" on upgrade.
Users opt in per `(connector, agent)` from Settings → Connectors →
"Active for".
- **Multi-caller equivalence preserved.** Whatever rigour PR amd#926 set
for grants (SDK / CLI / HTTP all see the same ledger, atomic writes,
mode 0600), this PR mirrors for activations. New
`TestActivationsMultiCallerSmoke` proves it.

## Test plan

- [x] `python util/lint.py --all` — clean.
- [x] `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.
- [x] `cd src/gaia/apps/webui && ./node_modules/.bin/tsc --noEmit` —
zero errors.
- [x] Manual CLI round-trip:
  ```bash
gaia connectors activations deactivate mcp-github builtin:chat # clean
up
gaia connectors grants revoke mcp-github builtin:chat # clean up
gaia connectors activations list mcp-github # empty
gaia connectors activations activate mcp-github builtin:chat --scopes
use # auto-grants
gaia connectors activations list mcp-github # builtin:chat: active
  gaia connectors activations deactivate mcp-github builtin:chat
gaia connectors activations list mcp-github # inactive; grant survives
  ```
- [x] OAuth rejection:
  ```bash
gaia connectors activations activate google builtin:connectors-demo
--scopes openid
# exit 3; stderr: "Configuration error: Activations apply to MCP-server
connectors only…"
  ```
- [x] HTTP rejection: `PUT
/api/connectors/google/activations/builtin:chat` → 400; CSRF still wins
(no header → 403); unknown connector → 404.
- [x] End-to-end LLM-visible effect: with Lemonade +
Gemma-4-E4B-it-GGUF, ChatAgent in the UI lists `mcp_github_*` tools when
activated, says "I don't have any GitHub MCP tools" when not.
- [x] Disconnect-wipe: after granting + activating `mcp-github` for two
agents and disconnecting via UI, both `~/.gaia/connectors/grants.json`
and `~/.gaia/connectors/activations.json` are empty for `mcp-github`.
- [x] Agent eval (`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)

- **SSE gap for non-router writes.** `connector.activation.changed` only
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 on
`activations.json` that emits SSE on change.
- **"Active for" panel filters by `REQUIRED_CONNECTORS`.** The UI
surfaces only agents that declare the connector in their
`REQUIRED_CONNECTORS` class attribute. For `mcp-github` that's only
`Connectors 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.py` hangs.** Running the full unit suite
(`pytest tests/unit/`) hangs on this file. Pre-existing — not introduced
by this PR — but worth a separate bug.
- **Stale `.env.example` and `LEMONADE_BASE_URL`.** Both this repo's and
a sibling checkout's `.env.example` still pin
`LEMONADE_BASE_URL=http://localhost:8000/api/v1`, the pre-v10.1 port.
Anyone copying `.env.example` → `.env` against Lemonade v10.1+ gets a
silent connection-refused that surfaces as "Lemonade server is not
running" — actionable error wording would help, but updating
`.env.example` to `13305` (or removing the line so the built-in default
applies) is the cleanest fix.
- **Misleading "Lemonade server is not running" warning.**
`lemonade_manager.py:353` logs that exact string when `health_check`
raises, without naming the URL it tried. Including `status.url` +
`status.error` would have surfaced the wrong-port mismatch immediately.
- **Stale eval baseline.**
`tests/fixtures/eval_baselines/gemma-4-e4b-d71cd914/scorecard_rag_quality.json`
was captured against a now-removed scenario list. A refresh with
`--save-baseline` would make future deltas meaningful.
- **`CONTRIBUTING.md` is silent on fork workflow.** Step 2 says "Branch
off `main`" 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

- [x] I have linked a GitHub issue above (`Closes amd#1005`).
- [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/connectors/ …`).
- [x] I have updated documentation if user-visible behavior changed —
`docs/sdk/infrastructure/connectors.mdx` and
`docs/security/connections.mdx` updated.

---------

Co-authored-by: Alexey Tyurin <>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents cli CLI changes dependencies Dependency updates devops DevOps/infrastructure changes documentation Documentation changes electron Electron app changes mcp MCP integration changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Google account connection for AgentUI (OAuth via PKCE)

4 participants