Python MCP Clients: Framework for LLM-Driven Tool Orchestration
mcp-clients is an open-source Python SDK designed for building and orchestrating LLM-powered tools using the Model Context Protocol (MCP). It allows seamless integration with OpenAI and Gemini, enabling natural language interactions with databases, file systems, APIs, and more. Developers can easily connect to multiple MCP servers through a unified interface and create intelligent agents that interact with real-world tools. It is free to use, modify, and distribute under the MIT license.
Features
- AI Models Integration: Built-in support for Google's Gemini and OpenAI models
- MCP Protocol Support: Seamless integration with MCP servers
- Tool Calling: Automatic tool discovery and execution
- Interactive Chat: Built-in chat interface with conversation history
- Customizable: Support for custom chat loops and system instructions
- Easy Setup: Simple configuration with environment variables
- Async/Await: Fully asynchronous for optimal performance
Installation
Install using pip:
pip install mcp-clients
Or install from uv:
uv add mcp-clients
Configuration
Environment Variables
Create a .env file in your project root:
# Required: Your API key
YOUR_API_KEY=your_api_key_here
# Required: Your MCP server path
MCP_SERVER=/path/to/your/mcp_server.py
Quick Start
Basic Usage with OpenAI
import asyncio
from dotenv import load_dotenv
from mcp_clients import OpenAI
load_dotenv()
async def main():
client = await OpenAI.init(
server_script_path="path_to_server_script",
)
try:
await client.chat_loop()
finally:
await client.cleanup()
if __name__ == "__main__":
asyncio.run(main())
Basic Usage with Gemini
import asyncio
from dotenv import load_dotenv
from mcp_clients import Gemini
load_dotenv()
async def main():
client = await Gemini.init(
server_script_path="path_to_server_script",
)
try:
await client.chat_loop()
finally:
await client.cleanup()
if __name__ == "__main__":
asyncio.run(main())
Custom Chat Loop
async def custom_chat_handler(client):
"""Custom chat loop with enhanced features"""
print("Enhanced Chat Started!")
print("Commands: 'help', 'history', 'clear', 'quit'")
while True:
try:
query = input("\n💬 You: ").strip()
if query.lower() == 'quit':
break
elif query.lower() == 'help':
print("Available commands: help, history, clear, quit")
continue
elif query.lower() == 'history':
print(f"Conversation has {len(client.history)} messages")
continue
elif query.lower() == 'clear':
client.history = []
print("Chat history cleared!")
continue
response = await client.process_query(query)
print(f"🤖 Assistant: {response}")
except KeyboardInterrupt:
break
except Exception as e:
print(f"Error: {e}")
# Use the custom chat loop
async def main():
client = await Gemini.init(
server_script_path='weather_server.py',
custom_chat_loop=custom_chat_handler
)
try:
await client.chat_loop()
finally:
await client.cleanup()
API Reference
Gemini Class
The Gemini client class for interacting with Gemini AI through MCP servers.
Initialization
client = await Gemini.init(
api_key=None, # Gemini API key (or use env var)
server_script_path=None, # Path to MCP server script
model="gemini-2.5-flash", # Gemini model to use
system_instruction=None, # Custom system instruction
custom_chat_loop=None # Custom chat loop function
)
OpenAI Class
The OpenAI client class for interacting with Gemini AI through MCP servers.
Initialization
client = await OpenAI.init(
api_key=None, # Gemini API key (or use env var)
server_script_path=None, # Path to MCP server script
model="gpt-4.1-nano", # OpenAI model to use
system_instruction=None, # Custom system instruction
custom_chat_loop=None # Custom chat loop function
)
Methods
process_query(query: str) -> str: Process a single querychat_loop(): Start interactive chat sessioncleanup(): Clean up resources (always call this!)connect_to_server(): Manually connect to MCP server
🔍 Troubleshooting
Common Issues
-
API Key Errors
Error: Invalid API key- Ensure your API key is correct
- Check that the API key is properly set in your environment
-
Server Connection Issues
Error: Server script must be a .py or .js file- Verify your MCP server script path is correct
- Ensure the file has the proper extension (.py or .js)
-
Import Errors
ModuleNotFoundError: No module named 'mcp_clients'- Install the package:
pip install mcp-clientsoruv add mcp-clients - If installing from source:
pip install -e .
- Install the package:
Examples
Check out the examples/ directory for more usage examples:
- gemini_client: Simple chat with MCP tools using Gemini.
- openai_client: Simple chat with MCP tools using OpenAI.
Contributing
I welcome contributions! Here's how you can help:
Getting Started
-
Fork the repository
git clone https://github.com/faizrazadec/mcp-clients.git cd mcp-clients
-
Set up development environment
uv venv source .venv/bin/activate # On Windows: venv\Scripts\activate uv sync
-
Create a feature branch
git checkout -b feature/your-feature-name
Development Guidelines
- Code Style: Follow PEP 8 and use
blackfor formatting - Type Hints: Add type hints to all functions and methods
- Documentation: Add docstrings and update README if needed
- Testing: Write tests for new features (pytest)
- Commits: Use conventional commit messages
Types of Contributions
- Bug Fixes: Fix issues and improve stability
- New Features: Add new models, tools, or capabilities
- Documentation: Improve docs, examples, and tutorials
- Testing: Add tests and improve test coverage
- UI/UX: Improve user experience and interfaces
Submitting Changes
-
Run tests (when available)
pytest
-
Format code
cd mcp_clients/ black .
-
Submit a pull request
- Describe your changes clearly
- Link any related issues
- Include examples if applicable
Code of Conduct
Please be respectful and inclusive. We're building this together! 🌟
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Anthropic for the Model Context Protocol specification
- FastMCP for the excellent MCP server framework
- Contributors who help make this project better
Made with ❤️ by Muhammad Faiz Raza
If you find this project helpful, please consider giving it a ⭐ on GitHub!
Metadata
Release files for mcp-clients 0.0.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| mcp_clients-0.0.4.tar.gz | 36.8 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mcp_clients-0.0.4-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 48.9 kB
Release files / mcp_clients-0.0.4.tar.gz
| Download URL | mcp_clients-0.0.4.tar.gz |
|---|---|
| Size | 36.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d2579c04afeff87eb64fc66175012f88992066fab518057587f5760778d3ea7c
|
|
BLAKE2b-256 checksum How to use checksums |
f191228119f771fc2a800919793503ac4eccf0bcc9f7071f0a9aa09ddae3b57e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.3
|
Release files / mcp_clients-0.0.4-py3-none-any.whl
| Download URL | mcp_clients-0.0.4-py3-none-any.whl |
|---|---|
| Size | 12.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
029da02ca0f63bec309460c6840c6f39b428e8b48755787e4d1e63cccfca0332
|
|
BLAKE2b-256 checksum How to use checksums |
739b2787b483001a0e55fd77bd29942f82585a304bef0ed3c587930b9e5722a5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.3
|
Security for mcp-clients 0.0.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.