Model Context Protocol

In this tutorial, you’ll learn how to build an LLM-powered chatbot client that connects to MCP servers. Before you begin, it helps to have gone through our Build an MCP Server tutorial so you can understand how clients and servers communicate.

  • Python

  • TypeScript

  • Java

  • Kotlin

  • C#

  • Ruby

  • Rust

You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your system meets these requirements:

  • Mac or Windows computer
  • Latest Python version installed
  • Latest version of uv installed
  • You must use the Python MCP SDK 2.0.0 or higher

Setting Up Your Environment

First, create a new Python project with uv:

Setting Up Your API Key

You’ll need an Anthropic API key from the Anthropic Console.Create a .env file to store it:

Add .env to your .gitignore:

Creating the Client

Imports and Setup

First, let’s set up our imports and the pieces the rest of the file shares:

Client is the single object your program talks to the server through. Listing the tools, calling one, reading a resource: each of those is a method on it.

Server Connection Management

Next, we’ll work out which process to launch for a given server script:

StdioServerParameters is configuration, not a connection. stdio_client() turns it into a stdio transport, and Client opens that transport when you enter its async with block. We’ll do both in main().

Query Processing Logic

Now let’s add the core functionality for processing queries and handling tool calls:

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.

Interactive Chat Interface

Now we’ll add the chat loop:

input() blocks, so it runs on a worker thread. That keeps the event loop free to service the connection while you type.

Main Entry Point

Finally, we’ll add the main execution logic:

That async with is the entire connection lifecycle. Entering it launches the server and agrees a protocol version with it; leaving it disconnects and shuts the subprocess down. There is nothing to close by hand.You can find the complete client.py file here.

Key Components Explained

1. Client Initialization

  • A single Client carries the connection, and async with is its whole lifecycle
  • There is no connect/close pair to call and nothing to clean up afterwards
  • Configures the Anthropic client for Claude interactions

2. Server Connection

  • Supports both Python and Node.js servers
  • Validates server script type
  • Launches the server as a subprocess and speaks stdio to it
  • Lists the available tools once the connection is open

3. Query Processing

  • Maintains conversation context
  • Handles Claude’s responses and tool calls
  • Manages the message flow between Claude and tools
  • Combines results into a coherent response

4. Interactive Interface

  • Provides a simple command-line interface
  • Handles user input and displays responses
  • Includes basic error handling
  • Allows graceful exit

5. Resource Management

  • Leaving the async with block disconnects and shuts the server subprocess down
  • A failing query is reported without ending the session
  • Typing quit, or closing standard input, exits cleanly

Common Customization Points

  1. Tool Handling
    • Modify process_query() to handle specific tool types
    • Add custom error handling for tool calls
    • Implement tool-specific response formatting
  2. Response Processing
    • Customize how tool results are formatted
    • Add response filtering or transformation
    • Implement custom logging
  3. User Interface
    • Add a GUI or web interface
    • Implement rich console output
    • Add command history or auto-completion

Running the Client

To run your client with any MCP server:

The client will:

  1. Connect to the specified server
  2. List available tools
  3. Start an interactive chat session where you can:
    • Enter queries
    • See tool executions
    • Get responses from Claude

Here’s an example of what it should look like if connected to the weather server from the server quickstart:

How It Works

When you submit a query:

  1. The client gets the list of available tools from the server
  2. Your query is sent to Claude along with tool descriptions
  3. Claude decides which tools (if any) to use
  4. The client executes any requested tool calls through the server
  5. Results are sent back to Claude
  6. Claude provides a natural language response
  7. The response is displayed to you

Best practices

  1. Error Handling
    • Check result.is_error rather than expecting a failing tool to raise
    • Provide meaningful error messages
    • Gracefully handle connection issues
  2. Resource Management
    • Let the async with block own the connection
    • Keep it open for as long as you need the server
    • Handle server disconnections
  3. Security
    • Store API keys securely in .env
    • Validate server responses
    • Be cautious with tool permissions
  4. Tool Names
    • Tool names can be validated according to the format specified here
    • If a tool name conforms to the specified format, it should not fail validation by an MCP client

Troubleshooting

Server Path Issues

  • Double-check the path to your server script is correct
  • Use the absolute path if the relative path isn’t working
  • For Windows users, make sure to use forward slashes (/) or escaped backslashes (\) in the path
  • Verify the server file has the correct extension (.py for Python or .js for Node.js)

Example of correct path usage:

Response Timing

  • The first response might take up to 30 seconds to return
  • This is normal and happens while:
    • The server initializes
    • Claude processes the query
    • Tools are being executed
  • Subsequent responses are typically faster
  • Don’t interrupt the process during this initial waiting period

Common Error Messages

If you see:

  • FileNotFoundError: Check your server path
  • Connection refused: Ensure the server is running and the path is correct
  • Tool execution failed: Verify the tool’s required environment variables are set
  • Timeout error: Consider raising read_timeout_seconds on the Client

You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your system meets these requirements:

  • Mac or Windows computer
  • Node.js 20 or higher installed
  • Latest version of npm installed
  • Anthropic API key (Claude)

Setting Up Your Environment

First, let’s create and set up our project:

Update your package.json to set type: "module" and a build script:

package.json

Create a tsconfig.json in the root of your project:

tsconfig.json

Setting Up Your API Key

You’ll need an Anthropic API key from the Anthropic Console.Create a .env file to store it:

Add .env to your .gitignore:

Creating the Client

Basic Client Structure

First, let’s set up our imports and create the basic client class in index.ts:

Server Connection Management

Next, we’ll implement the method to connect to an MCP server:

Query Processing Logic

Now let’s add the core functionality for processing queries and handling tool calls:

Interactive Chat Interface

Now we’ll add the chat loop and cleanup functionality:

Main Entry Point

Finally, we’ll add the main execution logic:

Running the Client

To run your client with any MCP server:

The client will:

  1. Connect to the specified server
  2. List available tools
  3. Start an interactive chat session where you can:
    • Enter queries
    • See tool executions
    • Get responses from Claude

How It Works

When you submit a query:

  1. The client gets the list of available tools from the server
  2. Your query is sent to Claude along with tool descriptions
  3. Claude decides which tools (if any) to use
  4. The client executes any requested tool calls through the server
  5. Results are sent back to Claude
  6. Claude provides a natural language response
  7. The response is displayed to you

Best practices

  1. Error Handling
    • Use TypeScript’s type system for better error detection
    • Wrap tool calls in try-catch blocks
    • Provide meaningful error messages
    • Gracefully handle connection issues
  2. Security
    • Store API keys securely in .env
    • Validate server responses
    • Be cautious with tool permissions

Troubleshooting

Server Path Issues

  • Double-check the path to your server script is correct
  • Use the absolute path if the relative path isn’t working
  • For Windows users, make sure to use forward slashes (/) or escaped backslashes (\) in the path
  • Verify the server file has the correct extension (.js for Node.js or .py for Python)

Example of correct path usage:

Response Timing

  • The first response might take up to 30 seconds to return
  • This is normal and happens while:
    • The server initializes
    • Claude processes the query
    • Tools are being executed
  • Subsequent responses are typically faster
  • Don’t interrupt the process during this initial waiting period

Common Error Messages

If you see:

  • Error: Cannot find module: Check your build folder and ensure TypeScript compilation succeeded
  • Connection refused: Ensure the server is running and the path is correct
  • Tool execution failed: Verify the tool’s required environment variables are set
  • ANTHROPIC_API_KEY is not set: Check your .env file and environment variables
  • TypeError: Ensure you’re using the correct types for tool arguments
  • BadRequestError: Ensure you have enough credits to access the Anthropic API

This example demonstrates how to build an interactive chatbot that combines Spring AI’s Model Context Protocol (MCP) with the Brave Search MCP Server. The application creates a conversational interface powered by Anthropic’s Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data. You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your system meets these requirements:

  • Java 17 or higher
  • Maven 3.6+
  • npx package manager
  • Anthropic API key (Claude)
  • Brave Search API key

Setting Up Your Environment

  1. Install npx (Node Package eXecute): First, make sure to install npm and then run:
  2. Clone the repository:
  3. Set up your API keys:
  4. Build the application:
  5. Run the application using Maven:

How it Works

The application integrates Spring AI with the Brave Search MCP server through several components:

MCP Client Configuration

  1. Required dependencies in pom.xml:
  1. Application properties (application.yml):

This activates the spring-ai-starter-mcp-client to create one or more McpClients based on the provided server configuration. The spring.ai.mcp.client.toolcallback.enabled=true property enables the tool callback mechanism, that automatically registers all MCP tool as spring ai tools. It is disabled by default.

  1. MCP Server Configuration (mcp-servers-config.json):

Chat Implementation

The chatbot is implemented using Spring AI’s ChatClient with MCP tool integration:

Key features:

  • Uses Claude AI model for natural language understanding
  • Integrates Brave Search through MCP for real-time web search capabilities
  • Maintains conversation memory using InMemoryChatMemory
  • Runs as an interactive command-line application

Build and run

or

The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.The chatbot can:

  • Answer questions using its built-in knowledge
  • Perform web searches when needed using Brave Search
  • Remember context from previous messages in the conversation
  • Combine information from multiple sources to provide comprehensive answers

Advanced Configuration

The MCP client supports additional configuration options:

  • Client customization through McpClientCustomizer<McpClient.SyncSpec> or McpClientCustomizer<McpClient.AsyncSpec> beans
  • Multiple clients with multiple transport types: STDIO and Streamable HTTP
  • Integration with Spring AI’s tool execution framework
  • Automatic client initialization and lifecycle management

To connect to a remote MCP server over Streamable HTTP, configure a connection URL:

For WebFlux-based applications, you can use the WebFlux starter instead:

This provides similar functionality but uses a WebFlux-based Streamable HTTP transport implementation, recommended for production deployments.

You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your system meets these requirements:

  • JDK 11 or higher
  • Anthropic API key (Claude)

Setting up your environment

First, let’s install java and gradle if you haven’t already. You can download java from official Oracle JDK website. Verify your java installation:

Now, let’s create and set up your project:

After running gradle init, select Application as the project type, Kotlin as the programming language.Alternatively, you can create a Kotlin application using the IntelliJ IDEA project wizard.After creating the project, replace the contents of your build.gradle.kts with:

build.gradle.kts

Verify that everything is set up correctly:

Setting up your API key

You’ll need an Anthropic API key from the Anthropic Console.Set up your API key:

Creating the Client

Basic Client Structure

First, let’s create the basic client class:

Server connection management

Next, we’ll implement the method to connect to an MCP server:

JsonObject.toJsonValue() helper

This helper converts a kotlinx.serialization JsonObject to an Anthropic SDK JsonValue using Jackson:

Query processing logic

Now let’s add the core functionality for processing queries and handling tool calls:

Interactive chat

We’ll add the chat loop:

Main entry point

Finally, we’ll add the main execution function:

Running the client

To run your client with any MCP server:

Alternatively, you can run directly with Gradle:

The client will:

  1. Connect to the specified server
  2. List available tools
  3. Start an interactive chat session where you can:
    • Enter queries
    • See tool executions
    • Get responses from Claude

How it works

Here’s a high-level workflow schema:

When you submit a query:

  1. The client gets the list of available tools from the server
  2. Your query is sent to Claude along with tool descriptions
  3. Claude decides which tools (if any) to use
  4. The client executes any requested tool calls through the server
  5. Results are sent back to Claude
  6. Claude provides a natural language response
  7. The response is displayed to you

Best practices

  1. Error Handling
    • Leverage Kotlin’s type system to model errors explicitly
    • Wrap external tool and API calls in try-catch blocks when exceptions are possible
    • Provide clear and meaningful error messages
    • Handle network timeouts and connection issues gracefully
  2. Security
    • Store API keys and secrets securely in local.properties, environment variables, or secret managers
    • Validate all external responses to avoid unexpected or unsafe data usage
    • Be cautious with permissions and trust boundaries when using tools
  3. Environment
    • Set ANTHROPIC_API_KEY through environment variables rather than hardcoding
    • Use .env files with appropriate .gitignore rules for local development

Troubleshooting

Server Path Issues

  • Double-check the path to your server script is correct
  • Use the absolute path if the relative path isn’t working
  • For Windows users, make sure to use forward slashes (/) or escaped backslashes (\) in the path
  • Make sure that the required runtime is installed (java for Java, npm for Node.js, or uv for Python)
  • Verify the server file has the correct extension (.jar for Java, .js for Node.js or .py for Python)

Example of correct path usage:

Build Issues

  • Use ./gradlew build or ./gradlew shadowJar (not ./gradlew jar) to create the shadow JAR with all dependencies
  • If you get JDK version errors, ensure your installed JDK version matches or exceeds the jvmToolchain setting in build.gradle.kts

Response Timing

  • The first response might take up to 30 seconds to return
  • This is normal and happens while:
    • The server initializes
    • Claude processes the query
    • Tools are being executed
  • Subsequent responses are typically faster
  • Don’t interrupt the process during this initial waiting period

Common Error Messages

If you see:

  • Connection refused: Ensure the server is running and the path is correct
  • Tool execution failed: Verify the tool’s required environment variables are set
  • ANTHROPIC_API_KEY is not set: Check your environment variables

You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your system meets these requirements:

  • .NET 8.0 or higher
  • Anthropic API key (Claude)
  • Windows, Linux, or macOS

Setting up your environment

First, create a new .NET project:

Then, add the required dependencies to your project:

Setting up your API key

You’ll need an Anthropic API key from the Anthropic Console.

Creating the Client

Basic Client Structure

First, let’s setup the basic client class in the file Program.cs:

This creates the beginnings of a .NET console application that can read the API key from user secrets.Next, we’ll setup the MCP Client:

Add this function at the end of the Program.cs file:

This creates an MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.

Query processing logic

Now let’s add the core functionality for processing queries and handling tool calls:

Key Components Explained

1. Client Initialization

  • The client is initialized using McpClient.CreateAsync(), which sets up the transport type and command to run the server.

2. Server Connection

  • Supports Python, Node.js, and .NET servers.
  • The server is started using the command specified in the arguments.
  • Configures to use stdio for communication with the server.
  • Initializes the session and available tools.

3. Query Processing

  • Leverages Microsoft.Extensions.AI for the chat client.
  • Configures the IChatClient to use automatic tool (function) invocation.
  • The client reads user input and sends it to the server.
  • The server processes the query and returns a response.
  • The response is displayed to the user.

Running the Client

To run your client with any MCP server:

The client will:

  1. Connect to the specified server
  2. List available tools
  3. Start an interactive chat session where you can:
    • Enter queries
    • See tool executions
    • Get responses from Claude
  4. Exit the session when done

Here’s an example of what it should look like if connected to the weather server quickstart:

You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your system meets these requirements:

  • Mac or Windows computer
  • Ruby 3.2.0 or higher installed (required by the Anthropic SDK)
  • Anthropic API key (Claude)

Setting Up Your Environment

First, create a new Ruby project:

Setting Up Your API Key

You’ll need an Anthropic API key from the Anthropic Console.Create a .env file to store it:

Add .env to your .gitignore:

Creating the Client

Basic Client Structure

First, let’s set up our requires and create the basic client class:

Server Connection Management

Next, we’ll implement the method to connect to an MCP server:

Query Processing Logic

Now let’s add the core functionality for processing queries and handling tool calls:

Interactive Chat Interface

Now we’ll add the chat loop and cleanup functionality:

Main Entry Point

Finally, we’ll add the main execution logic:

You can find the complete client.rb file here.

Key Components Explained

1. Client Initialization

  • The MCPClient class initializes with nil references for lazy setup
  • The Anthropic client is lazily initialized via the anthropic_client method
  • Uses dotenv to load environment variables from .env

2. Server Connection

  • Supports Ruby, Python, and Node.js servers
  • Uses File.extname to determine the server script type
  • Uses MCP::Client::Stdio for stdio transport
  • Initializes the MCP client and lists available tools

3. Query Processing

  • Maps MCP tools to Anthropic tool format (name, description, input_schema)
  • Uses Anthropic::Models::TextBlock and Anthropic::Models::ToolUseBlock for pattern matching
  • Builds assistant content once before iterating tool calls
  • Executes tool calls via @mcp_client.call_tool
  • Uses chat helper method to wrap Anthropic API calls
  • Extracts tool result content with result.dig("result", "content")
  • Passes tool results back to Claude for a final response

4. Interactive Interface

  • Provides a simple command-line interface
  • Handles user input and displays responses
  • Skips empty queries
  • Includes basic error handling

5. Resource Management

  • Proper cleanup of the transport via beginensure
  • Top-level rescue for error handling
  • API key validation after server connection

Running the Client

To run your client with any MCP server:

The client will:

  1. Connect to the specified server
  2. List available tools
  3. Start an interactive chat session where you can:
    • Enter queries
    • See tool executions
    • Get responses from Claude

How It Works

When you submit a query:

  1. The client gets the list of available tools from the server
  2. Your query is sent to Claude along with tool descriptions
  3. Claude decides which tools (if any) to use
  4. The client executes any requested tool calls through the server
  5. Results are sent back to Claude
  6. Claude provides a natural language response
  7. The response is displayed to you

Best practices

  1. Error Handling
    • Wrap tool calls in beginrescue blocks
    • Provide meaningful error messages
    • Gracefully handle connection issues
  2. Resource Management
    • Always close the transport when done
    • Use beginensure for proper cleanup
    • Handle server disconnections
  3. Security
    • Store API keys securely in .env
    • Validate server responses
    • Be cautious with tool permissions
  4. Tool Names
    • Tool names can be validated according to the format specified here
    • If a tool name conforms to the specified format, it should not fail validation by an MCP client

Troubleshooting

Server Path Issues

  • Double-check the path to your server script is correct
  • Use the absolute path if the relative path isn’t working
  • For Windows users, make sure to use forward slashes (/) or escaped backslashes (\) in the path
  • Verify the server file has the correct extension (.py for Python, .js for Node.js, or .rb for Ruby)

Example of correct path usage:

Response Timing

  • The first response might take up to 30 seconds to return
  • This is normal and happens while:
    • The server initializes
    • Claude processes the query
    • Tools are being executed
  • Subsequent responses are typically faster
  • Don’t interrupt the process during this initial waiting period

Common Error Messages

If you see:

  • Errno::ENOENT: Check your server path and ensure the command (ruby, python3, node) is available
  • Connection refused: Ensure the server is running and the path is correct
  • Tool execution failed: Verify the tool’s required environment variables are set
  • Anthropic::Errors::AuthenticationError: Check your .env file has a valid ANTHROPIC_API_KEY

You can find the complete code for this tutorial here.

System Requirements

Before starting, ensure your Linux system meets these requirements:

  • Latest stable version of Rust and Cargo
  • Anthropic API key (Claude)
  • A Python, Node.js, or executable MCP server to connect to

Setting Up Your Environment

First, create a new Rust project:

Replace the contents of Cargo.toml with the following:

Cargo.toml

The rmcp crate provides the Rust MCP SDK and child-process transport. This example uses the genai crate to send requests to Claude and represent tools in the model request.

Setting Up Your API Key

You’ll need an Anthropic API key from the Anthropic Console.Create a .env file to store it:

Add .env to your .gitignore:

Creating the Client

Open src/main.rs and replace its contents as you work through the following sections.

Imports and Client Structure

First, add the imports, model constant, and basic client structure:

The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.

Client Initialization

Next, initialize the model client and start without an MCP session or tools:

genai::Client::default() reads the ANTHROPIC_API_KEY environment variable when it sends a request.

Server Connection Management

Add this method inside the impl MCPClient block:

This method:

  1. Starts the server as a child process using the command and arguments supplied on the command line
  2. Establishes an MCP session over stdio
  3. Lists all tools advertised by the server
  4. Converts those tools into the format used in model requests

Converting MCP Tools

Add this function outside the impl MCPClient block:

MCP and model APIs describe tools with similar information but different Rust types. convert_tools maps each MCP tool’s name, description, and input schema into a genai tool definition.

Sending Model Requests

Add this helper method inside impl MCPClient:

This keeps model request handling in one place and adds useful context if the API request fails.

Query Processing Logic

Now add the core query-processing method inside impl MCPClient:

The method first sends the user’s query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.

Interactive Chat Interface

Add the interactive terminal loop inside impl MCPClient:

The loop accepts queries until the user types quit or closes standard input. Query errors are printed without terminating the client.

Cleanup

Add this method inside impl MCPClient to stop the MCP session and child process:

Main Entry Point

Finally, add the asynchronous entry point outside the impl MCPClient block:

The entry point loads .env, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.

Verify the Complete File

Before running the client, confirm the items in src/main.rs are placed at the correct scope:

  • new, connect_to_server, process_query, request_model, chat_loop, and cleanup are methods inside the single impl MCPClient block.
  • main and convert_tools are functions outside the impl MCPClient block.

Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the complete src/main.rs example, then check that it compiles:

Running the Client

Use cargo run -- followed by the command you would normally use to start the MCP server:

Running bare cargo run without a server command prints the usage message and exits.

The client will:

  1. Start and connect to the specified MCP server
  2. List the tools available from that server
  3. Start an interactive chat session where you can:
    • Enter queries
    • See tool executions
    • Get responses from Claude

How It Works

When you submit a query:

  1. The client sends your query and the server’s available tools to Claude
  2. Claude decides which tools, if any, to use
  3. The client executes requested tools through the MCP session
  4. Tool results are sent back to Claude
  5. Claude provides a natural language response
  6. The response is displayed in the terminal

Best Practices

  1. Error Handling
    • Add context to errors at process, MCP, model API, and serialization boundaries
    • Report individual query errors without terminating the interactive session
    • Validate server commands before running them
  2. Resource Management
    • Always cancel the MCP session during cleanup
    • Ensure cleanup runs even when connection or chat-loop operations fail
    • Avoid starting a second server while a session is active
  3. Security
    • Store API keys securely in .env
    • Review the tools exposed by a server before allowing model-driven calls
    • Connect only to servers and executable commands you trust

Troubleshooting

Server Command Issues

The arguments after cargo run -- must form a complete command. Interpreted server scripts need their runtime:

If a command cannot be found, use its absolute path or verify it is available in your PATH.

Environment File Issues

If you see Failed to load env file, ensure .env exists in the directory where you run the client.If the model request reports a missing API key, confirm that .env contains:

Tool and Response Errors

  • Unable to list tools from server: Verify the server starts successfully and communicates over stdio
  • Tool call ... failed: Verify the server tool’s required arguments and environment variables
  • Failed to serialize tool result: Inspect the server’s response for unsupported or malformed content

Next steps

Read the original on modelcontextprotocol.io ↗