Follow Discord
Sweep 20 Nov 2026 · 19:55Z Build v2.1.330 547 read Stable v2.1.323 Latest v2.1.330 Next v2.1.330 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One change · mcp

Build an MCP client changeddocs/draft/develop/build-client

Nearest release: v2.1.319, published 13 hours before upstream edited the page. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.

Upstream edited this page at 6 Nov 2026 14:17 UTC, give or take a minute or two: the time comes from Anthropic’s own sitemap rather than from a commit. This site recorded the change at 6 Nov 2026 14:37 UTC.

Upstream edited
Recorded here
Lines+329added
Lines−172removed
From line 105 where the diff opens
First seen 26 Aug 2026 this site's first read of the page
Recorded edits10to this page, all time

The whole hunk

from line 105, old and new numbered
/
lines

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 105
105105> load_dotenv() # load environment variables from .env
106106>
107107> MODEL = "claude-opus-5"
108> # The model thinks adaptively unless told otherwise, and max_tokens caps thinking
109> # plus the reply, so leave room for both.
110> MAX_TOKENS = 10000
111> MAX_TOOL_TURNS = 10
108112> anthropic = Anthropic()
109113> ```
110114>
from line 158
154158> "input_schema": tool.input_schema
155159> } for tool in tool_list.tools]
156160>
161> final_text = []
162>
157163> # Initial Claude API call
158164> response = anthropic.messages.create(
159165> model=MODEL,
160> max_tokens=1000,
166> max_tokens=MAX_TOKENS,
161167> messages=messages,
162168> tools=available_tools
163169> )
164170>
165> # Process response and handle tool calls
166> final_text = []
167> tool_results = []
168>
169> for content in response.content:
170> if content.type == 'text':
171> final_text.append(content.text)
172> elif content.type == 'tool_use':
173> tool_name = content.name
174> tool_args = content.input
175>
171> for _ in range(MAX_TOOL_TURNS):
172> # Process response and collect tool calls
173> tool_uses = []
174> for content in response.content:
175> if content.type == 'text':
176> final_text.append(content.text)
177> elif content.type == 'tool_use':
178> tool_uses.append(content)
179>
180> if not tool_uses:
181> return "\n".join(final_text)
182>
183> tool_results = []
184> for tool_use in tool_uses:
176185> # Execute tool call
177> result = await client.call_tool(tool_name, tool_args)
178> final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
186> result = await client.call_tool(tool_use.name, tool_use.input)
187> final_text.append(f"[Calling tool {tool_use.name} with args {tool_use.input}]")
179188>
180189> tool_results.append({
181190> "type": "tool_result",
182> "tool_use_id": content.id,
191> "tool_use_id": tool_use.id,
183192> "content": "\n".join(
184193> block.text
185194> for block in result.content
from line 197
188197> "is_error": result.is_error
189198> })
190199>
191> if tool_results:
200> # Replay the assistant turn as returned, then answer all of its
201> # tool calls in a single user message
192202> messages.append({"role": "assistant", "content": response.content})
193203> messages.append({"role": "user", "content": tool_results})
194204>
195205> # Get next response from Claude
196206> response = anthropic.messages.create(
197207> model=MODEL,
198> max_tokens=1000,
208> max_tokens=MAX_TOKENS,
199209> messages=messages,
200210> tools=available_tools
201211> )
202212>
203> for content in response.content:
204> if content.type == 'text':
205> final_text.append(content.text)
206>
213> # The turn cap was hit. Keep the last response's text. If it asked for
214> # more tools, say they were not run.
215> final_text.extend(content.text for content in response.content if content.type == 'text')
216> if any(content.type == 'tool_use' for content in response.content):
217> final_text.append(f"[Stopped after {MAX_TOOL_TURNS} tool-use turns]")
207218> return "\n".join(final_text)
208219> ```
209220>
210221> `call_tool` returns a `CallToolResult`. Its `content` is a list of blocks, which is why we narrow to `TextContent` before reading `.text`. A tool that raises does not raise here: it answers with `is_error` set, and passing that flag on lets Claude read the message and try something else.
222>
223> Each turn replays the assistant message exactly as Claude returned it, thinking blocks included, and answers every `tool_use` block of that turn in one user message. The Messages API rejects a conversation where those two do not line up. `tools` goes on every call so Claude can keep calling tools, and the loop runs until Claude answers without one or `MAX_TOOL_TURNS` is reached, at which point the client reports that it stopped.
211224>
212225> ### Interactive Chat Interface
213226>
from line 295
282295>
283296> * Maintains conversation context
284297> * Handles Claude's responses and tool calls
285> * Manages the message flow between Claude and tools
298> * Runs every tool call of a turn, then answers them all in one message
299> * Keeps looping while Claude asks for tools, up to `MAX_TOOL_TURNS`
286300> * Combines results into a coherent response
287301>
288302> ### 4. Interactive Interface
from line 316
302316>
303317> 1. **Tool Handling**
304318> * Modify `process_query()` to handle specific tool types
319> * Adjust `MAX_TOOL_TURNS` to allow more or fewer rounds of tool calls per query
305320> * Add custom error handling for tool calls
306321> * Implement tool-specific response formatting
307322> 2. **Response Processing**
from line 362
347362> 2. Your query is sent to Claude along with tool descriptions
348363> 3. Claude decides which tools (if any) to use
349364> 4. The client executes any requested tool calls through the server
350> 5. Results are sent back to Claude
365> 5. Results are sent back to Claude, and steps 3 to 5 repeat while Claude keeps asking for tools, up to `MAX_TOOL_TURNS`
351366> 6. Claude provides a natural language response
352367> 7. The response is displayed to you
353368>
from line 370
355370>
356371> 1. **Error Handling**
357372> * Check `result.is_error` rather than expecting a failing tool to raise
373> * Keep the tool loop capped so a query that never settles still returns
358374> * Provide meaningful error messages
359375> * Gracefully handle connection issues
360376> 2. **Resource Management**
from line 541
525541> ```typescript theme={null}
526542> import { Anthropic } from "@anthropic-ai/sdk";
527543> import {
544> ContentBlockParam,
528545> MessageParam,
529546> Tool,
547> ToolResultBlockParam,
548> ToolUseBlock,
530549> } from "@anthropic-ai/sdk/resources/messages/messages.mjs";
531550> import { Client } from "@modelcontextprotocol/client";
532551> import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
from line 559
540559> throw new Error("ANTHROPIC_API_KEY is not set");
541560> }
542561>
562> const MODEL = "claude-opus-5";
563> // The model thinks adaptively unless told otherwise, and max_tokens caps
564> // thinking plus the reply, so leave room for both.
565> const MAX_TOKENS = 10000;
566> const MAX_TOOL_TURNS = 10;
567>
543568> class MCPClient {
544569> private mcp: Client;
545570> private anthropic: Anthropic;
from line 575
550575> this.anthropic = new Anthropic({
551576> apiKey: ANTHROPIC_API_KEY,
552577> });
553> this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
578> // 'auto' probes server/discover, falling back to the 2025-11-25 handshake.
579> // The SDK's default is 'legacy'.
580> this.mcp = new Client(
581> { name: "mcp-client-cli", version: "1.0.0" },
582> { versionNegotiation: { mode: "auto" } },
583> );
554584> }
555585> // methods will go here
556586> }
from line 642
612642> },
613643> ];
614644>
615> const response = await this.anthropic.messages.create({
616> model: "claude-opus-5",
617> max_tokens: 1000,
645> let response = await this.anthropic.messages.create({
646> model: MODEL,
647> max_tokens: MAX_TOKENS,
618648> messages,
619649> tools: this.tools,
620650> });
621651>
622> const finalText = [];
623>
624> for (const content of response.content) {
625> if (content.type === "text") {
626> finalText.push(content.text);
627> } else if (content.type === "tool_use") {
628> const toolName = content.name;
629> const toolArgs = content.input as { [x: string]: unknown } | undefined;
652> const finalText: string[] = [];
653>
654> for (let turn = 0; turn < MAX_TOOL_TURNS; turn++) {
655> const toolUses: ToolUseBlock[] = [];
656>
657> for (const block of response.content) {
658> if (block.type === "text") {
659> finalText.push(block.text);
660> } else if (block.type === "tool_use") {
661> toolUses.push(block);
662> }
663> }
664>
665> if (toolUses.length === 0) {
666> return finalText.join("\n");
667> }
668>
669> const toolResults: ToolResultBlockParam[] = [];
670> for (const toolUse of toolUses) {
671> const toolArgs = toolUse.input as { [x: string]: unknown } | undefined;
672> finalText.push(
673> `[Calling tool ${toolUse.name} with args ${JSON.stringify(toolArgs)}]`
674> );
630675>
631676> const result = await this.mcp.callTool({
632> name: toolName,
677> name: toolUse.name,
633678> arguments: toolArgs,
634679> });
635> finalText.push(
636> `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
637> );
638>
639> messages.push({
640> role: "user",
680>
681> toolResults.push({
682> type: "tool_result",
683> tool_use_id: toolUse.id,
641684> content: result.content
642685> .filter((block) => block.type === "text")
643686> .map((block) => block.text)
644687> .join("\n"),
688> is_error: result.isError === true,
645689> });
646>
647> const response = await this.anthropic.messages.create({
648> model: "claude-opus-5",
649> max_tokens: 1000,
650> messages,
651> });
652>
653> for (const block of response.content) {
654> if (block.type === "text") {
655> finalText.push(block.text);
656> }
657> }
690> }
691>
692> messages.push({
693> role: "assistant",
694> content: response.content as unknown as ContentBlockParam[],
695> });
696> messages.push({ role: "user", content: toolResults });
697>
698> response = await this.anthropic.messages.create({
699> model: MODEL,
700> max_tokens: MAX_TOKENS,
701> messages,
702> tools: this.tools,
703> });
704> }
705>
706> // The turn cap was hit. Keep the last response's text. If it asked for
707> // more tools, say they were not run.
708> let wantsTools = false;
709> for (const block of response.content) {
710> if (block.type === "text") {
711> finalText.push(block.text);
712> } else if (block.type === "tool_use") {
713> wantsTools = true;
658714> }
659715> }
660>
716> if (wantsTools) {
717> finalText.push(`[Stopped after ${MAX_TOOL_TURNS} tool-use turns]`);
718> }
661719> return finalText.join("\n");
662720> }
663721> ```
722>
723> Each turn collects every `tool_use` block before calling the server, then sends the whole assistant turn back as returned (thinking blocks included) followed by one user message holding a `tool_result` block per call. `callTool` returns a `CallToolResult` whose `content` is a list of blocks, which is why the code narrows to `text` blocks before reading `.text`. A tool that fails does not throw here: it answers with `isError` set, and passing that flag on as `is_error` lets Claude read the message and try something else. Every request carries `tools`, so Claude can keep calling tools until it has an answer, up to `MAX_TOOL_TURNS` rounds.
664724>
665725> ### Interactive Chat Interface
666726>
from line 732
672732> input: process.stdin,
673733> output: process.stdout,
674734> });
735> // rl.question() doesn't reject on stdin EOF on its own. Wire its close
736> // event to an AbortSignal so EOF (Ctrl-D) and SIGINT both unblock it.
737> const ac = new AbortController();
738> const onClose = () => ac.abort();
739> rl.on("close", onClose);
740> const onSigint = () => rl.close();
741> process.once("SIGINT", onSigint);
675742>
676743> try {
677744> console.log("\nMCP Client Started!");
678745> console.log("Type your queries or 'quit' to exit.");
679746>
680747> while (true) {
681> const message = await rl.question("\nQuery: ");
748> let message: string;
749> try {
750> message = await rl.question("\nQuery: ", { signal: ac.signal });
751> } catch {
752> break;
753> }
754>
682755> if (message.toLowerCase() === "quit") {
683756> break;
684757> }
from line 759
686759> console.log("\n" + response);
687760> }
688761> } finally {
762> process.off("SIGINT", onSigint);
763> rl.off("close", onClose);
689764> rl.close();
690765> }
691766> }
from line 769
694769> await this.mcp.close();
695770> }
696771> ```
772>
773> Closing stdin (Ctrl-D) or pressing Ctrl-C aborts the pending `rl.question()` and breaks out of the loop, so the client reaches `cleanup()` and exits with status 0 instead of failing with `ERR_USE_AFTER_CLOSE`.
697774>
698775> ### Main Entry Point
699776>
from line 832
755832> 1. The client gets the list of available tools from the server
756833> 2. Your query is sent to Claude along with tool descriptions
757834> 3. Claude decides which tools (if any) to use
758> 4. The client executes any requested tool calls through the server
759> 5. Results are sent back to Claude
760> 6. Claude provides a natural language response
835> 4. The client executes every requested tool call through the server
836> 5. The assistant turn and all tool results go back to Claude in one request, with the tools attached again
837> 6. Claude either requests more tools (the loop allows up to `MAX_TOOL_TURNS` rounds) or provides a natural language response
761838> 7. The response is displayed to you
762839>
763840> ## Best practices
764841>
765842> 1. **Error Handling**
766843> * Use TypeScript's type system for better error detection
767> * Wrap tool calls in try-catch blocks
844> * Check `result.isError` rather than expecting a failing tool to throw
768845> * Provide meaningful error messages
769846> * Gracefully handle connection issues
770847> 2. **Security**
from line 1084
10071084 
10081085> [tab] Kotlin
10091086>
1087> > [!NOTE]
1088> >
1089> > This client uses MCP protocol version 2025-11-25, as supported by the latest stable release of the Kotlin SDK. It connects to servers that accept that version, but not to servers that accept only 2026-07-28. See [backward compatibility](https://modelcontextprotocol.io/specification/draft/basic/versioning.md#backward-compatibility-with-initialization-based-versions).
1090>
10101091> [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client)
10111092>
10121093> ## System Requirements
from line 1134
10531134>
10541135> ```kotlin build.gradle.kts theme={null}
10551136> // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1056> val mcpVersion = "0.9.0"
1137> val mcpVersion = "0.16.0"
10571138> val ktorVersion = "3.2.3"
10581139> val anthropicVersion = "2.15.0"
10591140> val slf4jVersion = "2.0.17"
from line 1143
10621143> kotlin("jvm") version "2.3.20"
10631144> id("com.gradleup.shadow") version "8.3.9"
10641145> application
1146> }
1147>
1148> repositories {
1149> mavenCentral()
10651150> }
10661151>
10671152> application {
from line 1188
11031188> First, let's create the basic client class:
11041189>
11051190> ```kotlin theme={null}
1191> private const val MODEL = "claude-opus-5"
1192> // The model thinks adaptively unless told otherwise, and max_tokens caps thinking
1193> // plus the reply, so leave room for both.
1194> private const val MAX_TOKENS = 10_000L
1195> private const val MAX_TOOL_TURNS = 10
1196>
11061197> class MCPClient(apiKey: String) : AutoCloseable {
11071198> private val anthropic = AnthropicOkHttpClient.builder()
11081199> .apiKey(apiKey)
from line 1277
11861277>
11871278> ### Query processing logic
11881279>
1189> Now let's add the core functionality for processing queries and handling tool calls:
1280> Now let's add the core functionality for processing queries and handling tool calls. Claude can request several tools in one turn and can request more after reading their results, so the client runs a loop: it executes every requested tool, sends all of the results back in one message, and repeats until Claude answers without tool calls or `MAX_TOOL_TURNS` is reached:
11901281>
11911282> ```kotlin theme={null}
11921283> suspend fun processQuery(query: String): String {
from line 1288
11971288> .build(),
11981289> )
11991290>
1200> val response = anthropic.messages().create(
1291> var response = anthropic.messages().create(
12011292> MessageCreateParams.builder()
1202> .model("claude-opus-5")
1203> .maxTokens(1024)
1293> .model(MODEL)
1294> .maxTokens(MAX_TOKENS)
12041295> .messages(messages)
12051296> .tools(tools)
12061297> .build(),
12071298> )
12081299>
12091300> val finalText = mutableListOf<String>()
1210> response.content().forEach { content ->
1211> when {
1212> content.isText() -> finalText.add(content.text().get().text())
1213>
1214> content.isToolUse() -> {
1215> val toolName = content.toolUse().get().name()
1216> val toolArgs =
1217> content.toolUse().get()._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
1218>
1219> val result = mcp.callTool(
1220> name = toolName,
1221> arguments = toolArgs ?: emptyMap(),
1222> )
1223> finalText.add("[Calling tool $toolName with args $toolArgs]")
1224>
1225> messages.add(
1226> MessageParam.builder()
1227> .role(MessageParam.Role.USER)
1228> .content(
1229> result.content
1230> .filterIsInstance<TextContent>()
1231> .joinToString("\n") { it.text }
1232> )
1233> .build(),
1234> )
1235>
1236> val aiResponse = anthropic.messages().create(
1237> MessageCreateParams.builder()
1238> .model("claude-opus-5")
1239> .maxTokens(1024)
1240> .messages(messages)
1241> .build(),
1242> )
1243>
1244> aiResponse.content().forEach { block ->
1245> if (block.isText()) finalText.add(block.text().get().text())
1246> }
1301>
1302> repeat(MAX_TOOL_TURNS) {
1303> val toolUses = mutableListOf<ToolUseBlock>()
1304> response.content().forEach { block ->
1305> when {
1306> block.isText() -> finalText.add(block.text().get().text())
1307> block.isToolUse() -> toolUses.add(block.toolUse().get())
12471308> }
12481309> }
1310>
1311> if (toolUses.isEmpty()) return finalText.joinToString("\n")
1312>
1313> val toolResults = toolUses.map { toolUse ->
1314> val toolArgs = toolUse._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
1315> finalText.add("[Calling tool ${toolUse.name()} with args $toolArgs]")
1316>
1317> val result = mcp.callTool(
1318> name = toolUse.name(),
1319> arguments = toolArgs ?: emptyMap(),
1320> )
1321>
1322> // content is a list of block types, so forward only the text ones. MCP
1323> // and Anthropic block shapes differ, so other kinds need converting.
1324> ContentBlockParam.ofToolResult(
1325> ToolResultBlockParam.builder()
1326> .toolUseId(toolUse.id())
1327> .content(result.content.filterIsInstance<TextContent>().joinToString("\n") { it.text })
1328> .apply { if (result.isError == true) isError(true) }
1329> .build(),
1330> )
1331> }
1332>
1333> // Replay the full assistant turn, tool_use blocks included, then send
1334> // every tool result of this turn in one user message.
1335> messages.add(
1336> MessageParam.builder()
1337> .role(MessageParam.Role.ASSISTANT)
1338> .contentOfBlockParams(response.content().map { it.toParam() })
1339> .build(),
1340> )
1341> messages.add(
1342> MessageParam.builder()
1343> .role(MessageParam.Role.USER)
1344> .contentOfBlockParams(toolResults)
1345> .build(),
1346> )
1347>
1348> response = anthropic.messages().create(
1349> MessageCreateParams.builder()
1350> .model(MODEL)
1351> .maxTokens(MAX_TOKENS)
1352> .messages(messages)
1353> .tools(tools)
1354> .build(),
1355> )
12491356> }
12501357>
1358> // The turn cap was hit. Keep the last response's text. If it asked for
1359> // more tools, say they were not run.
1360> var wantsTools = false
1361> response.content().forEach { block ->
1362> when {
1363> block.isText() -> finalText.add(block.text().get().text())
1364> block.isToolUse() -> wantsTools = true
1365> }
1366> }
1367> if (wantsTools) finalText.add("[Stopped after $MAX_TOOL_TURNS tool-use turns]")
1368>
12511369> return finalText.joinToString("\n")
12521370> }
12531371> ```
1372>
1373> `callTool` returns a `CallToolResult`. Its `content` is a list of blocks, which is why the code narrows to `TextContent` before reading `.text`. A tool that fails does not throw here: it answers with `isError` set, and passing that flag on through `ToolResultBlockParam` lets Claude read the message and try something else. Every tool result carries the `id` of the `tool_use` block it answers, and the assistant turn goes back exactly as returned, so the conversation stays valid for the next call.
12541374>
12551375> ### Interactive chat
12561376>
from line 1466
13461466> User->>Client: Send query
13471467> Client<<->>MCP_Server: Get available tools
13481468> Client->>Claude: Send query with tool descriptions
1349> Claude-->>Client: Decide tool execution
1350> Client->>MCP_Server: Request tool execution
1351> MCP_Server->>Tools: Execute chosen tools
1352> Tools-->>MCP_Server: Return results
1353> MCP_Server-->>Client: Send results
1354> Client->>Claude: Send tool results
1469> loop Until Claude answers without tool_use blocks, or MAX_TOOL_TURNS is reached
1470> Claude-->>Client: Return tool_use blocks
1471> Client->>MCP_Server: Request every tool execution
1472> MCP_Server->>Tools: Execute chosen tools
1473> Tools-->>MCP_Server: Return results
1474> MCP_Server-->>Client: Send results
1475> Client->>Claude: Replay assistant turn, send all tool results in one message
1476> end
13551477> Claude-->>Client: Provide final response
13561478> Client-->>User: Display response
13571479> ```
from line 1483
13611483> 1. The client gets the list of available tools from the server
13621484> 2. Your query is sent to Claude along with tool descriptions
13631485> 3. Claude decides which tools (if any) to use
1364> 4. The client executes any requested tool calls through the server
1365> 5. Results are sent back to Claude
1366> 6. Claude provides a natural language response
1486> 4. The client executes every requested tool call through the server and forwards the `isError` flag of any call that failed
1487> 5. The client replays the assistant turn and sends all tool results back to Claude in one message, with the tool descriptions attached again
1488> 6. Steps 3 to 5 repeat until Claude answers without tool calls or `MAX_TOOL_TURNS` is reached
13671489> 7. The response is displayed to you
13681490>
13691491> ## Best practices
13701492>
13711493> 1. **Error Handling**
1494> * Check `result.isError` on every tool result and forward it with `isError(true)`, since a failing tool answers with that flag instead of throwing
1495> * Keep `MAX_TOOL_TURNS` in place so a run that keeps requesting tools stops with a visible message
13721496> * Leverage Kotlin's type system to model errors explicitly
13731497> * Wrap external tool and API calls in `try-catch` blocks when exceptions are possible
13741498> * Provide clear and meaningful error messages
from line 1550
14261550>
14271551> * `Connection refused`: Ensure the server is running and the path is correct
14281552> * `Tool execution failed`: Verify the tool's required environment variables are set
1553> * `[Stopped after 10 tool-use turns]`: Claude was still requesting tools when `MAX_TOOL_TURNS` ran out, so raise the cap or narrow the query
14291554> * `ANTHROPIC_API_KEY is not set`: Check your environment variables
14301555 
14311556> [tab] C#
from line 1665
15401665>
15411666> var options = new ChatOptions
15421667> {
1543> MaxOutputTokens = 1000,
1668> MaxOutputTokens = 10000,
15441669> ModelId = "claude-opus-5",
15451670> Tools = [.. tools]
15461671> };
from line 1830
17051830>
17061831> class MCPClient
17071832> ANTHROPIC_MODEL = "claude-opus-5"
1833> # The model thinks adaptively unless told otherwise, and max_tokens caps thinking
1834> # plus the reply, so leave room for both.
1835> MAX_TOKENS = 10000
1836> MAX_TOOL_TURNS = 10
17081837>
17091838> def initialize
17101839> @mcp_client = nil
from line 1873
17441873>
17451874> ### Query Processing Logic
17461875>
1747> Now let's add the core functionality for processing queries and handling tool calls:
1876> Now let's add the core functionality for processing queries and handling tool calls. Each turn runs every tool Claude asks for, sends all of the results back in one message, and calls Claude again with the tools attached, until Claude answers without a tool call or `MAX_TOOL_TURNS` is reached:
17481877>
17491878> ```ruby theme={null}
1750> private
1751>
17521879> def process_query(query)
17531880> messages = [{ role: "user", content: query }]
17541881>
from line 1883
17561883> { name: tool.name, description: tool.description, input_schema: tool.input_schema }
17571884> end
17581885>
1759> # Initial Claude API call.
1760> response = chat(messages, tools: available_tools)
1761>
1762> # Process response and handle tool calls.
1763> if response.content.any?(Anthropic::Models::ToolUseBlock)
1764> assistant_content = response.content.filter_map do |content_block|
1765> case content_block
1886> final_text = []
1887>
1888> # Initial Claude API call with tools.
1889> response = chat(messages, available_tools)
1890>
1891> # Keep calling tools until Claude answers without one, up to a cap.
1892> MAX_TOOL_TURNS.times do
1893> tool_uses = []
1894> response.content.each do |block|
1895> case block
17661896> when Anthropic::Models::TextBlock
1767> { type: "text", text: content_block.text }
1897> final_text << block.text
17681898> when Anthropic::Models::ToolUseBlock
1769> { type: "tool_use", id: content_block.id, name: content_block.name, input: content_block.input }
1899> tool_uses << block
17701900> end
17711901> end
1772> messages << { role: "assistant", content: assistant_content }
1773> end
1774>
1775> response_parts = []
1776> tool_results = []
1777>
1778> response.content.each do |content|
1779> case content
1780> when Anthropic::Models::TextBlock
1781> response_parts << content.text
1782> when Anthropic::Models::ToolUseBlock
1783> # Execute tool call via MCP.
1784> result = @mcp_client.call_tool(name: content.name, arguments: content.input)
1785> response_parts << "[Calling tool #{content.name} with args #{content.input.to_json}]"
1786>
1902>
1903> return final_text.join("\n") if tool_uses.empty?
1904>
1905> # Execute every tool call in this response and collect the results.
1906> tool_results = tool_uses.map do |tool_use|
1907> result = @mcp_client.call_tool(name: tool_use.name, arguments: tool_use.input)
1908> final_text << "[Calling tool #{tool_use.name} with args #{tool_use.input.to_json}]"
1909>
1910> is_error = result.dig("result", "isError") == true
1911>
1912> # content is a list of block types, so forward only the text ones.
17871913> tool_result_content = result.dig("result", "content")
17881914> result_text = if tool_result_content.is_a?(Array)
17891915> tool_result_content.filter_map { |content_item| content_item["text"] }.join("\n")
from line 1917
17911917> tool_result_content.to_s
17921918> end
17931919>
1794> tool_results << { type: "tool_result", tool_use_id: content.id, content: result_text }
1920> { type: "tool_result", tool_use_id: tool_use.id, content: result_text, is_error: is_error }
17951921> end
1922>
1923> # Append the assistant's response and all tool results, in one user
1924> # message, to the history. Every tool_use needs a matching tool_result.
1925> messages << { role: "assistant", content: assistant_content(response) }
1926> messages << { role: "user", content: tool_results }
1927>
1928> response = chat(messages, available_tools)
17961929> end
17971930>
1798> unless tool_results.empty?
1799> # Every tool_use block needs a matching tool_result in a single user message.
1800> messages << { role: "user", content: tool_results }
1801>
1802> # Get next response from Claude.
1803> response = chat(messages)
1804>
1805> response.content.each do |content_block|
1806> response_parts << content_block.text if content_block.is_a?(Anthropic::Models::TextBlock)
1807> end
1931> # The turn cap was hit. Keep the last response's text. If it asked for
1932> # more tools, say they were not run.
1933> response.content.each do |block|
1934> final_text << block.text if block.is_a?(Anthropic::Models::TextBlock)
18081935> end
1809>
1810> response_parts.join("\n")
1936> if response.content.any?(Anthropic::Models::ToolUseBlock)
1937> final_text << "[Stopped after #{MAX_TOOL_TURNS} tool-use turns]"
1938> end
1939> final_text.join("\n")
18111940> end
1812>
1813> def chat(messages, tools: nil)
1814> params = { model: ANTHROPIC_MODEL, max_tokens: 1000, messages: messages }
1815> params[:tools] = tools if tools
1816>
1817> anthropic_client.messages.create(**params)
1818> end
1819>
1820> def anthropic_client
1821> @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"])
1822> end
18231941> ```
18241942>
18251943> ### Interactive Chat Interface
18261944>
1827> Now we'll add the chat loop and cleanup functionality:
1945> Now we'll add the chat loop and cleanup functionality, followed by the private helpers that `process_query` relies on:
18281946>
18291947> ```ruby theme={null}
18301948> def chat_loop
from line 1972
18541972> def cleanup
18551973> @transport&.close
18561974> end
1975>
1976> private
1977>
1978> # Convert a response's content blocks back into request parameters. Thinking
1979> # blocks must go back unchanged, signature included, or the API rejects the
1980> # follow-up request.
1981> def assistant_content(response)
1982> response.content.filter_map do |block|
1983> case block
1984> when Anthropic::Models::TextBlock
1985> { type: "text", text: block.text }
1986> when Anthropic::Models::ToolUseBlock
1987> { type: "tool_use", id: block.id, name: block.name, input: block.input }
1988> when Anthropic::Models::ThinkingBlock
1989> { type: "thinking", thinking: block.thinking, signature: block.signature }
1990> when Anthropic::Models::RedactedThinkingBlock
1991> { type: "redacted_thinking", data: block.data }
1992> end
1993> end
1994> end
1995>
1996> # Tools are passed on every call so Claude can keep calling them across turns.
1997> def chat(messages, tools)
1998> anthropic_client.messages.create(
1999> model: ANTHROPIC_MODEL,
2000> max_tokens: MAX_TOKENS,
2001> messages: messages,
2002> tools: tools
2003> )
2004> end
2005>
2006> def anthropic_client
2007> @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"])
2008> end
18572009> ```
18582010>
18592011> ### Main Entry Point
from line 2062
19102062>
19112063> * Maps MCP tools to Anthropic tool format (`name`, `description`, `input_schema`)
19122064> * Uses `Anthropic::Models::TextBlock` and `Anthropic::Models::ToolUseBlock` for pattern matching
1913> * Builds assistant content once before iterating tool calls
2065> * Loops up to `MAX_TOOL_TURNS` times, running every tool call in each response
19142066> * Executes tool calls via `@mcp_client.call_tool`
1915> * Uses `chat` helper method to wrap Anthropic API calls
1916> * Extracts tool result content with `result.dig("result", "content")`
1917> * Passes tool results back to Claude for a final response
2067> * Extracts tool result content with `result.dig("result", "content")` and the error flag with `result.dig("result", "isError")`
2068> * Sends all of a turn's `tool_result` blocks in a single user message, each with its `tool_use_id` and `is_error`
2069> * Replays the assistant turn with `assistant_content`, which round-trips thinking blocks with their signatures intact
2070> * Uses the `chat` helper, which passes `tools` and `MAX_TOKENS` on every API call
19182071>
19192072> ### 4. Interactive Interface
19202073>
from line 2112
19592112> 1. The client gets the list of available tools from the server
19602113> 2. Your query is sent to Claude along with tool descriptions
19612114> 3. Claude decides which tools (if any) to use
1962> 4. The client executes any requested tool calls through the server
1963> 5. Results are sent back to Claude
1964> 6. Claude provides a natural language response
1965> 7. The response is displayed to you
2115> 4. The client executes every requested tool call through the server
2116> 5. The assistant turn and all tool results are sent back to Claude, with the tools attached again
2117> 6. Steps 3 to 5 repeat until Claude answers without a tool call or `MAX_TOOL_TURNS` is reached
2118> 7. Claude provides a natural language response
2119> 8. The response is displayed to you
19662120>
19672121> ## Best practices
19682122>
19692123> 1. **Error Handling**
19702124> * Wrap tool calls in `begin`...`rescue` blocks
2125> * Check `isError` on each tool result and forward it as `is_error` rather than expecting a failing tool to raise
19712126> * Provide meaningful error messages
19722127> * Gracefully handle connection issues
19732128> 2. **Resource Management**
19742129> * Always close the transport when done
19752130> * Use `begin`...`ensure` for proper cleanup
2131> * Cap tool-use turns with `MAX_TOOL_TURNS` so one query cannot loop indefinitely
19762132> * Handle server disconnections
19772133> 3. **Security**
19782134> * Store API keys securely in `.env`
from line 2179
20232179> * `Connection refused`: Ensure the server is running and the path is correct
20242180> * `Tool execution failed`: Verify the tool's required environment variables are set
20252181> * `Anthropic::Errors::AuthenticationError`: Check your `.env` file has a valid `ANTHROPIC_API_KEY`
2182> * `[Stopped after 10 tool-use turns]`: Claude kept asking for tools, so the client stopped at `MAX_TOOL_TURNS` and returned the text collected so far
20262183 
20272184> [tab] Rust
20282185>
20292186 
Feedback