diff --git a/mcp-client-go/README.md b/mcp-client-go/README.md index 9a28db4a..a9be0db3 100644 --- a/mcp-client-go/README.md +++ b/mcp-client-go/README.md @@ -32,7 +32,7 @@ go run . ../weather-server-go/weather go run . uv --directory ../weather-server-python run weather.py ``` -Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` to exit. +Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. diff --git a/mcp-client-python/README.md b/mcp-client-python/README.md index 024aef78..b73350f4 100644 --- a/mcp-client-python/README.md +++ b/mcp-client-python/README.md @@ -33,7 +33,7 @@ or, against the TypeScript server (build it first — see its README): uv run client.py node ../weather-server-typescript/build/index.js ``` -Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` to exit. +Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. diff --git a/mcp-client-python/client.py b/mcp-client-python/client.py index 351a0a68..fa566e90 100644 --- a/mcp-client-python/client.py +++ b/mcp-client-python/client.py @@ -1,6 +1,7 @@ import asyncio import json import os +import signal import sys from contextlib import AsyncExitStack @@ -182,7 +183,7 @@ async def chat_loop(self): # input() blocks, so keep it off the event loop. try: query = (await asyncio.to_thread(input, "\nQuery: ")).strip() - except (EOFError, KeyboardInterrupt): + except EOFError: break if query.lower() == "quit": @@ -230,4 +231,6 @@ async def main(): if __name__ == "__main__": + # Ctrl-C exits at once; otherwise Python waits for the thread blocked in input(). + signal.signal(signal.SIGINT, signal.SIG_DFL) asyncio.run(main()) diff --git a/mcp-client-ruby/README.md b/mcp-client-ruby/README.md index dea936f0..20792cb5 100644 --- a/mcp-client-ruby/README.md +++ b/mcp-client-ruby/README.md @@ -28,7 +28,7 @@ Pass the command that starts the server, and its arguments: bundle exec ruby client.rb ruby ../weather-server-ruby/weather.rb ``` -Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` to exit. +Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. diff --git a/mcp-client-ruby/client.rb b/mcp-client-ruby/client.rb index 5f6eae34..38067aaa 100644 --- a/mcp-client-ruby/client.rb +++ b/mcp-client-ruby/client.rb @@ -241,6 +241,9 @@ def anthropic_client end client.chat_loop +rescue Interrupt + # Ctrl-C: stop without a backtrace; `ensure` still cleans up. + puts rescue => e warn "Error: #{e.message}" exit 1 diff --git a/mcp-client-rust/README.md b/mcp-client-rust/README.md index 124c2101..532987b8 100644 --- a/mcp-client-rust/README.md +++ b/mcp-client-rust/README.md @@ -27,7 +27,7 @@ cargo run -- ../weather-server-rust/target/release/weather (Build the server first with `cargo build --release` in its directory.) -Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` to exit. +Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. diff --git a/mcp-client-typescript/README.md b/mcp-client-typescript/README.md index 796b1dec..bcdfe9b2 100644 --- a/mcp-client-typescript/README.md +++ b/mcp-client-typescript/README.md @@ -31,7 +31,7 @@ node build/index.js node ../weather-server-typescript/build/index.js (Build the server first — see its README.) -Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` to exit. +Type a question (for example, "What's the weather in Sacramento?") and Claude answers using the server's tools. The client keeps the conversation for the whole session, so a follow-up such as "And the alerts for that state?" works. Type `clear` to start a new conversation, or `quit` (or press Ctrl-D) to exit and shut the server down cleanly. Ctrl-C stops the client at once. Without an `ANTHROPIC_API_KEY`, the client still connects, prints the server's tools, and exits — useful for verifying the MCP wiring without credentials. diff --git a/mcp-client-typescript/index.ts b/mcp-client-typescript/index.ts index 6a41ae23..fc572ce4 100644 --- a/mcp-client-typescript/index.ts +++ b/mcp-client-typescript/index.ts @@ -227,12 +227,12 @@ class MCPClient { output: process.stdout, }); // rl.question() doesn't reject on stdin EOF on its own; wire its close - // event to an AbortSignal so EOF (Ctrl-D) and SIGINT both unblock it. + // event to an AbortSignal so EOF (Ctrl-D) unblocks it. const ac = new AbortController(); const onClose = () => ac.abort(); rl.on("close", onClose); - const onSigint = () => rl.close(); - process.once("SIGINT", onSigint); + // In a terminal, readline takes Ctrl-C itself; exit at once, as the other clients do. + rl.on("SIGINT", () => process.exit(130)); try { console.log("\nMCP Client Started!"); @@ -265,7 +265,6 @@ class MCPClient { } } } finally { - process.off("SIGINT", onSigint); rl.off("close", onClose); rl.close(); } diff --git a/tests/README.md b/tests/README.md index 8fbdc89c..84fa66c1 100644 --- a/tests/README.md +++ b/tests/README.md @@ -40,6 +40,8 @@ The fake API picks a script from the query text and checks every request the cli Finally the client must exit 0 on `quit`. A client that does one tool round and stops, drops `tools` on the follow-up call, sends one `tool_result` per message, gets the turn cap wrong, drops what a tool returned, forgets the conversation, keeps a failed query or an empty reply, or ignores `stop_reason` passes the no-key test and fails this one. +A second run checks Ctrl-C: the helper starts the client in a process group of its own, sends `SIGINT` to the group at the `Query:` prompt, as a terminal does, and leaves stdin open. The client must exit within 15 seconds without printing a backtrace. `quit` and EOF are the clean exits, so the exit status isn't checked; a client that hangs on a blocked stdin read, or never reaches the prompt, fails here. + All five clients are covered, including Rust: it calls the Messages API directly, so it honours `ANTHROPIC_BASE_URL` like the official SDKs do. ## Running Tests @@ -120,7 +122,7 @@ node tests/helpers/build/mock-mcp-server.js ### tool-loop-test.ts -Runs a client through the scripted tool loop described above. It starts the fake Anthropic API, spawns the client command with `ANTHROPIC_BASE_URL` and a dummy `ANTHROPIC_API_KEY` set, types the queries, a blank line and ` clear ` before the last one, and then `quit` at the client's prompts, and reports which checks failed along with the client's output. +Runs a client through the scripted tool loop described above. It starts the fake Anthropic API, spawns the client command with `ANTHROPIC_BASE_URL` and a dummy `ANTHROPIC_API_KEY` set, types the queries, a blank line and ` clear ` before the last one, and then `quit` at the client's prompts, then runs the client once more to press Ctrl-C at the prompt, and reports which checks failed along with the client's output. **Usage**: diff --git a/tests/helpers/tool-loop-test.ts b/tests/helpers/tool-loop-test.ts index 8ffa8196..3b7f61ce 100644 --- a/tests/helpers/tool-loop-test.ts +++ b/tests/helpers/tool-loop-test.ts @@ -50,6 +50,10 @@ * call, sends one tool_result per message, or gets the turn cap wrong fails * here and passes the no-key test. * + * A second client process checks that Ctrl-C at the prompt stops the client + * promptly and without a backtrace. `quit` and EOF are the clean exits; Ctrl-C + * only has to stop it, not hang on a blocked stdin read. + * * Usage: node tool-loop-test.js [args...] */ @@ -67,6 +71,8 @@ const STOP_NOTICE = `[Stopped after ${MAX_TOOL_TURNS} tool-use turns]`; /** Every client prints this before reading a query. */ const PROMPT = "Query: "; const CLIENT_TIMEOUT_MS = 180_000; +/** How long a client may take to exit after Ctrl-C. */ +const INTERRUPT_TIMEOUT_MS = 15_000; const QUERIES = { parallel: "parallel tools", @@ -585,6 +591,51 @@ function runClient( }); } +/** + * Starts the client, sends SIGINT to its process group at the prompt, as a + * terminal's Ctrl-C does, and checks that it exits without a backtrace. + * stdin stays open. + */ +function runInterrupted(command: string, args: string[], baseUrl: string): Promise { + return new Promise((resolve) => { + const child = spawn(command, args, { + env: { ...process.env, ANTHROPIC_BASE_URL: baseUrl, ANTHROPIC_API_KEY: API_KEY }, + stdio: ["pipe", "pipe", "pipe"], + detached: true, + }); + const kill = (signal: NodeJS.Signals) => { + try { + process.kill(-child.pid!, signal); + } catch { + // Already gone. + } + }; + let stdout = ""; + let stderr = ""; + let timer: NodeJS.Timeout | undefined; + const startup = setTimeout(() => kill("SIGKILL"), CLIENT_TIMEOUT_MS); + child.stdout.on("data", (chunk) => { + stdout += chunk; + if (timer || !stdout.includes(PROMPT)) return; + clearTimeout(startup); + kill("SIGINT"); + timer = setTimeout(() => { + check(false, `Ctrl-C: client exited within ${INTERRUPT_TIMEOUT_MS / 1000}s`); + kill("SIGKILL"); + }, INTERRUPT_TIMEOUT_MS); + }); + child.stderr.on("data", (chunk) => (stderr += chunk)); + child.on("close", () => { + clearTimeout(startup); + clearTimeout(timer); + if (!timer) check(false, "Ctrl-C: client showed its prompt"); + // Python's traceback, or Ruby's uncaught `...: Interrupt`. + check(!/Traceback|KeyboardInterrupt|: Interrupt\b/.test(stderr), "Ctrl-C: client printed no backtrace"); + resolve(); + }); + }); +} + /** Checks on the client's output once it has exited. */ function checkOutput(code: number | null, stdout: string) { check(code === 0, `client exited 0 (got ${code})`); @@ -644,8 +695,9 @@ async function main() { console.error(`Testing client tool loop: ${command} ${args.join(" ")}`); const { code, stdout, stderr } = await runClient(command, args, baseUrl); - api.close(); checkOutput(code, stdout); + await runInterrupted(command, args, baseUrl); + api.close(); if (failures.length === 0) { console.error(`✓ Tool loop correct (${passed} checks)`); diff --git a/tests/smoke-test.sh b/tests/smoke-test.sh index 1860e911..fcc0749a 100755 --- a/tests/smoke-test.sh +++ b/tests/smoke-test.sh @@ -182,7 +182,7 @@ test_mcp_client_rust() { # tool turns then an answer, tool calls past the turn limit, three tools whose # results need translating, a refusal, a tool call then an API error, an empty # reply, a reply cut off by max_tokens, and one after `clear`. It checks every request the client sends, the conversation -# history included; see tests/README.md for what is checked. +# history included, then presses Ctrl-C at the prompt; see tests/README.md for what is checked. # Test: Python MCP client tool loop test_tool_loop_python() {