From 1055d983b27371dee6c8bfb712a21853fffaf602 Mon Sep 17 00:00:00 2001 From: a-akimov Date: Sun, 15 Nov 2026 13:11:54 +0100 Subject: [PATCH 1/5] Clean up on Ctrl-C in the Go, Rust and Ruby clients --- mcp-client-go/main.go | 55 +++++++++++++++++++++++++++++++------ mcp-client-ruby/client.rb | 4 +++ mcp-client-rust/src/main.rs | 24 ++++++++++++++-- 3 files changed, 71 insertions(+), 12 deletions(-) diff --git a/mcp-client-go/main.go b/mcp-client-go/main.go index 67daec37..75a8b89c 100644 --- a/mcp-client-go/main.go +++ b/mcp-client-go/main.go @@ -9,6 +9,7 @@ import ( "log" "os" "os/exec" + "os/signal" "strings" "github.com/anthropics/anthropic-sdk-go/v2" @@ -125,8 +126,10 @@ func (c *MCPClient) ConnectToServer(ctx context.Context, serverArgs []string) er return fmt.Errorf("no server command provided") } - // Create command to spawn server process - cmd := exec.CommandContext(ctx, serverArgs[0], serverArgs[1:]...) + // Create command to spawn server process. It isn't tied to ctx: cancelling + // ctx (Ctrl-C) would kill the server outright, and Cleanup should close the + // session first. + cmd := exec.Command(serverArgs[0], serverArgs[1:]...) // Create MCP client client := mcp.NewClient( @@ -346,17 +349,34 @@ func (c *MCPClient) ChatLoop(ctx context.Context) error { fmt.Println("\nMCP Client Started!") fmt.Println("Type your queries, 'clear' to forget the conversation, or 'quit' to exit.") + // Reading stdin blocks and can't be cancelled, so lines arrive on a + // channel and the loop also watches ctx, which Ctrl-C cancels. + lines := make(chan string) scanner := bufio.NewScanner(os.Stdin) + go func() { + defer close(lines) + for scanner.Scan() { + lines <- scanner.Text() + } + }() for { fmt.Print("\nQuery: ") - if !scanner.Scan() { - break // EOF + var line string + select { + case <-ctx.Done(): + fmt.Println() + return nil + case l, ok := <-lines: + if !ok { + return scanner.Err() // EOF + } + line = l } - query := strings.TrimSpace(scanner.Text()) + query := strings.TrimSpace(line) if strings.EqualFold(query, "quit") { - break + return nil } if strings.EqualFold(query, "clear") { c.messages = nil @@ -369,6 +389,10 @@ func (c *MCPClient) ChatLoop(ctx context.Context) error { historyLength := len(c.messages) response, err := c.ProcessQuery(ctx, query) + if ctx.Err() != nil { + fmt.Println() + return nil // Ctrl-C during a query + } if err != nil { // Drop the failed query so a follow-up doesn't send it again. c.messages = c.messages[:historyLength] @@ -378,8 +402,6 @@ func (c *MCPClient) ChatLoop(ctx context.Context) error { fmt.Printf("\n%s\n", response) } - - return scanner.Err() } func (c *MCPClient) Cleanup() error { @@ -405,9 +427,24 @@ func main() { log.Fatalf("Failed to create MCP client: %v", err) } - ctx := context.Background() + // Ctrl-C cancels ctx so the chat loop returns and Cleanup still runs. + // After the first one, restore the default so a second Ctrl-C force-quits. + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + go func() { + <-ctx.Done() + stop() + }() if err := client.ConnectToServer(ctx, serverArgs); err != nil { + // The session may already be open if listing tools failed. + if cleanupErr := client.Cleanup(); cleanupErr != nil { + log.Printf("Cleanup error: %v", cleanupErr) + } + if ctx.Err() != nil { + fmt.Println() + return // Ctrl-C while connecting + } log.Fatalf("Failed to connect to MCP server: %v", err) } diff --git a/mcp-client-ruby/client.rb b/mcp-client-ruby/client.rb index 5f6eae34..c2156fbb 100644 --- a/mcp-client-ruby/client.rb +++ b/mcp-client-ruby/client.rb @@ -241,6 +241,10 @@ def anthropic_client end client.chat_loop +rescue Interrupt + # Ctrl-C raises Interrupt, which isn't a StandardError, so `rescue => e` + # misses it. End quietly, as EOF does; `ensure` still cleans up. + puts rescue => e warn "Error: #{e.message}" exit 1 diff --git a/mcp-client-rust/src/main.rs b/mcp-client-rust/src/main.rs index d41544d1..b69127f9 100644 --- a/mcp-client-rust/src/main.rs +++ b/mcp-client-rust/src/main.rs @@ -469,7 +469,7 @@ async fn main() -> Result<()> { let mut client = MCPClient::new()?; - let result = async { + let session = async { client.connect_to_server(&server_args).await?; // Connecting and listing tools needs no credentials; querying them @@ -487,11 +487,29 @@ async fn main() -> Result<()> { } client.chat_loop().await - } - .await; + }; + + // Ctrl-C would otherwise kill the process before cleanup, so race it + // against the session; whichever finishes first, cleanup runs next. + let (result, interrupted) = tokio::select! { + result = session => (result, false), + _ = tokio::signal::ctrl_c() => { + println!(); + (Ok(()), true) + } + }; let cleanup_result = client.cleanup().await; + if interrupted { + // Tokio reads stdin on a blocking thread that can't be cancelled, and + // returning from main would wait for it, so exit directly. + if let Err(err) = cleanup_result { + eprintln!("Error: {err:#}"); + } + std::process::exit(0); + } + result?; cleanup_result?; From 0c7aaa7af9de7cdb4cb5e9d6cb94dc29d15ee3d4 Mon Sep 17 00:00:00 2001 From: a-akimov Date: Sun, 15 Nov 2026 14:31:30 +0100 Subject: [PATCH 2/5] Address feedback, improve tests, simplify comments --- mcp-client-go/main.go | 10 +-- mcp-client-python/client.py | 8 ++ mcp-client-ruby/client.rb | 3 +- mcp-client-rust/src/main.rs | 6 +- mcp-client-typescript/index.ts | 10 ++- tests/README.md | 6 +- tests/helpers/mock-mcp-server.ts | 12 +++ tests/helpers/tool-loop-test.ts | 145 ++++++++++++++++++++++++++++++- tests/smoke-test.sh | 2 +- 9 files changed, 179 insertions(+), 23 deletions(-) diff --git a/mcp-client-go/main.go b/mcp-client-go/main.go index 75a8b89c..19daa9d9 100644 --- a/mcp-client-go/main.go +++ b/mcp-client-go/main.go @@ -126,9 +126,7 @@ func (c *MCPClient) ConnectToServer(ctx context.Context, serverArgs []string) er return fmt.Errorf("no server command provided") } - // Create command to spawn server process. It isn't tied to ctx: cancelling - // ctx (Ctrl-C) would kill the server outright, and Cleanup should close the - // session first. + // Not tied to ctx: Ctrl-C would kill the server before Cleanup closes the session. cmd := exec.Command(serverArgs[0], serverArgs[1:]...) // Create MCP client @@ -349,8 +347,7 @@ func (c *MCPClient) ChatLoop(ctx context.Context) error { fmt.Println("\nMCP Client Started!") fmt.Println("Type your queries, 'clear' to forget the conversation, or 'quit' to exit.") - // Reading stdin blocks and can't be cancelled, so lines arrive on a - // channel and the loop also watches ctx, which Ctrl-C cancels. + // Reading stdin can't be cancelled, so read it on a goroutine and also watch ctx. lines := make(chan string) scanner := bufio.NewScanner(os.Stdin) go func() { @@ -427,8 +424,7 @@ func main() { log.Fatalf("Failed to create MCP client: %v", err) } - // Ctrl-C cancels ctx so the chat loop returns and Cleanup still runs. - // After the first one, restore the default so a second Ctrl-C force-quits. + // Ctrl-C cancels ctx so Cleanup still runs; a second Ctrl-C force-quits. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() go func() { diff --git a/mcp-client-python/client.py b/mcp-client-python/client.py index 351a0a68..f7cda79e 100644 --- a/mcp-client-python/client.py +++ b/mcp-client-python/client.py @@ -225,6 +225,14 @@ async def main(): return await client.chat_loop() + except (KeyboardInterrupt, asyncio.CancelledError): + # Ctrl-C. Undo the cancellation (3.11+) so cleanup can await, then exit + # directly: input() may still block a thread Python would wait for. + if sys.version_info >= (3, 11): + asyncio.current_task().uncancel() + await client.cleanup() + print(flush=True) + os._exit(0) finally: await client.cleanup() diff --git a/mcp-client-ruby/client.rb b/mcp-client-ruby/client.rb index c2156fbb..94686461 100644 --- a/mcp-client-ruby/client.rb +++ b/mcp-client-ruby/client.rb @@ -242,8 +242,7 @@ def anthropic_client client.chat_loop rescue Interrupt - # Ctrl-C raises Interrupt, which isn't a StandardError, so `rescue => e` - # misses it. End quietly, as EOF does; `ensure` still cleans up. + # Ctrl-C raises Interrupt, which `rescue => e` doesn't catch; `ensure` still cleans up. puts rescue => e warn "Error: #{e.message}" diff --git a/mcp-client-rust/src/main.rs b/mcp-client-rust/src/main.rs index b69127f9..c571c6f4 100644 --- a/mcp-client-rust/src/main.rs +++ b/mcp-client-rust/src/main.rs @@ -489,8 +489,7 @@ async fn main() -> Result<()> { client.chat_loop().await }; - // Ctrl-C would otherwise kill the process before cleanup, so race it - // against the session; whichever finishes first, cleanup runs next. + // Ctrl-C would otherwise kill the process before cleanup runs. let (result, interrupted) = tokio::select! { result = session => (result, false), _ = tokio::signal::ctrl_c() => { @@ -502,8 +501,7 @@ async fn main() -> Result<()> { let cleanup_result = client.cleanup().await; if interrupted { - // Tokio reads stdin on a blocking thread that can't be cancelled, and - // returning from main would wait for it, so exit directly. + // Returning would wait for tokio's blocking stdin read, so exit directly. if let Err(err) = cleanup_result { eprintln!("Error: {err:#}"); } diff --git a/mcp-client-typescript/index.ts b/mcp-client-typescript/index.ts index 6a41ae23..8007a9bd 100644 --- a/mcp-client-typescript/index.ts +++ b/mcp-client-typescript/index.ts @@ -120,11 +120,12 @@ class MCPClient { } } - async processQuery(query: string) { + async processQuery(query: string, signal?: AbortSignal) { /** * Process a query using Claude and available tools * * @param query - The user's input query + * @param signal - Aborts the query (Ctrl-C) * @returns Processed response as a string */ const historyLength = this.messages.length; @@ -138,7 +139,7 @@ class MCPClient { system: SYSTEM_PROMPT, messages: this.messages, tools: this.tools, - }); + }, { signal }); if (response.stop_reason === "refusal") { // Drop the refused query so a follow-up doesn't send it again. @@ -180,7 +181,7 @@ class MCPClient { result = await this.mcp.callTool({ name: toolUse.name, arguments: toolArgs, - }); + }, { signal }); } catch (error) { if (!(error instanceof ProtocolError)) throw error; // A rejected call is the model's mistake to correct, so it goes back @@ -256,9 +257,10 @@ class MCPClient { const historyLength = this.messages.length; try { - const response = await this.processQuery(message); + const response = await this.processQuery(message, ac.signal); console.log("\n" + response); } catch (e) { + if (ac.signal.aborted) break; // Drop the failed query so a follow-up doesn't send it again. this.messages.length = historyLength; console.log(`\nError: ${e instanceof Error ? e.message : String(e)}`); diff --git a/tests/README.md b/tests/README.md index 8fbdc89c..b7d29404 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. +Two more runs check Ctrl-C. The helper starts the client in a process group of its own and sends `SIGINT` to the whole group, as a terminal does: once at the `Query:` prompt, and once while the fake API holds the request for a query without answering it. stdin stays open, so only the signal can end the client. It must exit 0 within 15 seconds, print no backtrace (`Traceback`, `Interrupt`, `panic`) on stderr, and shut down the MCP server. A client that hangs on a blocked stdin read, or skips its cleanup, 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 @@ -112,6 +114,8 @@ It advertises two tools whose output schemas cover both shapes a structured resu Three more tools serve the tool-loop test's **tool result contents** query: `rejected_call` fails with a JSON-RPC error, `structured_only` returns `structuredContent` and an empty text block, and `non_text` returns an image, a text resource, an audio block, and an empty text block and resource. The values the test looks for are in `mock-values.ts`. +Given `--pid-file `, it writes its process ID there and ignores `SIGINT`. The tool-loop test's Ctrl-C runs use this to check that the client's cleanup, not the signal, ended the server. + **Usage**: ```bash @@ -120,7 +124,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. It then runs the client twice more to press Ctrl-C, appending `--pid-file` to the command so it reaches the mock server, and reports which checks failed along with the client's output. **Usage**: diff --git a/tests/helpers/mock-mcp-server.ts b/tests/helpers/mock-mcp-server.ts index 7bf72b68..e8f547a2 100644 --- a/tests/helpers/mock-mcp-server.ts +++ b/tests/helpers/mock-mcp-server.ts @@ -25,6 +25,8 @@ * exactly what is in this file. */ +import { writeFileSync } from "node:fs"; + import type { Implementation, Tool } from "@modelcontextprotocol/server"; import { Server } from "@modelcontextprotocol/server"; import { serveStdio } from "@modelcontextprotocol/server/stdio"; @@ -181,6 +183,16 @@ function buildServer(): Server { return server; } +// The tool-loop test's Ctrl-C runs pass `--pid-file ` so they can check +// afterwards that the client shut this server down. Ctrl-C in a terminal +// signals the whole foreground process group, this server included; those runs +// ignore it here, so only the client's cleanup can end the server. +const pidFileAt = process.argv.indexOf("--pid-file"); +if (pidFileAt >= 0) { + writeFileSync(process.argv[pidFileAt + 1], String(process.pid)); + process.on("SIGINT", () => {}); +} + serveStdio(buildServer); console.error("Mock MCP Server running on stdio"); diff --git a/tests/helpers/tool-loop-test.ts b/tests/helpers/tool-loop-test.ts index 8ffa8196..a8ed3d7c 100644 --- a/tests/helpers/tool-loop-test.ts +++ b/tests/helpers/tool-loop-test.ts @@ -50,11 +50,23 @@ * call, sends one tool_result per message, or gets the turn cap wrong fails * here and passes the no-key test. * + * Two more client processes check Ctrl-C. Each is started in a process group of + * its own, and SIGINT goes to the whole group, as a terminal sends it: once at + * the prompt, and once while the fake API holds a query's request without + * answering. stdin stays open, so only the signal can end the client. It must + * exit 0 within a few seconds, print no backtrace, and shut down the MCP server + * (the mock server ignores SIGINT in these runs, so the client's cleanup is + * what ends it). + * * Usage: node tool-loop-test.js [args...] */ -import { spawn } from "node:child_process"; +import { type ChildProcess, spawn } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import http from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; import { IMAGE_DATA, RESOURCE_TEXT, STRUCTURED_ONLY_VALUE } from "./mock-values.js"; /** Sonnet 5 thinks adaptively; the clients reserve this much for it. */ @@ -67,6 +79,10 @@ 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; +/** The query the fake API never answers, so Ctrl-C lands while it is pending. */ +const PENDING_QUERY = "pending query"; const QUERIES = { parallel: "parallel tools", @@ -230,11 +246,16 @@ function historyProblem(messages: Message[]): string | undefined { /** The scenario a request belongs to: named by its most recent user query. */ function scenarioOf(messages: Message[]): Scenario | undefined { + const query = latestQuery(messages); + return (Object.keys(QUERIES) as Scenario[]).find((key) => QUERIES[key] === query); +} + +/** The text of the most recent user query, skipping tool results. */ +function latestQuery(messages: Message[]): string | undefined { for (let i = messages.length - 1; i >= 0; i--) { const message = messages[i]; if (message.role !== "user" || toolResultsOf(message).length > 0) continue; - const text = textOf(message.content).trim(); - return (Object.keys(QUERIES) as Scenario[]).find((key) => QUERIES[key] === text); + return textOf(message.content).trim(); } return undefined; } @@ -500,6 +521,9 @@ function respond(request: Request): Reply { return { content: respondTurnLimit(scenario, n, request) }; } +/** Called when the fake API receives the pending query's request. */ +let onPendingRequest: (() => void) | undefined; + function startFakeApi(): Promise { const server = http.createServer((req, res) => { let body = ""; @@ -515,6 +539,11 @@ function startFakeApi(): Promise { res.writeHead(400).end(); return; } + if (latestQuery(request.messages) === PENDING_QUERY) { + // Never answered: the request stays open until the client goes away. + onPendingRequest?.(); + return; + } const { content, stopReason: scripted, error } = respond(request); res.setHeader("content-type", "application/json"); if (error) { @@ -585,6 +614,108 @@ function runClient( }); } +/** Resolves with the promise's value, or with "timeout" after `ms`. */ +function within(promise: Promise, ms: number): Promise { + return Promise.race([promise, sleep(ms, "timeout" as const)]); +} + +/** Sends a signal to the child's whole process group, as a terminal does. */ +function signalGroup(child: ChildProcess, signal: NodeJS.Signals) { + try { + process.kill(-child.pid!, signal); + } catch { + // The group is already gone. + } +} + +/** Whether a process is still running. */ +function isRunning(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +/** + * Starts the client, presses Ctrl-C at its prompt or while a query is pending, + * and checks that it exits cleanly and shuts the MCP server down. Returns the + * client's output if a check failed. + */ +async function runInterrupted( + command: string, + args: string[], + baseUrl: string, + during: "prompt" | "query", +): Promise { + const label = during === "prompt" ? "Ctrl-C at the prompt" : "Ctrl-C during a query"; + const failuresBefore = failures.length; + const dir = mkdtempSync(join(tmpdir(), "tool-loop-")); + const pidFile = join(dir, "server.pid"); + + // The last arguments start the MCP server, so --pid-file reaches it. + const child = spawn(command, [...args, "--pid-file", pidFile], { + env: { ...process.env, ANTHROPIC_BASE_URL: baseUrl, ANTHROPIC_API_KEY: API_KEY }, + stdio: ["pipe", "pipe", "pipe"], + detached: true, + }); + let stdout = ""; + let stderr = ""; + child.stderr.on("data", (chunk) => (stderr += chunk)); + const exited = new Promise((resolve) => { + child.on("error", (error) => { + failures.push(`${label}: could not start client: ${error.message}`); + resolve(null); + }); + child.on("close", (code) => resolve(code)); + }); + const prompted = new Promise((resolve) => { + child.stdout.on("data", (chunk) => { + stdout += chunk; + if (stdout.includes(PROMPT)) resolve(); + }); + }); + const ready = + during === "prompt" + ? prompted + : prompted.then(() => { + const pending = new Promise((resolve) => (onPendingRequest = resolve)); + child.stdin.write(`${PENDING_QUERY}\n`); + return pending; + }); + + const reached = await within(Promise.race([ready.then(() => true), exited.then(() => false)]), CLIENT_TIMEOUT_MS); + if (reached === true) { + signalGroup(child, "SIGINT"); + const code = await within(exited, INTERRUPT_TIMEOUT_MS); + if (code === "timeout") { + check(false, `${label}: client exited within ${INTERRUPT_TIMEOUT_MS / 1000}s`); + signalGroup(child, "SIGKILL"); + await exited; + } else { + check(code === 0, `${label}: client exited 0 (got ${code})`); + check( + !/Traceback|KeyboardInterrupt|Interrupt\b|panicked|^panic:/m.test(stderr), + `${label}: no backtrace on stderr`, + ); + // The server goes once the client closes its stdin; give it a moment. + const serverPid = Number(readFileSync(pidFile, "utf8")); + for (let i = 0; i < 20 && isRunning(serverPid); i++) await sleep(100); + check(!isRunning(serverPid), `${label}: the MCP server was shut down`); + } + } else { + check(false, `${label}: client ${during === "prompt" ? "showed its prompt" : "sent the query"}`); + signalGroup(child, "SIGKILL"); + await exited; + } + onPendingRequest = undefined; + rmSync(dir, { recursive: true, force: true }); + + if (failures.length === failuresBefore) return undefined; + return `--- ${label}: client stdout ---\n${stdout.trim()}\n--- ${label}: client stderr ---\n${stderr.trim()}`; +} + /** 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 +775,13 @@ 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); + const interrupted = [ + await runInterrupted(command, args, baseUrl, "prompt"), + await runInterrupted(command, args, baseUrl, "query"), + ].filter((output) => output !== undefined); + api.closeAllConnections(); + api.close(); if (failures.length === 0) { console.error(`✓ Tool loop correct (${passed} checks)`); @@ -657,6 +793,7 @@ async function main() { console.error(stdout.trim()); console.error("--- client stderr ---"); console.error(stderr.trim()); + for (const output of interrupted) console.error(output); process.exit(1); } diff --git a/tests/smoke-test.sh b/tests/smoke-test.sh index 1860e911..cb3deaf2 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 and during a query; see tests/README.md for what is checked. # Test: Python MCP client tool loop test_tool_loop_python() { From a8f58cabe5cff382998759f5b9231d8aa5867f78 Mon Sep 17 00:00:00 2001 From: a-akimov Date: Sun, 15 Nov 2026 14:50:41 +0100 Subject: [PATCH 3/5] Address feedback --- mcp-client-python/client.py | 10 +++++----- tests/helpers/tool-loop-test.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/mcp-client-python/client.py b/mcp-client-python/client.py index f7cda79e..c533c3bf 100644 --- a/mcp-client-python/client.py +++ b/mcp-client-python/client.py @@ -4,7 +4,7 @@ import sys from contextlib import AsyncExitStack -from anthropic import Anthropic +from anthropic import AsyncAnthropic from dotenv import load_dotenv from mcp import Client, MCPError, StdioServerParameters from mcp_types import CallToolResult, EmbeddedResource, ImageContent, Implementation, TextContent, TextResourceContents @@ -57,15 +57,15 @@ def __init__(self): # Initialize session and client objects self.client: Client | None = None self.exit_stack = AsyncExitStack() - self._anthropic: Anthropic | None = None + self._anthropic: AsyncAnthropic | None = None self.tools: list[dict] = [] self.messages: list[dict] = [] @property - def anthropic(self) -> Anthropic: + def anthropic(self) -> AsyncAnthropic: """Lazy-initialize Anthropic client when needed""" if self._anthropic is None: - self._anthropic = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) + self._anthropic = AsyncAnthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) return self._anthropic async def connect_to_server(self, server_command: list[str]): @@ -106,7 +106,7 @@ async def process_query(self, query: str) -> str: final_text = [] for turn in range(MAX_TOOL_TURNS + 1): - response = self.anthropic.messages.create( + response = await self.anthropic.messages.create( model=ANTHROPIC_MODEL, max_tokens=MAX_TOKENS, system=SYSTEM_PROMPT, diff --git a/tests/helpers/tool-loop-test.ts b/tests/helpers/tool-loop-test.ts index a8ed3d7c..bcb0d6cd 100644 --- a/tests/helpers/tool-loop-test.ts +++ b/tests/helpers/tool-loop-test.ts @@ -616,7 +616,7 @@ function runClient( /** Resolves with the promise's value, or with "timeout" after `ms`. */ function within(promise: Promise, ms: number): Promise { - return Promise.race([promise, sleep(ms, "timeout" as const)]); + return Promise.race([promise, sleep(ms, "timeout" as const, { ref: false })]); } /** Sends a signal to the child's whole process group, as a terminal does. */ From 41480ecd04bcd471311bcf6fa509f6288403643e Mon Sep 17 00:00:00 2001 From: a-akimov Date: Sun, 15 Nov 2026 18:45:20 +0100 Subject: [PATCH 4/5] Address feedback --- mcp-client-typescript/index.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/mcp-client-typescript/index.ts b/mcp-client-typescript/index.ts index 8007a9bd..ce22225b 100644 --- a/mcp-client-typescript/index.ts +++ b/mcp-client-typescript/index.ts @@ -232,7 +232,12 @@ class MCPClient { const ac = new AbortController(); const onClose = () => ac.abort(); rl.on("close", onClose); - const onSigint = () => rl.close(); + // Only SIGINT cancels a pending query; EOF after a query lets it finish. + const interrupt = new AbortController(); + const onSigint = () => { + interrupt.abort(); + rl.close(); + }; process.once("SIGINT", onSigint); try { @@ -257,10 +262,10 @@ class MCPClient { const historyLength = this.messages.length; try { - const response = await this.processQuery(message, ac.signal); + const response = await this.processQuery(message, interrupt.signal); console.log("\n" + response); } catch (e) { - if (ac.signal.aborted) break; + if (interrupt.signal.aborted) break; // Drop the failed query so a follow-up doesn't send it again. this.messages.length = historyLength; console.log(`\nError: ${e instanceof Error ? e.message : String(e)}`); From b7ed71558776cd96a07a138da3c81b02315f56e2 Mon Sep 17 00:00:00 2001 From: a-akimov Date: Sun, 15 Nov 2026 18:56:56 +0100 Subject: [PATCH 5/5] Address feedback --- mcp-client-typescript/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mcp-client-typescript/index.ts b/mcp-client-typescript/index.ts index ce22225b..2233c906 100644 --- a/mcp-client-typescript/index.ts +++ b/mcp-client-typescript/index.ts @@ -239,6 +239,8 @@ class MCPClient { rl.close(); }; process.once("SIGINT", onSigint); + // In a terminal, readline takes Ctrl-C itself instead of the process. + rl.on("SIGINT", onSigint); try { console.log("\nMCP Client Started!");