Windows: a tool's normal closing steps do not run when Copilot stops it

Aberta
#2,893 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
20/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Ativa
Stack de tecnologia
javascript, nodejs, python
Domínio
devtools

Direção de pesquisa

Start by running reproduce.py with server.cjs on Windows to confirm the three cases: direct EOF exits with code 0 and both notes, while stop_server and client.stop() exit with code 1 and no closing notes. The gap is in how the Copilot runtime stops MCP child processes, not in server.cjs, so look at the Python SDK's mcp.stop_server and client.stop paths. Done means a graceful stop lets process.on('exit') and the stdin-end handler run before any forced kill.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

What goes wrong

On Windows, a small tool connected to Copilot works correctly while it is running.
But when I ask Copilot to stop it, the tool closes without running the code it
normally runs before closing.

If I close the tool's incoming connection myself, that same code runs and the
tool closes normally.

Small example

I made a small tool that returns the number 2. It also writes a note to a file
when it starts, when it is used, when its connection closes, and when the program
closes.

The tool starts and returns the correct answer in all three cases:

How I stop it Does its normal closing code run?
Close its incoming connection directly Yes
Ask Copilot to stop No
Ask Copilot to stop only this tool No

This example does not call an AI model or use any other connected tools.

Why this matters

Tools may need their closing code to save information or release connections.
They cannot rely on that code running when Copilot stops them this way.

What should happen

Copilot should give the tool a chance to close normally first. If the tool still
does not close after a reasonable wait, Copilot can force it to end.

Please check how Copilot stops connected tools on Windows. The example shows
the difference, but does not prove exactly which part of Copilot causes it.

Version details and the two files needed to try the example
Versions used
  • Windows on ARM64.
  • Python 3.11.15, x64.
  • Node.js 24.22.2, ARM64.
  • Official Copilot program version 1.0.105-1, Windows ARM64.
  • Python package 1.0.28+local.fa108e71, built from the public
    v1.0.28 source at fa108e71ee3025663e0dac20f2a071055d3a6b14.

For the Python package, only the version label and the normal build step that
records the Copilot version were changed. There were no changes to how it starts,
stops, or communicates with programs. I did not test the already-packaged Python
download.

The official Copilot download had this SHA-256 file identifier:
9b1f5033f0b07b19575639d93b77b04cda9b9bdb39d934ffd2f179206d519167.

How to try it

Save server.cjs and reproduce.py beside each other. In the command below,
replace the example locations with the locations of Node.js and the Copilot
program on your computer. Keep runtime.node beside copilot-runtime.exe.

python .\reproduce.py --node 'C:\path\to\node.exe' --runtime 'C:\path\to\copilot-runtime.exe' --output '.\shutdown-output'

The output folder must not already exist. The script prints what happened and
saves a separate record for each of the three cases.

More detail about what was observed

When the connection is closed directly, Windows reports a normal ending
(result 0), and both closing notes are saved. When Copilot stops the tool,
Windows reports result 1, and neither closing note is saved.

The tool writes each note immediately and asks the operating system to save it
before continuing. Both Copilot cases record that the tool started, was ready,
and was used. Neither records that the connection ended or that the program's
normal closing code ran.

The tool itself only asks to end with result 0, shortly after its connection
closes. It has no instruction to end with result 1.

When asking Copilot to stop only the tool, the script checks that the tool has
ended before it asks Copilot itself to stop. It follows the exact program that
was started, rather than looking for any program with the same name.

Copilot starts Node.js directly. There is no extra startup script between them.
The example does not ask Copilot to restart the tool. Both ways of starting it
complete the initial connection setup and use the same tool.

server.cjs
const fs = require("node:fs");
const readline = require("node:readline");
const output = process.argv[2];

function record(phase, detail = {}) {
    const fd = fs.openSync(output, "a");
    try {
        fs.writeSync(fd, JSON.stringify({ phase, ...detail }) + "\n");
        fs.fsyncSync(fd);
    } finally {
        fs.closeSync(fd);
    }
}

record("started");
process.once("exit", (code) => record("exit", { code }));
process.stdin.once("end", () => {
    record("stdin-end");
    setTimeout(() => process.exit(0), 25);
});
setImmediate(() => record("event-loop-ready"));
readline.createInterface({ input: process.stdin }).on("line", (line) => {
    const request = JSON.parse(line);
    if (request.id === undefined) return;
    let result;
    if (request.method === "initialize") {
        result = {
            protocolVersion: request.params.protocolVersion,
            capabilities: { tools: {} },
            serverInfo: { name: "shutdown-probe", version: "1.0.0" },
        };
    } else if (request.method === "ping") {
        result = {};
    } else if (request.method === "tools/list") {
        result = { tools: [{
            name: "probe",
            description: "Return this process ID and the value two.",
            inputSchema: { type: "object", properties: {}, additionalProperties: false },
        }] };
    } else if (request.method === "tools/call" && request.params.name === "probe") {
        record("tool-called");
        result = { content: [{ type: "text", text: "PROBE:" + JSON.stringify({
            pid: process.pid, value: 2,
        }) }] };
    } else {
        process.stdout.write(JSON.stringify({
            jsonrpc: "2.0", id: request.id,
            error: { code: -32601, message: "Unsupported request" },
        }) + "\n");
        return;
    }
    process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) + "\n");
});
reproduce.py
"""Windows-only MCP shutdown control; no model requests or external services."""

import argparse
import asyncio
import ctypes
from ctypes import wintypes
import json
import os
from pathlib import Path
import re
import sys
from unittest.mock import patch

from copilot import CopilotClient, CopilotSession, PermissionHandler, RuntimeConnection
from copilot.generated.rpc import MCPStopServerRequest, ToolsExecuteRequest


if sys.platform != "win32":
    raise SystemExit("This reproduction uses Windows process handles.")

kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
kernel.OpenProcess.restype = wintypes.HANDLE
kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
kernel.WaitForSingleObject.restype = wintypes.DWORD
kernel.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
kernel.GetExitCodeProcess.restype = wintypes.BOOL
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
kernel.CloseHandle.restype = wintypes.BOOL


def retain(pid):
    handle = kernel.OpenProcess(0x00101000, False, pid)
    if not handle:
        raise ctypes.WinError(ctypes.get_last_error())
    return handle


async def exit_code(handle):
    result = await asyncio.to_thread(kernel.WaitForSingleObject, handle, 15000)
    if result == 0x102:
        raise TimeoutError("The exact child did not exit within 15 seconds.")
    if result != 0:
        raise ctypes.WinError(ctypes.get_last_error())
    code = wintypes.DWORD()
    if not kernel.GetExitCodeProcess(handle, ctypes.byref(code)):
        raise ctypes.WinError(ctypes.get_last_error())
    return code.value


async def direct(node, server, directory):
    witness = directory / "events.jsonl"
    with (directory / "stderr.log").open("wb") as errors:
        process = await asyncio.create_subprocess_exec(
            str(node), str(server), str(witness),
            cwd=directory, env={**os.environ, "NODE_OPTIONS": ""},
            stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
            stderr=errors,
        )
        requests = [
            {"method": "initialize", "params": {
                "protocolVersion": "2025-11-25", "capabilities": {},
                "clientInfo": {"name": "shutdown-probe", "version": "1.0.0"},
            }},
            {"method": "tools/list", "params": {}},
            {"method": "tools/call", "params": {"name": "probe", "arguments": {}}},
        ]
        for number, request in enumerate(requests, 1):
            process.stdin.write((json.dumps({
                "jsonrpc": "2.0", "id": number, **request,
            }) + "\n").encode())
            await process.stdin.drain()
            reply = json.loads(await asyncio.wait_for(process.stdout.readline(), 15))
            assert reply["id"] == number and "error" not in reply, reply
            if number == 1:
                process.stdin.write((json.dumps({
                    "jsonrpc": "2.0", "method": "notifications/initialized",
                }) + "\n").encode())
                await process.stdin.drain()
        assert "PROBE:" in json.dumps(reply), reply
        process.stdin.close()
        await process.stdin.wait_closed()
        return await asyncio.wait_for(process.wait(), 15)


async def through_sdk(node, server, runtime, directory, explicit):
    witness = directory / "events.jsonl"
    client = CopilotClient(
        mode="empty", connection=RuntimeConnection.for_stdio(path=str(runtime)),
        base_directory=str(directory / "storage"), working_directory=str(directory),
    )
    handle = None
    try:
        try:
            await client.start()
            session = await client.create_session(
                available_tools=["mcp:*"],
                mcp_servers={"shutdown-probe": {
                    "type": "local", "command": str(node),
                    "args": [str(server), str(witness)], "cwd": str(directory),
                    "env": {"NODE_OPTIONS": ""}, "tools": ["*"],
                }},
                on_permission_request=PermissionHandler.approve_all,
            )
            await session.rpc.tools.initialize_and_validate()
            metadata = await session.rpc.tools.get_current_metadata()
            names = [tool.name for tool in metadata.tools or []]
            names = [name for name in names
                     if "shutdown-probe" in name and name.endswith("probe")]
            assert len(names) == 1, names
            result = await session.rpc.tools.execute(
                ToolsExecuteRequest(name=names[0], arguments={}), timeout=30
            )
            if hasattr(result, "to_dict"):
                result = result.to_dict()
            assert result["resultType"] == "success", result
            match = re.search(r"PROBE:(\{[^}]+\})", result["textResultForLlm"])
            assert match, result
            identity = json.loads(match[1])
            assert identity["value"] == 2, identity
            handle = retain(identity["pid"])
            await asyncio.sleep(0.5)
            if explicit:
                await session.rpc.mcp.stop_server(
                    MCPStopServerRequest("shutdown-probe"), timeout=30
                )
                code = await exit_code(handle)
        finally:
            await client.stop()
        return code if explicit else await exit_code(handle)
    finally:
        if handle is not None and not kernel.CloseHandle(handle):
            raise ctypes.WinError(ctypes.get_last_error())


async def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--node", required=True, type=Path)
    parser.add_argument("--runtime", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    args = parser.parse_args()
    node = args.node.resolve(strict=True)
    runtime = args.runtime.resolve(strict=True)
    server = Path(__file__).with_name("server.cjs").resolve(strict=True)
    root = args.output.resolve()
    root.mkdir(parents=True, exist_ok=False)
    results = []
    for route in ("direct-eof", "sdk-stop", "sdk-stop-server"):
        directory = root / route
        directory.mkdir()
        if route == "direct-eof":
            code = await direct(node, server, directory)
        else:
            code = await through_sdk(
                node, server, runtime, directory, explicit=route == "sdk-stop-server"
            )
        records = [json.loads(line) for line in
                   (directory / "events.jsonl").read_text().splitlines()]
        results.append({"route": route, "exit_code": code, "events": records})
        (root / "results.json").write_text(json.dumps(results, indent=2))
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    with (
        patch.object(CopilotSession, "send", side_effect=AssertionError("Model calls forbidden")),
        patch.object(CopilotSession, "send_and_wait", side_effect=AssertionError("Model calls forbidden")),
    ):
        asyncio.run(main())
Other reports

github/copilot-sdk#1381
describes an earlier problem with stopping Copilot too quickly. Its fix is
already present in the Python package used here.

github/copilot-sdk#1804
and github/copilot-cli#4972
describe extra programs staying open after a startup script ends. This example
is different: Copilot starts the tool directly, and the tool ends without
running its normal closing code.

The connection standard also recommends letting a tool close normally before
forcing it to end:
https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#shutdown

Linguagem predominante
Java
Estrelas
10.7k
Forks
1.5k
Métricas de merge de PRs
Nenhum PR com merge em 30d

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de github/copilot-sdk

Todas as issues de github/copilot-sdk

Issues semelhantes

Mais issues de Java

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.