-
Notifications
You must be signed in to change notification settings - Fork 413
fix: Do not exit MCP if the parent process is alive #770
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+351
−12
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,12 @@ | ||
| mod cursor; | ||
| mod healthcheck; | ||
| mod output; | ||
| mod parent; | ||
| mod server; | ||
| mod update_check; | ||
|
|
||
| use std::time::{Duration, SystemTime}; | ||
|
|
||
| use clap::Parser; | ||
| use fff::file_picker::FilePicker; | ||
| use fff::frecency::FrecencyTracker; | ||
|
|
@@ -92,7 +95,7 @@ pub const MCP_INSTRUCTIONS: &str = concat!( | |
| " !generated/ - exclude generated code", | ||
| ); | ||
|
|
||
| /// FFF MCP Server -- a high performance & accuracy file finder for AI code assistants. | ||
| /// FFF MCP Server - a high performance & accuracy file finder for AI code assistants. | ||
| #[derive(Parser)] | ||
| #[command(name = "fff-mcp", version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("FFF_GIT_HASH"), ")"))] | ||
| pub(crate) struct Args { | ||
|
|
@@ -131,6 +134,7 @@ pub(crate) struct Args { | |
|
|
||
| /// Disable the content index built after the initial scan. | ||
| /// This makes grep calls slower but consumes less RAM (recommended to not turn off) | ||
| #[arg(long = "no-content-indexing")] | ||
| no_content_indexing: bool, | ||
|
|
||
| /// Explicitly enable content indexing even when `--no-warmup` is set. | ||
|
|
@@ -158,11 +162,12 @@ pub(crate) struct Args { | |
| #[arg(long = "healthcheck")] | ||
| pub(crate) healthcheck: bool, | ||
|
|
||
| /// Exit after this many seconds of inactivity. 0 = never exit. | ||
| /// Timeout of inactivity after which fff mcp will be exited. Even if the parent process | ||
| /// is alive we don't want to occupy resources on index and file watches if fff is unused | ||
| #[arg( | ||
| long = "idle-timeout-secs", | ||
| env = "FFF_MCP_IDLE_TIMEOUT_SECS", | ||
| default_value_t = 900 | ||
| default_value_t = 60 * 60 | ||
| )] | ||
| idle_timeout_secs: u64, | ||
| } | ||
|
|
@@ -317,9 +322,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
| } | ||
| }; | ||
|
|
||
| if idle_timeout_secs > 0 { | ||
| let parent_watcher = parent::ParentWatcher::new(); | ||
| match &parent_watcher { | ||
| Some(watcher) => tracing::info!( | ||
| "Watching parent process (pid {}); will exit when it dies", | ||
| watcher.parent_pid() | ||
| ), | ||
| None => tracing::warn!( | ||
| "Parent process liveness detection unavailable; idle timeout will exit unconditionally" | ||
| ), | ||
| } | ||
|
|
||
| if idle_timeout_secs > 0 || parent_watcher.is_some() { | ||
| last_activity.store( | ||
| std::time::SystemTime::now() | ||
| SystemTime::now() | ||
| .duration_since(std::time::UNIX_EPOCH) | ||
| .map(|d| d.as_secs()) | ||
| .unwrap_or(0), | ||
|
|
@@ -328,22 +344,36 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
|
|
||
| let last_activity_for_watchdog = last_activity.clone(); | ||
| tokio::spawn(async move { | ||
| let tick = std::time::Duration::from_secs(60); | ||
| let tick = watchdog_interval(); | ||
| loop { | ||
| tokio::time::sleep(tick).await; | ||
|
|
||
| if let Some(ref watcher) = parent_watcher { | ||
| if !watcher.parent_alive() { | ||
| tracing::info!( | ||
| "Parent process (pid {}) exited, shutting down", | ||
| watcher.parent_pid() | ||
| ); | ||
| flush_logs_and_exit().await; | ||
| } | ||
| // Parent is alive: it owns our lifecycle, never exit on idle | ||
| // Clients like Codex do not restart MCP servers @see #703 | ||
| continue; | ||
| } | ||
|
|
||
| if idle_timeout_secs == 0 { | ||
| continue; | ||
| } | ||
|
|
||
| let now = std::time::SystemTime::now() | ||
| .duration_since(std::time::UNIX_EPOCH) | ||
| .map(|d| d.as_secs()) | ||
| .unwrap_or(0); | ||
|
|
||
| let last = last_activity_for_watchdog.load(std::sync::atomic::Ordering::Relaxed); | ||
| if now.saturating_sub(last) >= idle_timeout_secs { | ||
| tracing::info!( | ||
| "Exiting after {}s of inactivity (idle_timeout_secs={})", | ||
| now.saturating_sub(last), | ||
| idle_timeout_secs | ||
| ); | ||
| std::process::exit(0); | ||
| tracing::info!(?idle_timeout_secs, "Exiting due to inactivity",); | ||
| flush_logs_and_exit().await; | ||
| } | ||
| } | ||
| }); | ||
|
|
@@ -370,3 +400,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| // Tracing appender is non blocking, to get full log give it some time before hard exit | ||
| async fn flush_logs_and_exit() -> ! { | ||
|
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. here brother |
||
| tokio::time::sleep(std::time::Duration::from_millis(250)).await; | ||
| std::process::exit(0); | ||
| } | ||
|
|
||
| fn watchdog_interval() -> Duration { | ||
| if cfg!(debug_assertions) | ||
| && let Some(milliseconds) = std::env::var("FFF_MCP_TEST_WATCHDOG_INTERVAL_MS") | ||
| .ok() | ||
| .and_then(|value| value.parse().ok()) | ||
| { | ||
| return Duration::from_millis(milliseconds); | ||
| } | ||
| Duration::from_secs(60) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| #[cfg(unix)] | ||
| mod imp { | ||
| pub struct ParentWatcher { | ||
| ppid: u32, | ||
| } | ||
|
|
||
| impl ParentWatcher { | ||
| pub fn new() -> Option<Self> { | ||
| let ppid = std::os::unix::process::parent_id(); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| // ppid <= 1 means we were spawned by init and can't detect death | ||
| (ppid > 1).then_some(Self { ppid }) | ||
| } | ||
|
|
||
| pub fn parent_pid(&self) -> u32 { | ||
| self.ppid | ||
| } | ||
|
|
||
| // When the parent dies the kernel reparents us, so getppid() changes. | ||
| // Race-free and immune to PID reuse, unlike kill(ppid, 0). | ||
| pub fn parent_alive(&self) -> bool { | ||
| std::os::unix::process::parent_id() == self.ppid | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(windows)] | ||
| mod imp { | ||
| use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, WAIT_TIMEOUT}; | ||
| use windows_sys::Win32::System::Diagnostics::ToolHelp::{ | ||
| CreateToolhelp32Snapshot, PROCESSENTRY32, Process32First, Process32Next, TH32CS_SNAPPROCESS, | ||
| }; | ||
| use windows_sys::Win32::System::Threading::{ | ||
| GetCurrentProcessId, OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject, | ||
| }; | ||
|
|
||
| pub struct ParentWatcher { | ||
| handle: HANDLE, | ||
| ppid: u32, | ||
| } | ||
|
|
||
| // HANDLE is a raw pointer; it is only ever used via WaitForSingleObject | ||
| // which is thread-safe, so moving/sharing the watcher across threads is fine. | ||
| unsafe impl Send for ParentWatcher {} | ||
| unsafe impl Sync for ParentWatcher {} | ||
|
|
||
| impl ParentWatcher { | ||
| pub fn new() -> Option<Self> { | ||
| let ppid = parent_pid_of_current()?; | ||
| let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, ppid) }; | ||
| if handle.is_null() { | ||
| return None; | ||
| } | ||
| // Holding the handle pins the PID, preventing reuse for the process lifetime | ||
| Some(Self { handle, ppid }) | ||
| } | ||
|
|
||
| pub fn parent_pid(&self) -> u32 { | ||
| self.ppid | ||
| } | ||
|
|
||
| pub fn parent_alive(&self) -> bool { | ||
| unsafe { WaitForSingleObject(self.handle, 0) == WAIT_TIMEOUT } | ||
| } | ||
| } | ||
|
|
||
| impl Drop for ParentWatcher { | ||
| fn drop(&mut self) { | ||
| unsafe { CloseHandle(self.handle) }; | ||
| } | ||
| } | ||
|
|
||
| fn parent_pid_of_current() -> Option<u32> { | ||
| unsafe { | ||
| let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); | ||
| if snapshot == INVALID_HANDLE_VALUE { | ||
| return None; | ||
| } | ||
| let mut entry: PROCESSENTRY32 = std::mem::zeroed(); | ||
| entry.dwSize = std::mem::size_of::<PROCESSENTRY32>() as u32; | ||
| let current = GetCurrentProcessId(); | ||
| let mut found = None; | ||
| if Process32First(snapshot, &mut entry) != 0 { | ||
| loop { | ||
| if entry.th32ProcessID == current { | ||
| found = Some(entry.th32ParentProcessID); | ||
| break; | ||
| } | ||
| if Process32Next(snapshot, &mut entry) == 0 { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| CloseHandle(snapshot); | ||
| found | ||
| } | ||
| } | ||
| } | ||
|
|
||
| pub use imp::ParentWatcher; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.