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