Shutdown listener? #888
Replies: 4 comments
|
The SDK currently does not expose an EOF/shutdown callback from For a process-based STDIO server, the practical solution is to own cleanup at the application boundary and register an idempotent JVM shutdown hook: var closed = new AtomicBoolean();
Runnable cleanup = () -> {
if (closed.compareAndSet(false, true)) {
serviceA.close();
serviceB.close();
}
};
Runtime.getRuntime().addShutdownHook(new Thread(cleanup, "mcp-cleanup"));This covers the normal MCP client lifecycle where the parent closes stdin and then terminates the child process. Also call the same One caveat: closing stdin alone does not force an arbitrary Java process to exit. If your other services own non-daemon threads, your main/application lifecycle must exit after EOF (or those services must be stopped by the cleanup path). A public termination signal on the transport would make this cleaner; today the provider only exposes The EOF behavior is in |
|
This is exactly the use case we have: our MCP server manages some non-daemon threads. A shutdown hook would not be triggered in this case. I still think we need a way to be notified that the SDK MCP server has finished |
|
You are right: a JVM shutdown hook alone does not solve this case. If stdin Current
Until the SDK exposes that signal, you can pass the transport a small final class EofNotifyingInputStream extends FilterInputStream {
private final Runnable onEof;
private final AtomicBoolean notified = new AtomicBoolean();
EofNotifyingInputStream(InputStream in, Runnable onEof) {
super(in);
this.onEof = onEof;
}
private int observe(int result) {
if (result == -1 && notified.compareAndSet(false, true)) {
onEof.run();
}
return result;
}
@Override
public int read() throws IOException {
return observe(super.read());
}
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
return observe(super.read(bytes, offset, length));
}
}Pass that stream instead of This is a workaround, not an ideal API. A public |
|
Yep, this is what I suggested in my original post, but this is a poor workaround. Please stop answering with AI-generated answers. I would happily get some feedback from the maintainers, and I'm eager to contribute if needed |
Uh oh!
There was an error while loading. Please reload this page.
Pre-submission Checklist
Question Category
Your Question
Hello,
When we start our MCP server in STDIO mode, we start a bunch of other services. When the stdin is closed, we need to shutdown those services. Would there be a way to listen to the shutdown via the SDK? Is this something you would consider? Or do we need to wrap stdin on our side to detect termination? We are using
StdioServerTransportProviderwithMcpServer.sync().Thanks
All reactions