diff --git a/README.md b/README.md index cda7995..87138bd 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,9 @@ nix fmt # format (nixfmt, nufmt, biome) `nh os switch` rebuilds and switches for the current host and assumes the repository at `~/dotfiles`. `nixos-rebuild switch` targets an explicit host. `nix build` produces the `wakuna` image. `nix fmt` formats the repository. -The MCP servers and skills under `modules/agents` are not only for the hosts here: `.#albedo-config` renders them into `/etc/albedo` (`extensions.json` plus the shared skills) and `.#albedo-seed` installs that tree into a home, merging into what albedo already wrote. An install without home-manager — the albedo image built in the infra repository — carries both and runs the seed before the daemon starts. +The MCP servers under `modules/agents` are declared once, in home-manager's `programs.mcp.servers` shape (`modules/agents/servers.nix`). `programs.mcp` writes them for other clients, opencode imports them with `enableMcpIntegration`, and albedo imports them through its own home-manager module, which merges them into `$ALBEDO_HOME/extensions.json` on activation. + +They are not only for the hosts here: `.#albedo-config` renders the same set into `/etc/albedo` (`extensions.json` plus the shared skills) and `.#albedo-seed` installs that tree into a home, merging into what albedo already wrote. An install without home-manager — the albedo image built in the infra repository — carries both and runs the seed before the daemon starts. ## Repository structure diff --git a/flake.lock b/flake.lock index 5d530ea..a74b963 100644 --- a/flake.lock +++ b/flake.lock @@ -12,11 +12,11 @@ "usage-core": "usage-core" }, "locked": { - "lastModified": 1794249520, - "narHash": "sha256-rHoCC1QBHF9oIQGKSE+DoSgC5epFjI5J6YZVBSUybdA=", + "lastModified": 1794305089, + "narHash": "sha256-0K0ZmH9WFkB7casbAQblFcb2UOlS4NRSaPrssWxv3tg=", "ref": "refs/heads/main", - "rev": "7577f15d7fd19b4996cc0d8f0374c97531d8f208", - "revCount": 1809, + "rev": "edd41aaee630cc73c0d049409a7ede4af9df62b9", + "revCount": 1824, "type": "git", "url": "https://tangled.org/karitham.dev/albedo" }, diff --git a/modules/agents/albedo-config.nix b/modules/agents/albedo-config.nix index c83c306..3777253 100644 --- a/modules/agents/albedo-config.nix +++ b/modules/agents/albedo-config.nix @@ -1,6 +1,6 @@ -# What albedo needs where home-manager does not run: the MCP servers every -# agent shares rendered into its extensions.json, the shared skills, and the -# script that installs both into a home. The flake exposes the pair as +# What albedo needs where home-manager does not run: the MCP servers every agent +# shares (./servers.nix) rendered into its extensions.json, the shared skills, and +# the script that installs both into a home. The flake exposes the pair as # .#albedo-config and .#albedo-seed; the image built in the infra repo carries # them and seeds its home volume before the daemon starts. { @@ -13,21 +13,15 @@ without ? [ ], }: let - # The same declarations, and the same defaults, the desktops evaluate - # through home-manager: the module needs neither, so it evaluates here too. - cfg = - (lib.evalModules { - modules = [ ./mcp-servers.nix ]; - specialArgs = { inherit self'; }; - }).config.dev.agents; - render = import ./lib.nix { inherit lib; }; + servers = removeAttrs (import ./servers.nix { inherit lib pkgs self'; }) without; + skills = import ./agent-skills.nix { inherit pkgs; }; fragment = pkgs.writeText "albedo-extensions.json" ( builtins.toJSON { - servers = lib.mapAttrs (_: render.toAlbedo) (removeAttrs cfg.mcpServers without); + servers = lib.mapAttrs (_: render.toAlbedo) servers; enabled.mcp = true; } ); diff --git a/modules/agents/albedo-exa-key.sh b/modules/agents/albedo-exa-key.sh new file mode 100644 index 0000000..f601782 --- /dev/null +++ b/modules/agents/albedo-exa-key.sh @@ -0,0 +1,39 @@ +# albedo_exa_key CREDS [RUNNER] +# +# Store the key in $EXA_API_KEY as albedo's `exa.apiKey` in CREDS, doing nothing +# when it is already there. Exa reads its key from creds.json and has no +# environment fallback, while every other section of that file belongs to +# albedo, so an unchanged key must not rewrite it under a running daemon. +# +# RUNNER optionally names a function to run the final move through, so the image +# seed can print its commands instead of applying them. +albedo_exa_key() { + albedo_exa_creds="$1" + albedo_exa_runner="${2:-}" + + [ -n "${EXA_API_KEY:-}" ] || return 0 + + albedo_exa_saved="$(jq -r '.exa.apiKey // ""' "$albedo_exa_creds" 2>/dev/null || true)" + [ "$albedo_exa_saved" = "$EXA_API_KEY" ] && return 0 + + albedo_exa_work="$(mktemp -d)" + if [ -r "$albedo_exa_creds" ]; then + cp "$albedo_exa_creds" "$albedo_exa_work/creds.json" + else + printf '{}\n' > "$albedo_exa_work/creds.json" + fi + + jq --arg key "$EXA_API_KEY" '.exa.apiKey = $key' "$albedo_exa_work/creds.json" > "$albedo_exa_work/next.json" + chmod 600 "$albedo_exa_work/next.json" + + # The status survives the cleanup: a move that fails must not look like a key + # that was written, and activation has nothing else to notice it by. + if [ -n "$albedo_exa_runner" ]; then + "$albedo_exa_runner" mv -f "$albedo_exa_work/next.json" "$albedo_exa_creds" || albedo_exa_status=$? + else + mv -f "$albedo_exa_work/next.json" "$albedo_exa_creds" || albedo_exa_status=$? + fi + + rm -rf "$albedo_exa_work" + return "${albedo_exa_status:-0}" +} diff --git a/modules/agents/albedo-merge.jq b/modules/agents/albedo-merge.jq deleted file mode 100644 index 09e1bc6..0000000 --- a/modules/agents/albedo-merge.jq +++ /dev/null @@ -1,22 +0,0 @@ -# Merge the extensions.json fragment this flake builds into the extensions.json -# albedo owns. A server the fragment carries is added or kept current, one it -# carried last time but no longer does was deleted in the flake and goes too, -# and every other server, toggle and setting stays as albedo wrote it. -# -# Inputs: --slurpfile f , --argjson before . -def resolve: - walk(if type == "string" and startswith("@env:") - then (.[5:] as $name | (env[$name] // .)) - else . end); -def unresolved: [.. | strings | select(startswith("@env:"))] | length > 0; - -($f[0] | resolve) as $frag -| ($frag.servers | with_entries(select(.value | unresolved | not))) as $servers -| ($servers | keys) as $owned -| ($before - $owned) as $gone -| .mcp = (.mcp // {}) -| .mcp.servers = ( - ((.mcp.servers // {}) | with_entries(select(.key as $name | ($gone | index($name)) | not))) - * $servers - ) -| .enabled = ((.enabled // {}) * ($frag.enabled // {})) diff --git a/modules/agents/albedo-seed.nix b/modules/agents/albedo-seed.nix index b6e8c80..c8659dc 100644 --- a/modules/agents/albedo-seed.nix +++ b/modules/agents/albedo-seed.nix @@ -1,8 +1,8 @@ # Installs the albedo configuration this flake builds into a home: the MCP # servers, the shared skills, and the Exa key when the environment carries one. -# Home-manager runs it on activation; an image with no home-manager runs it -# before the daemon starts (./albedo-config.nix), so both install the same -# things the same way. +# An image with no home-manager runs it before the daemon starts +# (./albedo-config.nix); a home home-manager manages needs none of it, because +# its module (./albedo.nix) merges the same servers on activation. { lib, pkgs, @@ -61,53 +61,34 @@ pkgs.writeShellApplication { trap 'rm -rf "$work"' EXIT target="$home/.albedo/extensions.json" - state="$home/.albedo/nix-mcp.json" creds="$home/.albedo/creds.json" run install -d -m 700 "$home/.albedo" - # A server the fragment carried last time but does not carry now was - # deleted in the flake, so the entry it left behind goes too. - before='[]' - if [ -r "$state" ]; then - before="$(jq -c '.servers // []' "$state" 2>/dev/null || printf '[]')" - fi - if [ -r "$target" ]; then cp "$target" "$work/extensions.json" else printf '{}\n' > "$work/extensions.json" fi - jq --slurpfile f "$fragment" --argjson before "$before" \ - -f ${./albedo-merge.jq} "$work/extensions.json" > "$work/merged.json" + # The declared servers and toggles win, and everything else albedo wrote — + # the servers it added itself, a server switched off in /mcp, its settings — + # stays. A server dropped from the flake keeps its entry, exactly as it does + # on a host home-manager merges for. + jq --slurpfile f "$fragment" \ + '.mcp.servers = ((.mcp.servers // {}) * ($f[0].servers // {})) + | .enabled = ((.enabled // {}) * ($f[0].enabled // {}))' \ + "$work/extensions.json" > "$work/merged.json" chmod 600 "$work/merged.json" - # A server whose @env: reference does not resolve here is left out, so the - # summary comes from what the merge produced, not from the fragment. - installed="$(jq -r '.mcp.servers | keys | join(", ")' "$work/merged.json")" + installed="$(jq -r '(.mcp.servers // {}) | keys | join(", ")' "$work/merged.json")" run mv -f "$work/merged.json" "$target" - jq -c -n --slurpfile f "$fragment" '{ servers: ($f[0].servers | keys) }' > "$work/nix-mcp.json" - chmod 600 "$work/nix-mcp.json" - run mv -f "$work/nix-mcp.json" "$state" - - # Exa reads its key from creds.json rather than from the environment, so - # one in this environment is copied in. Only a changed key rewrites the - # file: every other section belongs to albedo, and rewriting an identical - # one would race its own writes. - if [ -n "''${EXA_API_KEY:-}" ]; then - saved="$(jq -r '.exa.apiKey // ""' "$creds" 2>/dev/null || true)" - if [ "$saved" != "$EXA_API_KEY" ]; then - if [ -r "$creds" ]; then - cp "$creds" "$work/creds.json" - else - printf '{}\n' > "$work/creds.json" - fi - jq --arg key "$EXA_API_KEY" '.exa.apiKey = $key' "$work/creds.json" > "$work/creds-next.json" - chmod 600 "$work/creds-next.json" - run mv -f "$work/creds-next.json" "$creds" - fi - fi + # Exa reads its key from creds.json rather than from the environment, so one + # in this environment is copied in. The same function backs home-manager's + # activation (./albedo-exa-key.sh). + # shellcheck disable=SC1091 + source ${./albedo-exa-key.sh} + albedo_exa_key "$creds" run # One symlink per skill, so a skill added by hand stays and a skill that # moved in the flake lands on the next run. A symlinked skills root was put diff --git a/modules/agents/albedo.nix b/modules/agents/albedo.nix index c0cb7e7..f865801 100644 --- a/modules/agents/albedo.nix +++ b/modules/agents/albedo.nix @@ -1,86 +1,72 @@ -# Albedo's side of the shared agent config: the MCP servers, merged into -# $ALBEDO_HOME/extensions.json on activation, and a wrapper that puts the agent -# secrets in the daemon's environment, which is where albedo resolves -# `{ "env": ... }`. +# Albedo, through its own home-manager module: the client package, the daemon as +# a user service, and the MCP servers every agent shares (./servers.nix), which +# that module merges into $ALBEDO_HOME/extensions.json on activation. { config, + inputs, lib, pkgs, - inputs', ... }: let - cfg = config.dev.agents; albedo = config.dev.albedo; + cfg = config.dev.agents; - base = inputs'.albedo.packages.default; - - # The wrapper exists because the daemon reads its environment once, at exec: - # a shell that has the secrets is not enough, the process albedo starts must - # inherit them. - package = pkgs.writeShellApplication { - name = "albedo"; - meta = base.meta or { }; - passthru = base.passthru or { }; - derivationArgs.version = base.version or "0"; - text = '' - # shellcheck disable=SC1091 - if [ -f "${cfg.envFile}" ]; then set -a; . "${cfg.envFile}"; set +a; fi - - exec ${lib.getExe base} "$@" - ''; - }; + render = import ./lib.nix { inherit lib; }; - fragment = pkgs.writeText "albedo-mcp.json" ( - builtins.toJSON { - servers = lib.mapAttrs (_: render.toAlbedo) cfg.mcpServers; - enabled.mcp = true; - } + # A shared server the environment authenticates cannot be imported as written: + # albedo sends its bearer token as a variable read from the daemon's + # environment, never as a header. The import replaces a declared server of the + # same name as a whole, so the restated one is complete (./lib.nix) and only + # these servers need restating. + restatements = lib.optionalAttrs (cfg.enable && config.programs.mcp.enable) ( + lib.mapAttrs (_: render.toAlbedo) (lib.filterAttrs (_: server: server ? bearerTokenEnvVar) config.programs.mcp.servers) ); - render = import ./lib.nix { inherit lib; }; - - # The install itself is shared with the image the infra repo builds, so a - # merged extensions.json looks the same on a desktop and in a container. - seed = import ./albedo-seed.nix { - inherit lib pkgs; - inherit fragment; - }; + creds = "${config.home.homeDirectory}/.albedo/creds.json"; + keyPath = lib.makeBinPath [ + pkgs.coreutils + pkgs.jq + ]; in { - options.dev.agents.albedo = { - package = lib.mkOption { - type = lib.types.package; - readOnly = true; - default = package; - description = "The albedo CLI, wrapped to carry the agent secrets."; - }; - writeConfig = lib.mkOption { - type = lib.types.bool; - default = true; - description = '' - Merge dev.agents.mcpServers into $ALBEDO_HOME/extensions.json on - activation. Off leaves albedo's MCP servers to albedo's own /mcp. - ''; + imports = [ inputs.albedo.homeModules.default ]; + + options.dev.albedo.enable = lib.mkEnableOption "the Albedo coding agent"; + + config = lib.mkIf albedo.enable { + programs.albedo.enable = true; + + services.albedo = { + enable = true; + enableMcpIntegration = true; + settings.extensions.mcp.servers = restatements; }; - }; - config = lib.mkIf (albedo.enable && cfg.enable && cfg.albedo.writeConfig) { - home.activation.albedoMcp = - lib.hm.dag.entryAfter ([ "writeBoundary" ] ++ lib.optional (cfg.envFile != "/dev/null") "sops-nix") - '' - # A subshell, so sourcing the secrets stays out of every other - # activation entry's environment. - ( - # Secrets first: the fragment carries @env:NAME for URLs that are - # themselves secret, and the seed resolves them from this - # environment. It also copies EXA_API_KEY into creds.json, which is - # the only place Exa looks for it. - # shellcheck disable=SC1091 - if [ -f "${cfg.envFile}" ]; then set -a; . "${cfg.envFile}"; set +a; fi + # The daemon reads its environment once, at exec: a shell that has the + # secrets is not enough, so the service gets the decrypted dotenv file + # instead of the wrapper that used to source it. + systemd.user.services.albedo.Service.EnvironmentFile = lib.mkIf cfg.sops.enable "-${cfg.envFile}"; + + # Exa reads its key from creds.json rather than from the environment, and + # creds.json is albedo's own file (the module only manages the settings + # documents), so the key from the decrypted secrets is copied in. A subshell, + # so sourcing the secrets stays out of every other activation entry. + home.activation.albedoExaKey = lib.mkIf cfg.sops.enable ( + lib.hm.dag.entryAfter [ "writeBoundary" "sops-nix" ] '' + ( + export PATH=${keyPath}:$PATH + # shellcheck disable=SC1091 + source ${./albedo-exa-key.sh} + + set -a + # shellcheck disable=SC1091 + if [ -f "${cfg.envFile}" ]; then . "${cfg.envFile}"; fi + set +a - ${lib.getExe seed} ''${DRY_RUN_CMD:+--dry-run} - ) - ''; + albedo_exa_key ${lib.escapeShellArg creds} + ) + '' + ); }; } diff --git a/modules/agents/default.nix b/modules/agents/default.nix index 2a454be..7963fa4 100644 --- a/modules/agents/default.nix +++ b/modules/agents/default.nix @@ -1,7 +1,8 @@ -# Coding-agent configuration shared by every agent on this host: the MCP -# servers each one is given, the skills they all read, and one module per agent -# rendering that shared set into the agent's own format. Agent-specific settings -# stay in that agent's own module. +# Coding-agent configuration shared by every agent on this host: the MCP servers +# they are given, declared once in home-manager's `programs.mcp.servers` +# (./servers.nix), the skills they all read, and one module per agent, which +# imports that shared set into its own format. Agent-specific settings stay in +# that agent's own module. { ... }: { imports = [ ./albedo.nix diff --git a/modules/agents/lib.nix b/modules/agents/lib.nix index 0912e26..e866fec 100644 --- a/modules/agents/lib.nix +++ b/modules/agents/lib.nix @@ -1,68 +1,18 @@ -# One neutral MCP server shape, rendered into each agent's own config format. -# ./mcp.nix and any tag module declare a server once; opencode and albedo are -# both generated from that same set. -{ lib }: -let - # A header or environment value is a literal, or a reference to a variable - # the agent resolves when it connects. - toOpencodeSource = value: if builtins.isString value then value else "{env:${value.env}}"; - toAlbedoSource = value: if builtins.isString value then value else { env = value.env; }; -in -{ - # One entry of `mcp.servers` in ~/.config/opencode/opencode.json. - toOpencode = - server: - if server.type == "http" then - let - headers = - lib.mapAttrs (_: toOpencodeSource) server.headers - // lib.optionalAttrs (server.bearerEnv != null) { Authorization = "Bearer {env:${server.bearerEnv}}"; }; - in - { - type = "remote"; - url = if server.urlEnv != null then "{env:${server.urlEnv}}" else server.url; - } - // lib.optionalAttrs (headers != { }) { inherit headers; } - // lib.optionalAttrs (server.oauth != null) { inherit (server) oauth; } - // lib.optionalAttrs (!server.enabled) { disabled = true; } - // lib.optionalAttrs (server.timeoutMs != null) { timeout = server.timeoutMs; } - else - { - type = "local"; - command = server.command; - } - // lib.optionalAttrs (server.env != { }) { environment = lib.mapAttrs (_: toOpencodeSource) server.env; } - // lib.optionalAttrs (server.cwd != null) { inherit (server) cwd; } - // lib.optionalAttrs (!server.enabled) { disabled = true; } - // lib.optionalAttrs (server.timeoutMs != null) { timeout = server.timeoutMs; }; - - # One entry of `mcp.servers` in $ALBEDO_HOME/extensions.json. `enabled` is - # only written when it is off: albedo reads a missing one as on, so a server - # switched off from albedo's own UI survives the next activation. - # - # A URL cannot reference a variable here, so `urlEnv` becomes an `@env:NAME@` - # sentinel that ./albedo.nix substitutes from the decrypted secrets. +# The shared servers (./servers.nix) are declared in albedo's own shape already, +# so this only drops what albedo cannot use. Both callers need it: the restated +# servers in a home (./albedo.nix), and the image's extensions.json +# (./albedo-config.nix). +{ lib }: { + # Albedo cannot put a variable inside a header value, so a server that names + # its token variable sends it as `bearerTokenEnvVar` and loses that one + # header; a header it can send as written stays. It has no OAuth settings + # either: it starts its own sign-in when asked. toAlbedo = server: - if server.type == "http" then - { - type = "http"; - url = if server.urlEnv != null then "@env:${server.urlEnv}" else server.url; - } - // lib.optionalAttrs (server.headers != { }) { headers = lib.mapAttrs (_: toAlbedoSource) server.headers; } - // lib.optionalAttrs (server.bearerEnv != null) { bearerTokenEnvVar = server.bearerEnv; } - // lib.optionalAttrs (!server.enabled) { enabled = false; } - // lib.optionalAttrs (server.timeoutMs != null) { callTimeoutMs = server.timeoutMs; } - // lib.optionalAttrs (server.startupTimeoutMs != null) { inherit (server) startupTimeoutMs; } - else - { - type = "stdio"; - command = lib.head server.command; + lib.filterAttrs (_: value: value != null && value != [ ] && value != { }) ( + removeAttrs server [ "oauth" ] + // lib.optionalAttrs (server ? bearerTokenEnvVar) { + headers = removeAttrs (server.headers or { }) [ "Authorization" ]; } - // lib.optionalAttrs (lib.length server.command > 1) { args = lib.tail server.command; } - // lib.optionalAttrs (server.env != { }) { env = lib.mapAttrs (_: toAlbedoSource) server.env; } - // lib.optionalAttrs (server.cwd != null) { inherit (server) cwd; } - // lib.optionalAttrs (!server.enabled) { enabled = false; } - // lib.optionalAttrs (server.timeoutMs != null) { callTimeoutMs = server.timeoutMs; } - // lib.optionalAttrs (server.startupTimeoutMs != null) { inherit (server) startupTimeoutMs; }; + ); } diff --git a/modules/agents/mcp-servers.nix b/modules/agents/mcp-servers.nix deleted file mode 100644 index 8a33bf3..0000000 --- a/modules/agents/mcp-servers.nix +++ /dev/null @@ -1,210 +0,0 @@ -# The MCP servers every agent on the host is given, in one transport-neutral -# shape, and nothing about the way an install delivers them. ./mcp.nix adds the -# home-manager side (sops), and the flake renders this same set into albedo's -# own config for a machine home-manager never touches (./albedo-config.nix). -# -# A tag module adds a host's own servers with -# `dev.agents.mcpServers. = { ... };`. -{ - config, - lib, - self', - ... -}: -let - cfg = config.dev.agents; - - # A header or environment value is a literal, or a reference to a variable - # the agent resolves when it connects. - source = lib.types.either lib.types.str ( - lib.types.submodule { - options.env = lib.mkOption { - type = lib.types.str; - description = "Name of the environment variable holding the value."; - }; - } - ); - - server = lib.types.submodule { - options = { - type = lib.mkOption { - type = lib.types.enum [ - "http" - "stdio" - ]; - description = "An HTTP endpoint, or a command spoken to over stdio."; - }; - url = lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - description = "Endpoint of an HTTP server."; - }; - urlEnv = lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - description = '' - Environment variable holding the whole endpoint, for a URL that is - itself a secret. Albedo cannot reference a variable in `url`, so its - config carries the value substituted at activation. - ''; - }; - bearerEnv = lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - description = "Environment variable holding a token sent as `Authorization: Bearer $VAR`."; - }; - headers = lib.mkOption { - type = lib.types.attrsOf source; - default = { }; - description = "Extra headers of an HTTP server."; - }; - oauth = lib.mkOption { - type = lib.types.nullOr (lib.types.either lib.types.bool lib.types.attrs); - default = null; - description = '' - OpenCode's OAuth settings; `false` stops it probing for one. Albedo - has no equivalent and starts its own sign-in whenever a server asks - for one. - ''; - }; - command = lib.mkOption { - type = lib.types.listOf lib.types.str; - default = [ ]; - description = "Command and arguments of a stdio server."; - }; - env = lib.mkOption { - type = lib.types.attrsOf source; - default = { }; - description = "Environment of a stdio server."; - }; - cwd = lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - description = "Working directory of a stdio server."; - }; - enabled = lib.mkOption { - type = lib.types.bool; - default = true; - description = "Off keeps the definition without connecting to it."; - }; - timeoutMs = lib.mkOption { - type = lib.types.nullOr lib.types.int; - default = null; - description = "Per-request timeout in milliseconds."; - }; - startupTimeoutMs = lib.mkOption { - type = lib.types.nullOr lib.types.int; - default = null; - description = "How long a session waits for the server to start. Albedo only."; - }; - }; - }; -in -{ - options.dev.agents = { - enable = lib.mkEnableOption "shared coding-agent configuration"; - - secretServers = lib.mkOption { - type = lib.types.bool; - default = true; - description = '' - Include the servers that need a secret from the environment. A host - that holds the secrets itself (home-manager decrypts them with sops, a - container gets them from its deployment) says so here, so the servers - without one stay declared and switched off. - ''; - }; - - mcpBrowser = lib.mkOption { - type = lib.types.nullOr lib.types.package; - default = null; - description = '' - Browser the chrome-devtools MCP drives, passed as --executablePath. - Null leaves the flag off and lets the server look for a Chrome itself. - Desktop hosts set this to helium (modules/desktop/apps/browser.nix); - override it per host to use a different browser. - ''; - }; - - attachBrowser = lib.mkOption { - type = lib.types.nullOr lib.types.str; - default = null; - description = '' - DevToolsActivePort file of a browser that is already running, as a path - this machine can read. When set, the chrome-devtools MCP attaches to - that browser over CDP instead of launching one, so the agent sees the - tabs and logged-in sessions of the user's own profile. - - The file holds two lines: the CDP port, then the - /devtools/browser/ socket path. Chromium serves no - /json/version on that implicit endpoint, so the server needs - --wsEndpoint rather than --browserUrl, and it must read the file at - connect time because the uuid changes on every browser start. - ''; - }; - - mcpServers = lib.mkOption { - type = lib.types.attrsOf server; - default = { }; - description = '' - MCP servers every agent on this host is given. Declared here or in a - tag module; rendered into each agent's own config by ./lib.nix. - ''; - }; - }; - - config = { - dev.agents.enable = lib.mkDefault true; - - dev.agents.mcpServers = lib.mkIf cfg.enable ( - { - # outline doesn't need secrets, always available - outline = { - type = "http"; - url = "https://outline.dolly-ruffe.ts.net/mcp"; - }; - - # Off unless a host points it at a running browser: the fallback - # branch launches one, which is a blank profile and no sessions. - chrome-devtools = { - type = "stdio"; - enabled = cfg.attachBrowser != null; - command = - if cfg.attachBrowser != null then - [ - "bash" - "-lc" - ( - "f=${lib.escapeShellArg cfg.attachBrowser}; " - + "exec ${lib.getExe self'.packages.chrome-devtools-mcp} " - + "--wsEndpoint \"ws://127.0.0.1:$(sed -n 1p \"$f\")$(sed -n 2p \"$f\")\"" - ) - ] - else - [ (lib.getExe self'.packages.chrome-devtools-mcp) ] - ++ lib.optionals (cfg.mcpBrowser != null) [ - "--executablePath" - (lib.getExe cfg.mcpBrowser) - ]; - }; - } - // lib.optionalAttrs cfg.secretServers { - # These need a secret from the environment, so they only appear where - # the host has one to give. - github = { - type = "http"; - url = "https://api.githubcopilot.com/mcp/"; - bearerEnv = "GITHUB_TOKEN"; - }; - - kagi = { - type = "http"; - url = "https://mcp.kagi.com/mcp"; - bearerEnv = "KAGI_API_KEY"; - oauth = false; - enabled = false; - }; - } - ); - }; -} diff --git a/modules/agents/mcp.nix b/modules/agents/mcp.nix index 4f82556..1cf6eb2 100644 --- a/modules/agents/mcp.nix +++ b/modules/agents/mcp.nix @@ -1,23 +1,29 @@ -# The home-manager side of the shared MCP servers (./mcp-servers.nix): the -# encrypted secrets they read, and the hosts that have them. The servers -# themselves live in the module this one imports, so the flake can evaluate -# them without home-manager for an image that home-manager never configures. +# The home-manager side of the shared MCP servers (./servers.nix): the encrypted +# secrets they read, the hosts that have them, and the declaration itself — +# `programs.mcp.servers`, which every client on this host is fed from (opencode +# through enableMcpIntegration, albedo through its own module in ./albedo.nix). { config, inputs, lib, + pkgs, + self', ... }: let cfg = config.dev.agents; + + servers = import ./servers.nix { + inherit lib pkgs self'; + inherit (cfg) mcpBrowser attachBrowser secretServers; + }; in { - imports = [ - ./mcp-servers.nix - inputs.sops-nix.homeManagerModules.sops - ]; + imports = [ inputs.sops-nix.homeManagerModules.sops ]; options.dev.agents = { + enable = lib.mkEnableOption "shared coding-agent configuration"; + sops = { enable = lib.mkOption { type = lib.types.bool; @@ -29,22 +35,64 @@ in ''; }; }; + envFile = lib.mkOption { type = lib.types.path; readOnly = true; default = lib.attrByPath [ "agents/env" "path" ] "/dev/null" config.sops.secrets; description = "Decrypted dotenv file holding the agents' secrets."; }; + + secretServers = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Include the servers that need a secret from the environment. A host that + holds the secrets itself (home-manager decrypts them with sops, a + container gets them from its deployment) says so here, so the servers + without one stay declared and switched off. + ''; + }; + + mcpBrowser = lib.mkOption { + type = lib.types.nullOr lib.types.package; + default = null; + description = '' + Browser the chrome-devtools MCP drives, passed as --executablePath. Null + leaves the flag off and lets the server look for a Chrome itself. + Desktop hosts set this to helium (modules/desktop/apps/browser.nix); + override it per host to use a different browser. + ''; + }; + + attachBrowser = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + description = '' + DevToolsActivePort file of a browser that is already running, as a path + this machine can read. When set, the chrome-devtools MCP attaches to that + browser over CDP instead of launching one, so the agent sees the tabs and + logged-in sessions of the user's own profile, and the server is switched + on. + ''; + }; }; config = { + dev.agents.enable = lib.mkDefault true; + # A host whose secrets decrypt is a host whose secret-bearing servers have - # something to send; ./mcp-servers.nix only knows that second fact. + # something to send; ./servers.nix only knows that second fact. dev.agents.secretServers = lib.mkDefault cfg.sops.enable; sops.secrets."agents/env" = lib.mkIf cfg.sops.enable { sopsFile = ../../secrets/agents.env; format = "dotenv"; }; + + programs.mcp = lib.mkIf cfg.enable { + enable = true; + inherit servers; + }; }; } diff --git a/modules/agents/opencode.nix b/modules/agents/opencode.nix index 1d672ec..fb76539 100644 --- a/modules/agents/opencode.nix +++ b/modules/agents/opencode.nix @@ -1,7 +1,7 @@ # OpenCode, the agent: the switch that turns it on, the wrapper that carries the # agent secrets, the resource-confined shell, and everything else it is given — -# the agents and commands under ./opencode, the MCP servers from ./mcp.nix, and -# the settings that shape them. +# the agents and commands under ./opencode, the MCP servers from +# `programs.mcp.servers` (./mcp.nix), and the settings that shape them. { config, lib, @@ -16,9 +16,6 @@ let # where sops can't decrypt. opencodeEnvFile = config.dev.agents.envFile; - # The shared MCP servers, in this agent's own shape. - render = import ./lib.nix { inherit lib; }; - sliceName = "opencode.slice"; # systemd-run has to hand off the real binary on the same exec line; as a @@ -78,7 +75,7 @@ in enableMcp = lib.mkOption { type = lib.types.bool; default = true; - description = "MCP server integrations for enhanced language support"; + description = "Import the shared programs.mcp.servers (./mcp.nix) into this client's own MCP configuration."; }; theme = lib.mkOption { type = lib.types.str; @@ -269,8 +266,6 @@ in effect = "allow"; } ]; - # The servers are declared once, in ./mcp.nix. - mcp = lib.mkIf cfg.enableMcp { servers = lib.mapAttrs (_: render.toOpencode) config.dev.agents.mcpServers; }; } // lib.optionalAttrs (cfg.plugins != [ ]) { inherit (cfg) plugins; }; }; diff --git a/modules/agents/servers.nix b/modules/agents/servers.nix new file mode 100644 index 0000000..08b7fc8 --- /dev/null +++ b/modules/agents/servers.nix @@ -0,0 +1,91 @@ +# The MCP servers every agent on this host is given, in home-manager's +# `programs.mcp.servers` shape. ./mcp.nix hands them to `programs.mcp`, which +# writes them for the clients that read ~/.config/mcp/mcp.json and feeds both +# agents' own integrations; ./albedo-config.nix renders the same set into the +# image that home-manager never configures. +# +# Each entry is written so albedo can take it as-is (./lib.nix only drops the two +# fields it has no use for), which means `type` is spelled out: opencode +# recomputes it, albedo reads it. +# +# A tag module adds a host's own servers with +# `programs.mcp.servers. = { ... };` — there is no wrapper option. +{ + lib, + pkgs, + self', + # Browser the chrome-devtools MCP drives, passed as --executablePath. Null + # leaves the flag off and lets the server look for a Chrome itself. + mcpBrowser ? null, + # DevToolsActivePort file of a browser that is already running, as a path this + # machine can read: the server attaches to it over CDP instead of launching + # one, so the agent sees the tabs and logged-in sessions of the user's own + # profile. + attachBrowser ? null, + # Include the servers that need a secret from the environment. A host that + # holds the secrets itself says so here; the ones without keep them declared + # and switched off. + secretServers ? true, +}: +let + chrome-devtools-mcp = lib.getExe self'.packages.chrome-devtools-mcp; + sed = lib.getExe' pkgs.coreutils "sed"; + + # DevToolsActivePort holds the CDP port on line 1 and /devtools/browser/ + # on line 2. Chromium serves no /json/version on that implicit endpoint, so + # the server needs --wsEndpoint rather than --browserUrl, and it must read the + # file at connect time because the uuid changes on every browser start. + attachScript = '' + f=${lib.escapeShellArg attachBrowser} + exec ${chrome-devtools-mcp} --wsEndpoint "ws://127.0.0.1:$(${sed} -n 1p "$f")$(${sed} -n 2p "$f")" + ''; +in +{ + # No secret, so always available. + outline = { + type = "http"; + url = "https://outline.dolly-ruffe.ts.net/mcp"; + }; + + # Off unless a host points it at a running browser: the fallback branch + # launches one, which is a blank profile and no sessions. + chrome-devtools = { + type = "stdio"; + enabled = attachBrowser != null; + command = if attachBrowser != null then lib.getExe pkgs.bash else chrome-devtools-mcp; + args = + if attachBrowser != null then + [ + "-lc" + attachScript + ] + else + lib.optionals (mcpBrowser != null) [ + "--executablePath" + (lib.getExe mcpBrowser) + ]; + }; +} +// lib.optionalAttrs secretServers { + # These need a secret from the environment, so they only appear where the host + # has one to give. Each names its token twice because the clients disagree on + # the form: opencode sends the header, albedo reads the variable out of the + # daemon's environment and cannot put a variable inside a header value at all, + # so `bearerTokenEnvVar` is also the mark for the servers ./lib.nix strips. + github = { + type = "http"; + url = "https://api.githubcopilot.com/mcp/"; + headers.Authorization = "Bearer {env:GITHUB_TOKEN}"; + bearerTokenEnvVar = "GITHUB_TOKEN"; + }; + + kagi = { + type = "http"; + url = "https://mcp.kagi.com/mcp"; + headers.Authorization = "Bearer {env:KAGI_API_KEY}"; + bearerTokenEnvVar = "KAGI_API_KEY"; + # The key is the credential; an OAuth probe only gets in the way. + oauth = false; + enabled = false; + }; +} diff --git a/modules/dev/tools/albedo.nix b/modules/dev/tools/albedo.nix deleted file mode 100644 index 6e253a3..0000000 --- a/modules/dev/tools/albedo.nix +++ /dev/null @@ -1,7 +0,0 @@ -{ config, lib, ... }: { - options.dev.albedo.enable = lib.mkEnableOption "the Albedo coding agent"; - - # The package comes from modules/agents: albedo is handed the same MCP - # servers opencode gets, and it needs the agent secrets in its environment. - config = lib.mkIf config.dev.albedo.enable { home.packages = [ config.dev.agents.albedo.package ]; }; -} diff --git a/modules/dev/tools/default.nix b/modules/dev/tools/default.nix index 6a4782a..7134f50 100644 --- a/modules/dev/tools/default.nix +++ b/modules/dev/tools/default.nix @@ -19,6 +19,8 @@ in { config = lib.mkIf config.dev.enable { home.packages = [ + # The guided-review skill renders its pages with python3. + pkgs.python3 pkgs.sd pkgs.fd pkgs.uutils-coreutils-noprefix @@ -42,7 +44,6 @@ in }; imports = [ - ./albedo.nix ./direnv.nix ./gallant.nix ./tuicr.nix diff --git a/modules/tags/work-home.nix b/modules/tags/work-home.nix index 3245dff..61baee9 100644 --- a/modules/tags/work-home.nix +++ b/modules/tags/work-home.nix @@ -9,18 +9,24 @@ path = "~/upf/.gitconfig" ''; - # Work's MCP servers, in the shared shape (modules/agents): opencode and - # albedo are both generated from these. - dev.agents.mcpServers = { + # Work's MCP servers, in home-manager's shared shape: opencode imports them + # through enableMcpIntegration, albedo through its own module. A server the + # environment authenticates names its token twice (../agents/servers.nix says + # why): opencode sends the header, albedo reads `bearerTokenEnvVar`. + programs.mcp.servers = { linear = { type = "http"; url = "https://mcp.linear.app/mcp"; - bearerEnv = "LINEAR_API_KEY"; + headers.Authorization = "Bearer {env:LINEAR_API_KEY}"; + bearerTokenEnvVar = "LINEAR_API_KEY"; }; + + # Sentry's hosted MCP signs in with OAuth, so the endpoint carries no + # credential and needs no scope: both clients start their own sign-in, and + # whoever has one organization gets it as the default without naming it. sentry = { type = "http"; - urlEnv = "SENTRY_MCP_URL"; - oauth = { }; + url = "https://mcp.sentry.dev/mcp"; }; }; } diff --git a/secrets/agents.env b/secrets/agents.env index ce63c3a..6be37aa 100644 --- a/secrets/agents.env +++ b/secrets/agents.env @@ -2,7 +2,6 @@ GITHUB_TOKEN=ENC[AES256_GCM,data:g/pqSC70GyTu47q/4GJaK6Gbpiz4VHQOJDl+I/kUg+05QiS KAGI_API_KEY=ENC[AES256_GCM,data:t+cD44D/LewJiIreUkQaFDnwHE7etkKDkDy0hf/PlgeOzOH/6uynzcrkj+8ucWp7TdN54csTT9APIf7obpfuWAdxUGWJCroKpVMKWhJUeH0sKieAX/jT1cE=,iv:80xFz6jlrDz0Fq2LU/oRmQ4D0aD2qb5WOcFJX7mjTRk=,tag:jNem3NKoH+pXcnwUteOguA==,type:str] LINEAR_API_KEY=ENC[AES256_GCM,data:3a0OkLtLSjZII+U4VpwOMimXkpikyrwL8xsnpbSUlq76ue4akST6ce8AGUvWz+JsVyU=,iv:yEu9g8LFBiiYWGOMDbFluBgq/wr1fWKF6BPcp8ynpPI=,tag:ROyd6FXhYs4nTfUYSQTuxw==,type:str] EXA_API_KEY=ENC[AES256_GCM,data:+k2MrLH0V5S1cc2EnSZ7CgkzIdAga9O/TYZwWA+M72oaDD6uliE=,iv:h9poL0P9XaoSzApp6Zd/PD4gnS+r458nq7IYGY9aFlo=,tag:xAz2WeeP0+eg4REXGW0Teg==,type:str] -SENTRY_MCP_URL=ENC[AES256_GCM,data:fprKxyopD4qRoZqLojNErq+4CPE1VI5QTUNQn5DZtgBzY5Gx6+E=,iv:pMKJn/UKVAS2o7QwtwjMKyFZHULdjRgz6kWwpN2mZpo=,tag:tRXnfCOfw80q4id0PPbBCQ==,type:str] sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IHdLbEpGdyBPSWJj\nb2V1ZjZiNjRvNDJnM2RDOWpiNk1iOWFzRGpUNThmbnJ1QjdNNUNzCi9haU9xTFcy\ncm1PYVJmcUk1cmZqSnVXM1FKMndtMWZ1U0Zpb2E1MXlMVm8KLS0tIHdMQVhNcFNZ\neEFWZDdsMkxoWlp2QU9BZ0RqZ0lUNzkyWE9BbmdXU0pBdVUKnf1RiM8/yUJhDaUc\nhoIQddc9H9AvZasv+rQFtjhXBnRKSSQyWE40gha9FPjW18iFzvcDEMEvWjxExfpn\nR5PHsQ==\n-----END AGE ENCRYPTED FILE-----\n sops_age__list_0__map_recipient=ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSNRhCfSzYU5bliUcc+3axoVI46XbQ7uE58374CoOg3 sops_age__list_1__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IE9EZVJNQSA0M2pE\neklnUW40MlB3N3Q3WnZ0UEtnUzhOSkNwWHNlcnpka3NLbnZ4OVNNCjU0UzZwSFk3\nRGdjc2RXdndBbStvOFpuWkM1SzgrdGpsZGUrTjFKckRrT0EKLS0tIHhOaHZNZitY\nSDdqeFkzc25uc05hdFVNcitrN3NoOEo2K3ZsUlozcFlXS0UK+ZudPGHRW3xSYQDI\ncAtbfc2/2JHhMddv9NVK6FDF8QZ/i2/UUfZN1s3Y3sXnc7ITmwtbwbtUv6ATQLnP\n8am3ow==\n-----END AGE ENCRYPTED FILE-----\n @@ -11,7 +10,7 @@ sops_age__list_2__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb2 sops_age__list_2__map_recipient=age17cxj5zwkkxjkjvmpskpkyh6yt4xj4l8h6jyjxez3nmq6y9tvhqjsdp0m5j sops_age__list_3__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBnSXlaNVRLbG1hVHZmcEN0\nR0pnb21BczhySCt4SXc0OFRVbjgzUTROOVc0CldHam1pK1N5cnRka0E2TUExeXph\nV3UvUERoVktiMG9sSS9PSGx0a2Q0bWsKLS0tIFB4YXRsR0xFckV5L09MQ3dwQm9R\nbUN0WUVaaXZISEtZNldBOUNzZFhZbFEKKv4ybBd/NySlQ3pe0gCUG00jO5xQEbPv\nRbKo2aFVP7zv+xJj9uam1q2CTrFoWt1GY25JK6Utn7giMNy2IvBu6A==\n-----END AGE ENCRYPTED FILE-----\n sops_age__list_3__map_recipient=age1j6j2ldpsj7jmchstwl3nktvatut9hzxnemmy6py84rrga5eaf93q5w8s39 -sops_lastmodified=2026-08-17T08:04:26Z -sops_mac=ENC[AES256_GCM,data:AeEzoba6Sph31bs4+nAKdO9MsLaAFpoeiOk4BJVAqxlIxk0NvWuLX+j/SzG2BZLlba4qexqgz/92AD6fqQ7j4eDxIO/jOu8dtNg8CSjepwPITgXYhZiqkA0D84Qdtmgn5sdgUY4tlsehI7zoDhEBlOAZX4gxDkNDt7SXmmeOdyw=,iv:Nkc281TH/vbtF2Nvgdc836YRY3FYOYVlY8lMe2sNHyY=,tag:OVqwR8jdpVYdVPIO4sUhQg==,type:str] +sops_lastmodified=2026-11-10T09:22:58Z +sops_mac=ENC[AES256_GCM,data:2L0BBEmVbjxsxC5F4S5KASWhv/cHYqWCnXPFhNXlWq5Xo0TvCO0CjMDEcZELKKQFTeVKDJt17fmOJP6Hp/9DbPmg7PrUgIQ9rZAGUquAokLF+Ww3slKcMTk6hl23vbs5eZ3SvVhSLCz29Ig5TbBonDIXslrX6Jd6ZknNcys2rcg=,iv:rre5M5hmg8E28q97W2c6VsYEq7QsNhizUCYkZTtTwUc=,tag:FPWdcvERhkpM3EuoUgb1xw==,type:str] sops_unencrypted_suffix=_unencrypted -sops_version=3.13.1 +sops_version=3.13.3