A powerful Python library for creating Model Context Protocol (MCP) clients with seamless AI model integration
Project description
MCP Clients
A powerful and easy-to-use Python package for creating Model Context Protocol (MCP) clients that seamlessly integrate with AI models and external tools. Currently supports Google's Gemini AI with plans for additional model integrations.
Features
- ** Gemini AI Integration**: Built-in support for Google's Gemini 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
Prerequisites
- Python 3.12+
- Google Gemini API Key - Get yours from Google AI Studio
- MCP Server - A Model Context Protocol server (Python or JavaScript)
Configuration
Environment Variables
Create a .env file in your project root:
# Required: Your Gemini API key
GEMINI_API_KEY=your_gemini_api_key_here
# Optional: Default MCP server path
MCP_SERVER=/path/to/your/mcp_server.py
API Key Setup
- Visit Google AI Studio
- Create a new API key
- Add it to your
.envfile or pass it directly to the client
Quick Start
Basic Usage
import asyncio
from dotenv import load_dotenv
from mcp_clients import Gemini
load_dotenv()
async def main():
# Initialize the client
client = await Gemini.init(
server_script_path='path/to/your/mcp_server.py',
system_instruction='You are a helpful assistant.'
)
try:
# Start interactive chat
await client.chat_loop()
finally:
# Clean up resources
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 main 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
)
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
MCP Server Example
Here's a simple weather MCP server example:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("weather")
@mcp.tool()
async def get_weather(city: str) -> str:
"""Get weather information for a city."""
# Your weather API logic here
return f"The weather in {city} is sunny and 72°F"
@mcp.tool()
async def get_forecast(city: str, days: int = 3) -> str:
"""Get weather forecast for a city."""
# Your forecast logic here
return f"3-day forecast for {city}: Sunny, Partly Cloudy, Rainy"
if __name__ == "__main__":
mcp.run()
🔍 Troubleshooting
Common Issues
-
API Key Errors
Error: Invalid API key- Ensure your Gemini 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-clients - If installing from source:
pip install -e .
- Install the package:
🧪 Examples
Check out the examples/ directory for more usage examples:
- Basic Usage: Simple chat with MCP tools
- Weather Bot: Weather information assistant
- Custom Tools: Creating and using custom MCP tools
Roadmap
- Additional Model Support: OpenAI GPT, Anthropic Claude
- Advanced Tool Management: Tool discovery and validation
- Streaming Responses: Real-time response streaming
- Session Management: Persistent conversation sessions
- Plugin System: Extensible plugin architecture
- Web Interface: Optional web-based chat interface
🤝 Contributing
I welcome contributions! Here's how you can help:
Getting Started
-
Fork the repository
git clone https://github.com/yourusername/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
- Google for the Gemini AI API
- 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.2.tar.gz.
File metadata
- Download URL: mcp_clients-0.0.2.tar.gz
- Upload date:
- Size: 31.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a53abb64e7d7bf293edb26fffa06f062f84ab31eba9fb4df1a321f8aa5c7fd3c
|
|
| MD5 |
614115efd168029b714f79714c17a4f9
|
|
| BLAKE2b-256 |
1028e745288fcd884a25baaaaa8fc56df6036be48915e4e7cc7713e441d4182e
|
File details
Details for the file mcp_clients-0.0.2-py3-none-any.whl.
File metadata
- Download URL: mcp_clients-0.0.2-py3-none-any.whl
- Upload date:
- Size: 9.0 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 |
3e9837e6ff8b621e093d3bd3dd7d4b9d229a6c855a3537d7106e9469b0c3a52f
|
|
| MD5 |
3ce22d0a4c8c53418d4563a426838e05
|
|
| BLAKE2b-256 |
8bcd9952ca328b4419e2a7c57b8a56c2f0eae1c765d59ff2385a00928340101d
|