How to install mcp-use, Unified MCP Client Library
Table of Contents
- Introduction: What is MCP and
mcp-use
? - Prerequisites
- Installation
- Core Concepts of MCP
- Getting Started: Basic Usage
- Key Features and Usage Patterns (Based on
mcp-use
) - Advanced Examples and Use Cases
- Troubleshooting Common Issues
- Contributing to
mcp-use
- Conclusion
- License
1. Introduction: What is MCP and mcp-use
?
In the rapidly evolving landscape of machine learning and artificial intelligence, interacting with deployed models often requires standardized communication protocols. This is where the Model Context Protocol (MCP) comes into play.
Understanding MCP (Model Context Protocol)
MCP, or Model Context Protocol, is designed to facilitate standardized communication between clients and "Model Servers" or similar inference endpoints. While the specific details of the protocol are defined in its specification (potentially linked from the mcp-use
repository or other documentation), the core idea revolves around managing the context of interactions with a model.
What does "context" mean here? It often refers to:
- Session State: Maintaining information across multiple requests from the same client (e.g., conversation history for a chatbot).
- Configuration: Specifying model parameters or operational modes for an interaction.
- Resource Management: Handling the allocation and release of model resources on the server side.
By defining a standard protocol, MCP aims to simplify the development of both model serving infrastructure and the client applications that interact with them. It provides a common language and structure for requests and responses, abstracting away the underlying complexities of different model types or serving frameworks. Think of it like HTTP for web browsers and servers, but specialized for interacting with machine learning models.
Tired of Postman? Want a decent postman alternative that doesn't suck?
Apidog is a powerful all-in-one API development platform that's revolutionizing how developers design, test, and document their APIs.
Unlike traditional tools like Postman, Apidog seamlessly integrates API design, automated testing, mock servers, and documentation into a single cohesive workflow. With its intuitive interface, collaborative features, and comprehensive toolset, Apidog eliminates the need to juggle multiple applications during your API development process.
Whether you're a solo developer or part of a large team, Apidog streamlines your workflow, increases productivity, and ensures consistent API quality across your projects.
Introducing mcp-use
: The Unified Client
The mcp-use
library is a Python implementation designed to act as a Unified MCP Client. Its purpose is to provide developers with a straightforward and consistent way to interact with servers that implement the Model Context Protocol.
Instead of needing to manually handle socket connections, message formatting, context tracking, and protocol specifics, mcp-use
offers a higher-level API that simplifies these tasks. It allows developers to focus on the application logic rather than the intricacies of the MCP communication itself.
Key benefits of using mcp-use
include:
- Abstraction: Hides the low-level details of the MCP protocol.
- Simplicity: Provides an intuitive Python interface for connecting, sending requests, and receiving responses.
- Standardization: Ensures correct implementation of the client-side MCP interactions.
- Efficiency: (Potentially) Offers optimized communication handling.
Who is this Tutorial For?
This tutorial is aimed at:
- Python developers building applications that need to interact with machine learning models served via an MCP-compliant server.
- Researchers or engineers deploying models who need to test or interact with their MCP-based serving endpoints.
- Anyone interested in understanding how to use a standardized protocol client library for model interaction.
Basic familiarity with Python programming, package installation using pip
, and the concept of client-server communication is assumed.
What You'll Learn
By the end of this tutorial, you will be able to:
- Understand the purpose of MCP and the role of
mcp-use
. - Install the
mcp-use
library correctly. - Initialize and configure the MCP client.
- Connect to an MCP server.
- Send requests and receive responses using the library.
- Handle basic errors and understand common usage patterns.
- Find resources for further information and potential contribution.
2. Prerequisites
Before you begin, ensure you have the following installed:
- Python:
mcp-use
requires Python. Check thesetup.py
orpyproject.toml
file in the GitHub repository for the specific minimum version required (typically Python 3.7+ or newer). You can check your Python version by running:python --version # or python3 --version
- pip: The Python package installer. It usually comes bundled with Python. You can check if it's installed and update it using:
python -m pip --version python -m pip install --upgrade pip
- Access to an MCP Server: To fully test the client library, you'll need the address (hostname or IP) and port of a running server that implements the Model Context Protocol. For development or testing purposes, you might have a local instance or be provided with connection details for a remote one.
3. Installation
Installing mcp-use
is straightforward using pip
. It's highly recommended to use a virtual environment to avoid conflicts with other project dependencies.
Setting up a Virtual Environment (Recommended)
Create a virtual environment: Open your terminal or command prompt, navigate to your project directory, and run:
python -m venv mcp_env # You can replace 'mcp_env' with your preferred environment name
Activate the virtual environment:
- On macOS/Linux:
source mcp_env/bin/activate
- On Windows:
.\mcp_env\Scripts\activate
You should see the environment name (e.g.,
(mcp_env)
) prefixed to your command prompt line, indicating it's active.- On macOS/Linux:
Installing mcp-use
via pip
With your virtual environment activated (or globally, if you prefer), install the library using pip
:
pip install mcp-use
Pip will download and install mcp-use
and any necessary dependencies.
Verifying the Installation
You can verify that the library was installed correctly by trying to import it in a Python interpreter or by using pip show
:
Using
pip show
:pip show mcp-use
This command should display information about the installed package, including its name, version, and location.
Using Python Interpreter: Start a Python interpreter:
python
Then try importing the main client class (assuming it's
MCPClient
based on common patterns - check the library's actual usage examples):>>> try: ... from mcp_use import MCPClient ... print("Successfully imported MCPClient from mcp_use!") ... except ImportError: ... print("Error: Could not import MCPClient from mcp_use.") ... >>> exit()
If you see the success message, the installation is likely correct.
4. Core Concepts of MCP
Understanding the concepts behind MCP helps in using mcp-use
effectively.
Client-Server Architecture
MCP operates on a classic client-server model:
- MCP Server: Hosts the machine learning model(s) and exposes an endpoint that listens for connections adhering to the MCP protocol. It processes incoming requests, interacts with the model, manages context, and sends back responses.
- MCP Client (
mcp-use
): Your application uses themcp-use
library to initiate connections, format requests according to the MCP specification, send them to the server, receive responses, and handle the communication lifecycle.
Context Management
This is a key aspect of MCP. The protocol likely defines mechanisms for:
- Establishing Context: Starting a session with the server, potentially receiving a context ID.
- Maintaining Context: Sending subsequent requests within the same context, allowing the server to retain state (like conversation history or intermediate computations).
- Closing Context: Signaling the end of a session, allowing the server to release associated resources.
mcp-use
should provide methods or patterns to manage this context lifecycle implicitly or explicitly.
Communication Protocol
MCP defines the precise rules for communication:
- Connection: How clients establish and terminate connections with the server.
- Message Format: The structure of requests and responses (e.g., using JSON, Protobuf, or a custom binary format). This includes headers, payloads, and status indicators.
- Operations: Standardized operations the client can invoke (e.g.,
invoke
,get_metadata
,create_context
,delete_context
). - Error Handling: How errors are reported from the server back to the client.
mcp-use
implements these rules on the client side, ensuring compliance with the protocol.
5. Getting Started: Basic Usage
Let's walk through the fundamental steps of using mcp-use
to communicate with an MCP server. Note: The exact class names and method names (MCPClient
, connect
, invoke
, close
) are based on common patterns and the likely structure inferred from the repository name. Refer to the actual examples in the mcp-use
repository for precise usage.
Assume you have an MCP server running at mcp.example.com
on port 12345
.
Importing the Client
First, import the necessary class from the library:
from mcp_use import MCPClient
Initializing the MCP Client
Create an instance of the client, providing the server's host and port:
# Replace with your actual server host and port
server_host = "mcp.example.com"
server_port = 12345
client = MCPClient(host=server_host, port=server_port)
print(f"MCP Client initialized for {server_host}:{server_port}")
The MCPClient
constructor might accept other parameters for configuration (e.g., timeouts, security credentials). Check the library's documentation or source code for details.
Connecting to the Server
Before sending requests, you usually need to establish a connection.
try:
# Establish the connection (might be handled automatically by invoke,
# or might be an explicit step like this)
client.connect()
print("Successfully connected to the MCP server.")
except ConnectionRefusedError:
print(f"Error: Connection refused. Is the server running at {server_host}:{server_port}?")
exit()
except Exception as e:
print(f"An error occurred during connection: {e}")
exit()
(Self-correction: Some client libraries handle connection implicitly when the first request is made. Check mcp-use
specifics. If connect
is not needed explicitly before the first invoke
, adjust this step).
Sending Requests (Invoking Operations)
The core interaction involves sending data or commands to the server, often via an invoke
or send
method. The structure of the request data depends heavily on the MCP server implementation and the specific model operation you want to perform.
# Example request data (structure depends on the server/model)
request_data = {
"operation": "predict",
"payload": {
"text": "What is the capital of France?"
},
"context_id": None # Or provide an existing context ID if needed
}
try:
print(f"Sending request: {request_data}")
# The method might be called 'invoke', 'send', 'call', etc.
# It might take the request data directly or require specific arguments.
response = client.invoke(request_data) # Or client.send(request_data), etc.
print("Received response from server.")
except Exception as e:
print(f"An error occurred while sending request or receiving response: {e}")
# Consider closing the connection here if the error is severe
client.close()
exit()
Handling Responses
The response
variable will contain the data returned by the server. Its format is defined by the MCP protocol and the server's implementation. You'll need to parse it accordingly.
# Assuming response is a dictionary-like object or can be parsed into one
if response:
print("Response Content:")
# Print structure might vary greatly
print(response)
# Example: Accessing specific parts of the response
if isinstance(response, dict):
status = response.get("status")
result = response.get("result")
error_message = response.get("error")
if status == "success" and result:
print(f" Status: {status}")
print(f" Result: {result}")
elif status == "error":
print(f" Status: {status}")
print(f" Error: {error_message}")
else:
print(" Response format unclear or status missing.")
else:
print("Received an empty or invalid response.")
Closing the Connection
Once you are done interacting with the server, it's crucial to close the connection to release resources on both the client and server sides.
# Close the connection
client.close()
print("Connection closed.")
Using a try...finally
block is good practice to ensure the connection is closed even if errors occur:
client = MCPClient(host=server_host, port=server_port)
try:
client.connect() # If explicit connection is needed
# ... send requests and handle responses ...
response = client.invoke(request_data)
print(f"Response: {response}")
finally:
# This block executes whether an error occurred or not
print("Closing connection in finally block.")
client.close()
Putting it Together: A Simple Example
from mcp_use import MCPClient # Assuming this is the correct import
# --- Configuration ---
server_host = "127.0.0.1" # Use localhost if running server locally
server_port = 12345 # Replace with your MCP server port
# --- Initialize Client ---
client = MCPClient(host=server_host, port=server_port)
print(f"MCP Client initialized for {server_host}:{server_port}")
try:
# --- Connect (if needed explicitly) ---
# client.connect()
# print("Connected to server.")
# --- Prepare Request ---
# This structure is hypothetical - adapt to your server's needs
request_data = {
"operation": "get_greeting",
"payload": {"name": "Alice"},
"context_id": None
}
print(f"Sending request: {request_data}")
# --- Send Request and Receive Response ---
# Adjust method name ('invoke', 'send', etc.) based on the library
response = client.invoke(request_data)
print("Received response.")
# --- Process Response ---
if response:
print("Response Content:")
print(response)
# Add more detailed parsing based on expected response format
if isinstance(response, dict):
greeting = response.get("result", {}).get("message")
if greeting:
print(f"Server says: {greeting}")
else:
print("Received an empty response.")
except ConnectionRefusedError:
print(f"Error: Connection refused. Check if server is running at {server_host}:{server_port}.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# --- Close Connection ---
if client: # Ensure client was initialized
print("Closing connection.")
client.close()
print("Script finished.")
6. Key Features and Usage Patterns (Based on mcp-use
)
(This section requires specific knowledge from the mcp-use
repository. Below are common possibilities. Check the repository's README or examples for accuracy).
Synchronous vs. Asynchronous Operations (if applicable)
Modern Python libraries often support asynchronous operations using asyncio
. Check if mcp-use
provides an AsyncMCPClient
or if the standard client has async
methods (e.g., await client.connect()
, await client.invoke(...)
). Using async I/O can be beneficial for applications that need to handle many concurrent MCP requests efficiently.
Example (Hypothetical Async Usage):
# import asyncio
# from mcp_use import AsyncMCPClient # Hypothetical async client
# async def main():
# async_client = AsyncMCPClient(host=server_host, port=server_port)
# try:
# await async_client.connect()
# response = await async_client.invoke(request_data)
# print(f"Async Response: {response}")
# finally:
# await async_client.close()
# if __name__ == "__main__":
# asyncio.run(main())
Error Handling
Robust applications need proper error handling. Besides ConnectionRefusedError
, mcp-use
might raise custom exceptions for:
- Protocol Errors: Malformed messages, unexpected responses.
- Timeout Errors: Server not responding within a specified time.
- Server-Side Errors: Errors reported by the MCP server itself (e.g., invalid operation, model loading failure), which might be indicated in the response payload.
Wrap your client interactions in try...except
blocks, catching specific exceptions provided by mcp-use
where possible.
# from mcp_use import MCPProtocolError, MCPTimeoutError # Hypothetical exceptions
# try:
# response = client.invoke(request_data)
# # Check response content for server-reported errors
# if isinstance(response, dict) and response.get("status") == "error":
# print(f"Server Error: {response.get('error')}")
# except MCPTimeoutError:
# print("Error: Request timed out.")
# except MCPProtocolError as e:
# print(f"Error: MCP Protocol violation: {e}")
# except Exception as e:
# print(f"An unexpected error: {e}")
Data Serialization/Deserialization
The library likely handles the conversion of your Python request data (e.g., dictionaries) into the byte format required by MCP and converts the received bytes back into Python objects. Check if you need to use specific data types or structures, or if common types like dictionaries, lists, strings, and numbers are automatically handled (e.g., via JSON).
7. Advanced Examples and Use Cases
Example: Multi-Turn Interaction (Conceptual)
If MCP and your server support context management for conversations:
# --- Start Conversation (get context ID) ---
initial_request = {"operation": "start_chat", "payload": {}}
response = client.invoke(initial_request)
context_id = response.get("context_id") if isinstance(response, dict) else None
if not context_id:
print("Failed to start chat context.")
client.close()
exit()
print(f"Started chat with context ID: {context_id}")
# --- Send follow-up message ---
follow_up_request = {
"operation": "continue_chat",
"payload": {"text": "Tell me more about that."},
"context_id": context_id # Use the received context ID
}
response = client.invoke(follow_up_request)
print(f"Follow-up Response: {response}")
# --- End Conversation ---
end_request = {"operation": "end_chat", "context_id": context_id}
client.invoke(end_request)
print("Chat context ended.")
Example: Sending Structured Data
If your model expects complex input:
complex_request = {
"operation": "analyze_image",
"payload": {
"image_bytes": b"...", # Base64 encoded or raw bytes, depending on server
"parameters": {"threshold": 0.75, "regions": ["face", "text"]}
},
"context_id": None
}
response = client.invoke(complex_request)
print(f"Analysis Response: {response}")
8. Troubleshooting Common Issues
Connection Errors
ConnectionRefusedError
: Server is not running, firewall blocking the port, or wrong host/port specified. Double-check server status and connection details.- Timeouts: Server is running but unresponsive or network latency is high. Check server load, network conditions, or increase client timeout settings (if configurable in
mcp-use
).
Installation Problems
- Ensure you have the correct Python version and
pip
is up-to-date. - Use a virtual environment to prevent conflicts.
- Check network connection if
pip install
fails to download packages. - Look for specific error messages during installation (e.g., missing system dependencies if the library relies on C extensions).
Unexpected Responses
- Check Request Format: Ensure the data you send matches exactly what the MCP server expects for the specific operation.
- Check Server Logs: Server logs often provide detailed information about why a request failed or produced an unexpected result.
- Verify Protocol Version: If MCP has different versions, ensure the client (
mcp-use
) and server are compatible. - Parse Response Correctly: Make sure your client-side code correctly interprets the structure (e.g., JSON, dictionary keys) of the response sent by the server.
9. Contributing to mcp-use
Open-source projects thrive on community contributions. If you find bugs, have ideas for improvements, or want to add features to mcp-use
:
- Check the GitHub Repository: Look for a
CONTRIBUTING.md
file, which usually outlines the contribution process (how to report issues, submit pull requests, coding standards, etc.). - Issues: Use the GitHub Issues tab to report bugs or suggest features. Check if a similar issue already exists.
- Pull Requests: If you've made code changes, you can submit a Pull Request. Ensure you follow the project's guidelines, write tests for your changes, and update documentation if necessary.
10. Conclusion
mcp-use
provides a valuable tool for Python developers needing to interact with Model Context Protocol servers. By abstracting the protocol's complexities, it allows you to integrate ML model interactions into your applications more easily and reliably. This tutorial has covered the essentials from installation and basic usage to core concepts and troubleshooting.
For the most accurate and detailed information, always refer to the official mcp-use
GitHub repository: https://github.com/pietrozullo/mcp-use
Remember to adapt the code examples based on the specific requirements of your MCP server and the exact API provided by the mcp-use
library version you are using.