Skip to content
Closed
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
51 changes: 42 additions & 9 deletions mcp-client-go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"log"
"os"
"os/exec"
"os/signal"
"strings"

"github.com/anthropics/anthropic-sdk-go/v2"
Expand Down Expand Up @@ -125,8 +126,8 @@ 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:]...)
// 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
client := mcp.NewClient(
Expand Down Expand Up @@ -346,17 +347,33 @@ 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 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() {
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
Expand All @@ -369,6 +386,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]
Expand All @@ -378,8 +399,6 @@ func (c *MCPClient) ChatLoop(ctx context.Context) error {

fmt.Printf("\n%s\n", response)
}

return scanner.Err()
}

func (c *MCPClient) Cleanup() error {
Expand All @@ -405,9 +424,23 @@ func main() {
log.Fatalf("Failed to create MCP client: %v", err)
}

ctx := context.Background()
// 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() {
<-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)
}

Expand Down
18 changes: 13 additions & 5 deletions mcp-client-python/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]):
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -225,6 +225,14 @@ async def main():
return

await client.chat_loop()
except (KeyboardInterrupt, asyncio.CancelledError):
Comment thread
Copilot marked this conversation as resolved.
Resolved
# 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()

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 raises Interrupt, which `rescue => e` doesn't catch; `ensure` still cleans up.
puts
rescue => e
warn "Error: #{e.message}"
exit 1
Expand Down
22 changes: 19 additions & 3 deletions mcp-client-rust/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -487,11 +487,27 @@ async fn main() -> Result<()> {
}

client.chat_loop().await
}
.await;
};

// Ctrl-C would otherwise kill the process before cleanup runs.
let (result, interrupted) = tokio::select! {
result = session => (result, false),
_ = tokio::signal::ctrl_c() => {
println!();
(Ok(()), true)
}
};

let cleanup_result = client.cleanup().await;

if interrupted {
// Returning would wait for tokio's blocking stdin read, so exit directly.
if let Err(err) = cleanup_result {
eprintln!("Error: {err:#}");
}
std::process::exit(0);
Comment thread
a-akimov marked this conversation as resolved.
Resolved
}

result?;
cleanup_result?;

Expand Down
19 changes: 14 additions & 5 deletions mcp-client-typescript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -231,8 +232,15 @@ 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);
Comment thread
a-akimov marked this conversation as resolved.
Resolved
// In a terminal, readline takes Ctrl-C itself instead of the process.
rl.on("SIGINT", onSigint);

try {
console.log("\nMCP Client Started!");
Expand All @@ -256,9 +264,10 @@ class MCPClient {

const historyLength = this.messages.length;
try {
const response = await this.processQuery(message);
const response = await this.processQuery(message, interrupt.signal);
console.log("\n" + response);
} catch (e) {
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)}`);
Expand Down
6 changes: 5 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.

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
Expand Down Expand Up @@ -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 <path>`, 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
Expand All @@ -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**:

Expand Down
12 changes: 12 additions & 0 deletions tests/helpers/mock-mcp-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -181,6 +183,16 @@ function buildServer(): Server {
return server;
}

// The tool-loop test's Ctrl-C runs pass `--pid-file <path>` 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");

Expand Down
Loading
Loading