Model Context Protocol Clients SDK
Project description
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 Gemini
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!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcp_clients-0.0.3.tar.gz.
File metadata
- Download URL: mcp_clients-0.0.3.tar.gz
- Upload date:
- Size: 36.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
791f8eb3b44f6f4f092f139b5ef5927cfbd44f7d15a845d9d8c022d9f40fa3e1
|
|
| MD5 |
36223bd5ff5a5d9e22d9a0bea93704ec
|
|
| BLAKE2b-256 |
47473287053c13f36168e73f2d7f7d26babaaa537f2c41db5ac9de60701d578f
|
File details
Details for the file mcp_clients-0.0.3-py3-none-any.whl.
File metadata
- Download URL: mcp_clients-0.0.3-py3-none-any.whl
- Upload date:
- Size: 12.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5033564979e54204e70383afd05bc91baaf2fa33e166c39845bf6e0db1f23a41
|
|
| MD5 |
a18cabea8e8890a5292c8abe2b14e46d
|
|
| BLAKE2b-256 |
d7d508d276a1c963ec6734c641a5becd5b2a062a982553ea09f28f80f097c1a8
|