Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(mcp): clean stale Windows replacement temporary files (#13010)

zipg32bfb30410d2
diff --git a/.github/scripts/install-mcp-powershell.test.ps1 b/.github/scripts/install-mcp-powershell.test.ps1
index ef159aeec9..32c269006c 100644
--- a/.github/scripts/install-mcp-powershell.test.ps1
+++ b/.github/scripts/install-mcp-powershell.test.ps1
@@ -73,11 +73,16 @@ try {
Assert-True ($output.Contains((ConvertTo-Json -InputObject $binary -Compress))) 'Config is not the escaped absolute path'
Assert-True ($configuredPath -eq (Split-Path $binary)) 'PATH target differs'
Assert-True (!(Get-ChildItem -LiteralPath (Split-Path $binary) -Directory -Force)) 'Temporary install directory leaked'
+ $stale = Join-Path (Split-Path $binary) 'dbx-mcp.exe~RF8c73e4f.TMP'
+ [IO.File]::WriteAllText($stale, 'old executable')
$rerun = Install-DbxMcp | Out-String
Assert-True ($rerun.Contains('dbx-mcp 0.4.96 already up to date')) 'Rerun not idempotent'
+ Assert-True (!(Test-Path -LiteralPath $stale)) 'Up-to-date install left replacement temp file'
+ [IO.File]::WriteAllText($stale, 'old executable')
'0.4.95' | Set-Content -LiteralPath $marker
$updated = Install-DbxMcp | Out-String
Assert-True ($updated.Contains('Installed dbx-mcp 0.4.96')) 'Marker-based upgrade failed'
+ Assert-True (!(Test-Path -LiteralPath $stale)) 'Upgrade left replacement temp file'
Remove-Item -LiteralPath $binary
$repaired = Install-DbxMcp | Out-String
Assert-True ($repaired.Contains('Installed dbx-mcp 0.4.96')) 'Orphan marker prevented installation'
@@ -107,6 +112,61 @@ try {
Assert-True ((Get-Content -LiteralPath $marker -Raw).Trim() -eq '0.4.97') 'Downgrade changed marker'
$script:count++
Write-Output 'PASS older mirror cannot downgrade installation'
+ $installDir = Split-Path $binary
+ $preservedNames = @('dbx-mcp.exe', '.dbx-mcp-version', 'other.tmp', 'dbx-mcp.exe~RFxyz.TMP', 'dbx-mcp.exe~RF.TMP')
+ foreach ($name in $preservedNames | Select-Object -Skip 2) {
+ [IO.File]::WriteAllText((Join-Path $installDir $name), 'preserve')
+ }
+ $nested = Join-Path $installDir 'dbx-mcp.exe~RF123.TMP'
+ [IO.Directory]::CreateDirectory($nested) | Out-Null
+ $nestedFile = Join-Path $nested 'dbx-mcp.exe~RFabc.TMP'
+ [IO.File]::WriteAllText($nestedFile, 'nested')
+ $stale = Join-Path $installDir 'DBX-MCP.EXE~rfABC123.tmp'
+ [IO.File]::WriteAllText($stale, 'old executable')
+ Remove-McpReplacementTempFiles $installDir
+ Assert-True (!(Test-Path -LiteralPath $stale)) 'Case-insensitive replacement cleanup failed'
+ foreach ($name in $preservedNames) {
+ Assert-True (Test-Path -LiteralPath (Join-Path $installDir $name) -PathType Leaf) "Cleanup removed $name"
+ }
+ Assert-True ((Get-Content -LiteralPath $binary -Raw) -eq 'fixture binary') 'Cleanup changed active binary'
+ Assert-True ((Get-Content -LiteralPath $marker -Raw).Trim() -eq '0.4.97') 'Cleanup changed version marker'
+ Assert-True ((Get-Content -LiteralPath $nestedFile -Raw) -eq 'nested') 'Cleanup recursed into a directory'
+ Remove-McpReplacementTempFiles (Join-Path $testRoot 'missing')
+ $script:count++
+ Write-Output 'PASS cleanup preserves active binary, marker, unrelated files and directories'
+ $linkTarget = Join-Path $testRoot 'linked-target'
+ [IO.Directory]::CreateDirectory($linkTarget) | Out-Null
+ $targetFile = Join-Path $linkTarget 'dbx-mcp.exe~RF789.TMP'
+ [IO.File]::WriteAllText($targetFile, 'preserve link target')
+ $directoryLink = Join-Path $installDir 'dbx-mcp.exe~RF789.TMP'
+ $linkType = if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { 'Junction' } else { 'SymbolicLink' }
+ New-Item -ItemType $linkType -Path $directoryLink -Target $linkTarget | Out-Null
+ Remove-McpReplacementTempFiles $installDir
+ Remove-McpReplacementTempFiles $directoryLink
+ Assert-True ((Get-Content -LiteralPath $targetFile -Raw) -eq 'preserve link target') 'Cleanup followed directory link'
+ if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
+ $fileLink = Join-Path $installDir 'dbx-mcp.exe~RFabc.TMP'
+ New-Item -ItemType SymbolicLink -Path $fileLink -Target $targetFile | Out-Null
+ Remove-McpReplacementTempFiles $installDir
+ Assert-True ((Get-Item -LiteralPath $fileLink).Attributes -band [IO.FileAttributes]::ReparsePoint) 'Cleanup removed file link'
+ }
+ $script:count++
+ Write-Output 'PASS cleanup skips links'
+ if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) {
+ $lockedPath = Join-Path $installDir 'dbx-mcp.exe~RF456.TMP'
+ [IO.File]::WriteAllText($lockedPath, 'locked')
+ $locked = [IO.File]::Open($lockedPath, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
+ try {
+ [IO.File]::WriteAllText($stale, 'old executable')
+ Remove-McpReplacementTempFiles $installDir
+ Assert-True (Test-Path -LiteralPath $lockedPath) 'Cleanup removed locked file'
+ Assert-True (!(Test-Path -LiteralPath $stale)) 'Locked file prevented cleanup of other files'
+ } finally { $locked.Dispose() }
+ Remove-McpReplacementTempFiles $installDir
+ Assert-True (!(Test-Path -LiteralPath $lockedPath)) 'Cleanup did not retry released file'
+ $script:count++
+ Write-Output 'PASS cleanup skips locked files and retries after release'
+ }
Write-Output "PowerShell installer scenarios passed: $script:count"
} finally {
Set-Variable HOME -Scope Global -Force -Value $originalHome
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d09cebf52c..432caf6ea4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -324,6 +324,21 @@ jobs:
- name: Setup Rust for standard Windows
uses: dtolnay/[email protected]
+ - name: MCP replacement temporary file cleanup tests
+ shell: pwsh
+ run: |
+ @'
+ #[path = "src-tauri/src/commands/mcp_cleanup.rs"]
+ mod cleanup;
+ '@ | rustc --edition 2021 --test -o "$env:RUNNER_TEMP/mcp-cleanup-tests.exe" -
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ & "$env:RUNNER_TEMP/mcp-cleanup-tests.exe"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+
+ - name: PowerShell MCP installer tests
+ shell: pwsh
+ run: ./.github/scripts/install-mcp-powershell.test.ps1
+
- uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
with:
version: "v0.16.0"
diff --git a/docs/public/install-mcp.ps1 b/docs/public/install-mcp.ps1
index f16da3ed88..4ef3bff47d 100644
--- a/docs/public/install-mcp.ps1
+++ b/docs/public/install-mcp.ps1
@@ -41,6 +41,19 @@ function Move-Atomic([string]$Source, [string]$Destination) {
if ([IO.File]::Exists($Destination)) { [IO.File]::Replace($Source, $Destination, [NullString]::Value) }
else { [IO.File]::Move($Source, $Destination) }
}
+function Remove-McpReplacementTempFiles([string]$Directory) {
+ try {
+ $item = Get-Item -LiteralPath $Directory -Force -ErrorAction Stop
+ if (!$item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { return }
+ Get-ChildItem -LiteralPath $Directory -Force -ErrorAction Stop | Where-Object {
+ !$_.PSIsContainer -and !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and
+ $_.Name -imatch '\Adbx-mcp\.exe~RF[0-9a-f]+\.TMP\z'
+ } | ForEach-Object {
+ # A running MCP process may still hold the old executable; retry on the next run.
+ try { [IO.File]::Delete($_.FullName) } catch {}
+ }
+ } catch {}
+}
function Set-InstallPath([string]$Directory) {
try {
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
@@ -162,7 +175,10 @@ function Install-DbxMcp {
Set-InstallPath $installDir
Write-Output "Installed dbx-mcp $version at $binary"
Show-Configs $binary
- } finally { Remove-Item -LiteralPath $workDir -Recurse -Force -ErrorAction SilentlyContinue }
+ } finally {
+ Remove-Item -LiteralPath $workDir -Recurse -Force -ErrorAction SilentlyContinue
+ Remove-McpReplacementTempFiles $installDir
+ }
}
Install-DbxMcp
diff --git a/src-tauri/src/commands/mcp.rs b/src-tauri/src/commands/mcp.rs
index fd4df0b7af..ea49318816 100644
--- a/src-tauri/src/commands/mcp.rs
+++ b/src-tauri/src/commands/mcp.rs
@@ -7,9 +7,23 @@ use std::time::Duration;
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Manager};
+#[cfg(any(windows, test))]
+#[path = "mcp_cleanup.rs"]
+mod cleanup;
#[path = "mcp_native_installation.rs"]
mod native_installation;
+#[cfg(windows)]
+pub(crate) fn cleanup_mcp_installation_temp_files() {
+ let Some(home) = env::var_os("USERPROFILE").map(PathBuf::from).filter(|home| home.is_absolute()) else {
+ return;
+ };
+ let directory = home.join(".dbx").join("bin");
+ if let Err(error) = cleanup::cleanup_directory(&directory) {
+ log::debug!("Could not clean MCP replacement temporary files in {}: {error}", directory.display());
+ }
+}
+
const MCP_PACKAGE_NAME: &str = "@dbx-app/mcp-server";
const MCP_LATEST_URL: &str = "https://registry.npmjs.org/@dbx-app%2fmcp-server/latest";
const MCP_UNINSTALL_COMMAND: &str = "npm uninstall -g @dbx-app/mcp-server";
diff --git a/src-tauri/src/commands/mcp_cleanup.rs b/src-tauri/src/commands/mcp_cleanup.rs
new file mode 100644
index 0000000000..54e93ffb19
--- /dev/null
+++ b/src-tauri/src/commands/mcp_cleanup.rs
@@ -0,0 +1,162 @@
+use std::fs::{self, Metadata};
+use std::io;
+use std::path::Path;
+
+fn is_replacement_temp_file(name: &str) -> bool {
+ let name = name.to_ascii_lowercase();
+ name.strip_prefix("dbx-mcp.exe~rf")
+ .and_then(|suffix| suffix.strip_suffix(".tmp"))
+ .is_some_and(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_hexdigit()))
+}
+
+fn is_link(metadata: &Metadata) -> bool {
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::MetadataExt;
+ metadata.file_attributes() & 0x400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT
+ }
+ #[cfg(not(windows))]
+ {
+ metadata.file_type().is_symlink()
+ }
+}
+
+pub(super) fn cleanup_directory(directory: &Path) -> io::Result<usize> {
+ let metadata = match fs::symlink_metadata(directory) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(0),
+ Err(error) => return Err(error),
+ };
+ if !metadata.is_dir() || is_link(&metadata) {
+ return Ok(0);
+ }
+
+ let mut removed = 0;
+ for entry in fs::read_dir(directory)? {
+ let Ok(entry) = entry else { continue };
+ if !entry.file_name().to_str().is_some_and(is_replacement_temp_file) {
+ continue;
+ }
+ let path = entry.path();
+ let Ok(metadata) = fs::symlink_metadata(&path) else { continue };
+ // Never recurse or follow links; locked/read-only leftovers can be retried next launch.
+ if metadata.is_file() && !is_link(&metadata) && fs::remove_file(&path).is_ok() {
+ removed += 1;
+ }
+ }
+ Ok(removed)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ struct TestDirectory(PathBuf);
+
+ impl TestDirectory {
+ fn new() -> Self {
+ let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
+ let path = std::env::temp_dir().join(format!("dbx-mcp-cleanup-{}-{nonce}", std::process::id()));
+ fs::create_dir(&path).unwrap();
+ Self(path)
+ }
+ }
+
+ impl Drop for TestDirectory {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.0);
+ }
+ }
+
+ #[test]
+ fn recognizes_only_mcp_replacement_temp_names() {
+ for name in ["dbx-mcp.exe~RF8c73e4f.TMP", "DBX-MCP.EXE~rfAb123.tmp", "dbx-mcp.exe~RF1.TMP"] {
+ assert!(is_replacement_temp_file(name), "{name}");
+ }
+ for name in [
+ "dbx-mcp.exe",
+ ".dbx-mcp-version",
+ "dbx-mcp.exe~RF.TMP",
+ "dbx-mcp.exe~RFxyz.TMP",
+ "dbx-mcp.exe~RF123.TMP.bak",
+ "dbx-mcp.exe~RF123.TMP\n",
+ "other.exe~RF123.TMP",
+ "dbx-mcp.exe.tmp",
+ ] {
+ assert!(!is_replacement_temp_file(name), "{name}");
+ }
+ }
+
+ #[test]
+ fn removes_only_matching_files_without_recursing() {
+ let directory = TestDirectory::new();
+ let stale = ["dbx-mcp.exe~RF8c73e4f.TMP", "DBX-MCP.EXE~rfABC123.tmp"];
+ let preserved = ["dbx-mcp.exe", ".dbx-mcp-version", "other.tmp", "dbx-mcp.exe~RFxyz.TMP"];
+ for name in stale.iter().chain(preserved.iter()) {
+ fs::write(directory.0.join(name), b"original contents").unwrap();
+ }
+ let nested = directory.0.join("dbx-mcp.exe~RF123.TMP");
+ fs::create_dir(&nested).unwrap();
+ fs::write(nested.join(stale[0]), b"nested contents").unwrap();
+
+ assert_eq!(cleanup_directory(&directory.0).unwrap(), stale.len());
+ for name in stale {
+ assert!(!directory.0.join(name).exists());
+ }
+ for name in preserved {
+ assert_eq!(fs::read(directory.0.join(name)).unwrap(), b"original contents");
+ }
+ assert_eq!(fs::read(nested.join(stale[0])).unwrap(), b"nested contents");
+ assert_eq!(cleanup_directory(&directory.0).unwrap(), 0);
+ }
+
+ #[test]
+ fn missing_directory_is_a_noop() {
+ let directory = TestDirectory::new();
+ let missing = directory.0.join("missing");
+ assert_eq!(cleanup_directory(&missing).unwrap(), 0);
+ assert!(!missing.exists());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn skips_symlinked_files_and_directories() {
+ use std::os::unix::fs::symlink;
+
+ let directory = TestDirectory::new();
+ let target = TestDirectory::new();
+ let target_file = target.0.join("dbx-mcp.exe~RF123.TMP");
+ fs::write(&target_file, b"keep").unwrap();
+ let file_link = directory.0.join("dbx-mcp.exe~RFabc.TMP");
+ symlink(&target_file, &file_link).unwrap();
+ let dir_link = directory.0.join("linked-bin");
+ symlink(&target.0, &dir_link).unwrap();
+
+ assert_eq!(cleanup_directory(&directory.0).unwrap(), 0);
+ assert_eq!(cleanup_directory(&dir_link).unwrap(), 0);
+ assert!(file_link.symlink_metadata().unwrap().file_type().is_symlink());
+ assert_eq!(fs::read(&target_file).unwrap(), b"keep");
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn skips_locked_files_and_retries_after_release() {
+ use std::os::windows::fs::OpenOptionsExt;
+
+ let directory = TestDirectory::new();
+ let locked_path = directory.0.join("dbx-mcp.exe~RF123.TMP");
+ fs::write(&locked_path, b"locked").unwrap();
+ let locked = fs::OpenOptions::new().read(true).share_mode(0).open(&locked_path).unwrap();
+ let unlocked_path = directory.0.join("dbx-mcp.exe~RF456.TMP");
+ fs::write(&unlocked_path, b"unlocked").unwrap();
+
+ assert_eq!(cleanup_directory(&directory.0).unwrap(), 1);
+ assert!(locked_path.exists());
+ assert!(!unlocked_path.exists());
+ drop(locked);
+ assert_eq!(cleanup_directory(&directory.0).unwrap(), 1);
+ assert!(!locked_path.exists());
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index bdf237608e..79fc9bb19b 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2010,6 +2010,8 @@ pub fn run() {
open_plugin_install_deep_links(app.handle(), startup_plugin_install_links);
let app_handle = app.handle().clone();
+ #[cfg(target_os = "windows")]
+ tauri::async_runtime::spawn_blocking(commands::mcp::cleanup_mcp_installation_temp_files);
tauri::async_runtime::spawn(async move {
migration_gate.wait().await;
commands::mcp_bridge::start(app_handle, state, data_dir);