Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mcp-client-go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion mcp-client-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 4 additions & 1 deletion mcp-client-python/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import json
import os
import signal
import sys
from contextlib import AsyncExitStack

Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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())
2 changes: 1 addition & 1 deletion mcp-client-ruby/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions mcp-client-ruby/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ def anthropic_client
end

client.chat_loop
rescue Interrupt
# Ctrl-C: stop without a backtrace; `ensure` still cleans up.
puts
Comment thread
a-akimov marked this conversation as resolved.
Resolved
rescue => e
warn "Error: #{e.message}"
exit 1
Expand Down
2 changes: 1 addition & 1 deletion mcp-client-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion mcp-client-typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 3 additions & 4 deletions mcp-client-typescript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!");
Expand Down Expand Up @@ -265,7 +265,6 @@ class MCPClient {
}
}
} finally {
process.off("SIGINT", onSigint);
rl.off("close", onClose);
rl.close();
}
Expand Down
4 changes: 3 additions & 1 deletion tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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**:

Expand Down
54 changes: 53 additions & 1 deletion tests/helpers/tool-loop-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <client command> [args...]
*/

Expand All @@ -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",
Expand Down Expand Up @@ -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<void> {
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"],
Comment thread
a-akimov marked this conversation as resolved.
Resolved
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})`);
Expand Down Expand Up @@ -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)`);
Expand Down
2 changes: 1 addition & 1 deletion tests/smoke-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading