MCP Client
A Python client library for interacting with Model Context Protocol (MCP) servers over HTTP.
Even though this was originally written for testing AAP MCP Server,
you should be able to use this for other MCP servers that use streamable HTTP for transport.
Features
- HTTP-based MCP communication - Connect to MCP servers using streamable HTTP transport
- Authentication support - Bearer token authentication with API keys
- Configurable TLS verification - Support for both self-signed certificates and verified TLS
- Category-based routing - Optional category endpoints for organizing MCP tools (for AAP MCP Server only)
- Async/await support - Full async support for modern Python applications
- Health checking - Built-in health check endpoint support
- Scenario execution - Execute custom MCP scenarios with initialized sessions
- Tool discovery - List available tools from MCP servers
- Proper resource cleanup - Automatic cleanup of HTTP connections to prevent hanging
Installation
Using uv (recommended)```bash
Install in development mode
uv pip install -e .
Or install from source
git clone https://github.com/TamiTakamiya/mcp-client.git
cd mcp-client
uv pip install -e .
### Using pip```bash
pip install -e .
Quick Start
Basic Usage```python
import asyncio
from mcpclient import MCPClient
async def main():
# Create client (TLS verification disabled for self-signed certs)
client = MCPClient(
base_url="https://your-mcp-server.com",
api_key="your-api-key",
category="job_management"
)
# Check server health
response = client.health_check()
print(f"Server status: {response.status_code}")
# Get available tools
tools = await client.get_tools()
for tool in tools:
print(f"Tool: {tool.name}")
asyncio.run(main())
### With TLS Verification```python
from mcpclient import MCPClient
# Enable TLS verification for production servers
client = MCPClient(
base_url="https://production-server.com",
api_key="your-api-key",
category="job_management",
verify_tls=True # Enable certificate verification
)
Running Custom Scenarios```python
from mcpclient import MCPClient
from mcp import ClientSession
async def my_scenario(session: ClientSession):
# List available tools
tools = await session.list_tools()
print(f"Found {len(tools.tools)} tools")
# Call a specific tool
result = await session.call_tool(
name="controller.job_templates_list",
arguments={"version": "v2"}
)
return result
async def main():
# Execute the scenario
client = MCPClient(base_url="https://server.com", api_key="key", category="job_management")
result = await client.run_a_scenario(my_scenario)
print(result)
asyncio.run(main())
## API Reference
### MCPClient
#### Constructor```python
MCPClient(
base_url: str,
api_key: str,
category: str | None = None,
verify_tls: bool = False
)
Parameters:
- base_url (str): Base URL of the MCP server (e.g., "https://example.com")
- api_key (str): API key for Bearer token authentication
- category (str | None): Optional category for endpoint routing
- verify_tls (bool): Enable TLS certificate verification (default: False)
Methods
health_check() -> httpx.Response
Check the server health status.```python
response = client.health_check()
assert response.status_code == 200
##### `async get_tools() -> list[types.Tool]`
Get available tools from the MCP server.```python
tools = await client.get_tools()
for tool in tools:
print(f"Tool: {tool.name}")
async run_a_scenario(scenario_func: Callable) -> Any
Run a custom scenario function with an initialized MCP session.```python
async def scenario(session: ClientSession):
tools = await session.list_tools()
return tools.tools
result = await client.run_a_scenario(scenario)
## Configuration
### Environment Variables
The client can be configured using environment variables:```bash
export SERVER_URL="https://your-mcp-server.com"
export API_KEY="your-api-key"
Then in your code:```python
import os
from mcpclient import MCPClient
client = MCPClient(
base_url=os.environ["SERVER_URL"],
api_key=os.environ["API_KEY"]
)
### TLS Configuration
For self-signed certificates (default):```python
client = MCPClient(base_url=url, api_key=key, verify_tls=False)
For production with valid certificates:```python
client = MCPClient(base_url=url, api_key=key, verify_tls=True)
## Testing
### Running Tests
Before starting tests, create the `.env` file to define environment variables that are required for running the tests.```bash
API_KEY=your-aap-api-key
SERVER_URL=your-mcp-server-url
The project uses pytest for testing:```bash
Install test dependencies
uv pip install -e ".[dev]"
Run all tests
uv run --env-file=.env pytest
Run specific test file
uv run --env-file=.env pytest tests/test_mcpserver.py
Run with verbose output
uv run --env-file=.env pytest -v
Run async tests only
uv run --env-file=.env pytest -k "asyncio"
### Test Configuration
Tests require environment variables:```bash
export SERVER_URL="https://test-server.com"
export API_KEY="test-api-key"
If these are not set, tests will be automatically skipped.
Running Tests with Coverage```bash
pytest --cov=mcpclient --cov-report=html
## Development
### Setup Development Environment```bash
# Clone the repository
git clone https://github.com/TamiTakamiya/mcp-client.git
cd mcp-client
# Install in development mode with dev dependencies
uv pip install -e ".[dev]"
# Run tests
pytest
Project Structure```
mcp-client/
├── mcpclient/ # Main package
│ ├── init.py # Package exports
│ └── mcpclient.py # MCPClient class
├── tests/ # Test files
│ └── test_mcpserver.py
├── pyproject.toml # Project configuration
└── README.md # This file
### Code Quality
The codebase includes:
- Type hints for all public APIs
- Comprehensive docstrings
- Logging support via Python's `logging` module
- Proper async resource cleanup
## Logging
The library uses Python's standard logging module:```python
import asyncio
import logging
from mcpclient import MCPClient
# Enable debug logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
async def main():
# Use the client - will log tool information
client = MCPClient(base_url="https://server.com", api_key="your-key")
tools = await client.get_tools()
print(f"Found {len(tools)} tools")
asyncio.run(main())
Troubleshooting
Tests Hanging
If async tests hang, ensure you're not creating client instances without proper cleanup. The library now uses lazy client creation to prevent this issue.
SSL Certificate Errors
If you encounter SSL certificate errors:
- For self-signed certificates: Use
verify_tls=False(default) - For production: Use
verify_tls=Trueand ensure valid certificates
Import Errors
If you get import errors:```bash
Reinstall in development mode
uv pip install -e .
```
Requirements
- Python >= 3.12
- mcp[cli] >= 1.20.0
- httpx (installed with mcp)
License
[Specify your license here]
Contributing
[Specify contribution guidelines here]
Support
For issues and questions, please open an issue on GitHub.
