|
| 1 | +{ |
| 2 | + config, |
| 3 | + pkgs, |
| 4 | + lib, |
| 5 | + ... |
| 6 | +}: let |
| 7 | + cfg = config.services.kagi-mcp; |
| 8 | + |
| 9 | + startScript = pkgs.writeShellScript "kagi-mcp-start" '' |
| 10 | + exec ${lib.getExe pkgs.uv} run --with kagimcp python -c " |
| 11 | + from kagimcp.server import mcp |
| 12 | + mcp.settings.host = '${cfg.host}' |
| 13 | + mcp.settings.port = ${toString cfg.port} |
| 14 | + mcp.run(transport='streamable-http') |
| 15 | + " |
| 16 | + ''; |
| 17 | +in { |
| 18 | + options.services.kagi-mcp = { |
| 19 | + enable = lib.mkEnableOption "Kagi MCP server"; |
| 20 | + |
| 21 | + port = lib.mkOption { |
| 22 | + type = lib.types.port; |
| 23 | + default = 8093; |
| 24 | + description = "Port for the streamable HTTP transport."; |
| 25 | + }; |
| 26 | + |
| 27 | + host = lib.mkOption { |
| 28 | + type = lib.types.str; |
| 29 | + default = "127.0.0.1"; |
| 30 | + description = "Address to bind the HTTP server to."; |
| 31 | + }; |
| 32 | + |
| 33 | + environmentFile = lib.mkOption { |
| 34 | + type = lib.types.path; |
| 35 | + description = "Path to environment file containing KAGI_API_KEY."; |
| 36 | + }; |
| 37 | + |
| 38 | + openFirewall = lib.mkEnableOption "opening firewall ports for Kagi MCP"; |
| 39 | + }; |
| 40 | + |
| 41 | + config = lib.mkIf cfg.enable { |
| 42 | + users.users.kagi-mcp = { |
| 43 | + isSystemUser = true; |
| 44 | + group = "kagi-mcp"; |
| 45 | + home = "/var/lib/kagi-mcp"; |
| 46 | + }; |
| 47 | + users.groups.kagi-mcp = {}; |
| 48 | + |
| 49 | + systemd.services.kagi-mcp = { |
| 50 | + description = "Kagi MCP Server"; |
| 51 | + after = ["network-online.target"]; |
| 52 | + wants = ["network-online.target"]; |
| 53 | + wantedBy = ["multi-user.target"]; |
| 54 | + |
| 55 | + environment = { |
| 56 | + HOME = "/var/lib/kagi-mcp"; |
| 57 | + UV_CACHE_DIR = "/var/lib/kagi-mcp/.cache/uv"; |
| 58 | + }; |
| 59 | + |
| 60 | + serviceConfig = { |
| 61 | + ExecStart = "${startScript}"; |
| 62 | + EnvironmentFile = cfg.environmentFile; |
| 63 | + User = "kagi-mcp"; |
| 64 | + Group = "kagi-mcp"; |
| 65 | + WorkingDirectory = "/var/lib/kagi-mcp"; |
| 66 | + StateDirectory = "kagi-mcp"; |
| 67 | + Restart = "on-failure"; |
| 68 | + RestartSec = 5; |
| 69 | + |
| 70 | + # Hardening |
| 71 | + NoNewPrivileges = true; |
| 72 | + PrivateDevices = true; |
| 73 | + PrivateTmp = true; |
| 74 | + ProtectHome = "tmpfs"; |
| 75 | + BindPaths = ["/var/lib/kagi-mcp"]; |
| 76 | + ProtectSystem = "strict"; |
| 77 | + ReadWritePaths = ["/var/lib/kagi-mcp"]; |
| 78 | + ProtectKernelTunables = true; |
| 79 | + ProtectKernelModules = true; |
| 80 | + ProtectControlGroups = true; |
| 81 | + RestrictSUIDSGID = true; |
| 82 | + }; |
| 83 | + }; |
| 84 | + |
| 85 | + programs.nix-ld.enable = true; |
| 86 | + |
| 87 | + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [cfg.port]; |
| 88 | + }; |
| 89 | +} |
0 commit comments