Powerful JSON-RPC microservices framework with built-in security, authentication, and proxy registration
Project description
MCP Proxy Adapter
A powerful framework for creating JSON-RPC-enabled microservices with built-in security, authentication, and proxy registration capabilities.
🚀 Quick Install
pip install mcp-proxy-adapter
✨ Key Features
- 🔒 Security First: Built-in mTLS, JWT, API Key authentication
- 🌐 JSON-RPC 2.0: Complete protocol implementation
- 🔄 Proxy Registration: Automatic service discovery and registration
- ⚡ High Performance: Built on FastAPI with async support
- 🛡️ Role-Based Access: Fine-grained permission control
- 📡 Universal Client: Supports all authentication methods
🏃♂️ Quick Example
Create a secure JSON-RPC microservice in minutes:
from mcp_proxy_adapter import create_app, Command, SuccessResult
# Create a custom command
class HelloCommand(Command):
name = "hello"
description = "Say hello"
async def execute(self, **kwargs) -> SuccessResult:
name = kwargs.get("name", "World")
return SuccessResult(f"Hello, {name}!")
# Create and run the application
app = create_app()
📖 Full Documentation - Complete usage guide, examples, and API reference.
📋 Usage Examples
Basic Server Setup
from mcp_proxy_adapter import create_app
import uvicorn
app = create_app()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
With Security Configuration
from mcp_proxy_adapter import create_app
from mcp_proxy_adapter.config import Config
# Load configuration
config = Config.from_file("config.json")
app = create_app(config)
Client Usage
from mcp_proxy_adapter.core.client import UniversalClient
async def main():
async with UniversalClient({"server_url": "http://localhost:8000"}) as client:
result = await client.execute_command("help")
print(result)
import asyncio
asyncio.run(main())
🔧 Requirements
- Python: 3.9+
- Dependencies:
fastapi- Web frameworkpydantic- Data validationhypercorn- ASGI servermcp_security_framework- Security componentsjsonrpc- JSON-RPC protocol
Features
- JSON-RPC Framework: Complete JSON-RPC 2.0 implementation
- Security Integration: Built-in support for mcp_security_framework
- Authentication: Multiple auth methods (API Key, JWT, Certificate, Basic Auth)
- Proxy Registration: Automatic registration and discovery of services
- Command System: Extensible command framework with role-based access control
- SSL/TLS Support: Full SSL/TLS support including mTLS
- Async Support: Built on FastAPI with full async support
- Extensible: Plugin system for custom commands and middleware
Quick Start
Installation
pip install mcp-proxy-adapter
Detailed Usage Guide
Step 1: Initialize Working Environment
Первый шаг - создание изолированного рабочего окружения с помощью скрипта копирования:
# Создание рабочего окружения
python scripts/init_working_environment.py my_test_env
# Переход в созданную директорию
cd my_test_env
Что делает скрипт init_working_environment.py:
- Создает изолированную директорию с именем, которое вы указали
- Копирует все примеры из проекта:
basic_framework/- базовый пример приложенияfull_application/- полный пример с proxy endpointsuniversal_client.py- универсальный клиент
- Копирует утилитарные скрипты:
config_generator.py- генератор конфигурацийcreate_certificates_simple.py- генератор сертификатов
- Копирует тестовые скрипты:
generate_certificates_and_tokens.py- генерация сертификатов и токеновsetup_test_environment.py- настройка тестового окруженияtest_config.py- тестирование конфигурацийgenerate_test_configs.py- генерация тестовых конфигурацийtest_proxy_registration.py- тестирование proxy registration
- Автоматически генерирует конфигурации для всех режимов работы
- Создает сертификаты для SSL и mTLS тестирования
- Создает локальную документацию в виде README.md
Step 2: Генерация конфигураций
После создания рабочего окружения, сгенерируйте тестовые конфигурации:
# Генерация всех типов конфигураций
python scripts/generate_test_configs.py --output-dir configs
# Просмотр созданных конфигураций
ls -la configs/
Создаются следующие конфигурации:
http_simple.json- HTTP без аутентификацииhttp_token.json- HTTP с токен аутентификациейhttps_simple.json- HTTPS без аутентификацииhttps_token.json- HTTPS с токен аутентификациейmtls_no_roles.json- mTLS без ролейmtls_with_roles.json- mTLS с ролямиroles.json- конфигурация ролей и разрешений
Step 3: Запуск базового примера
Начните с самого простого примера - HTTP без аутентификации:
# Запуск сервера с HTTP конфигурацией
python examples/basic_framework/main.py --config configs/http_simple.json
В другом терминале протестируйте подключение:
# Тестирование базовой функциональности
python scripts/test_config.py --config configs/http_simple.json
Step 4: Тестирование различных режимов безопасности
HTTP с токен аутентификацией
# Запуск сервера
python examples/basic_framework/main.py --config configs/http_token.json
# Тестирование в другом терминале
python scripts/test_config.py --config configs/http_token.json
HTTPS с сертификатами
# Запуск сервера
python examples/basic_framework/main.py --config configs/https_simple.json
# Тестирование в другом терминале
python scripts/test_config.py --config configs/https_simple.json
mTLS (Mutual TLS) аутентификация
# Запуск сервера с mTLS
python examples/basic_framework/main.py --config configs/mtls_no_roles.json
# Тестирование в другом терминале
python scripts/test_config.py --config configs/mtls_no_roles.json
Step 5: Тестирование Proxy Registration
Запустите полный тест всех режимов proxy registration:
# Полный тест proxy registration для всех режимов
python scripts/test_proxy_registration.py
Этот тест проверит:
- ✅ HTTP без ролей
- ✅ HTTP с ролями
- ✅ HTTPS без ролей
- ✅ HTTPS с ролями
- ✅ mTLS без ролей
- ✅ mTLS с ролями
Step 6: Использование универсального клиента
Универсальный клиент поддерживает все режимы аутентификации:
Создание конфигурации клиента
# Пример конфигурации для mTLS
cat > client_config.json << 'EOF'
{
"server_url": "https://127.0.0.1:8443",
"timeout": 30,
"retry_attempts": 3,
"retry_delay": 1,
"security": {
"auth_method": "certificate",
"ssl": {
"enabled": true,
"check_hostname": false,
"verify": false,
"ca_cert_file": "./certs/ca_cert.pem"
},
"certificate": {
"enabled": true,
"cert_file": "./certs/admin_cert.pem",
"key_file": "./certs/admin_key.pem"
}
}
}
EOF
Тестирование с помощью клиента
# Тестирование подключения
python examples/universal_client.py --config client_config.json --test-connection
# Выполнение команды help
python examples/universal_client.py --config client_config.json --method help
# Регистрация в proxy
python examples/universal_client.py --config client_config.json --method proxy_register --params '{"server_id": "test-server", "server_url": "http://127.0.0.1:8001", "server_name": "Test Server"}'
Step 7: Работа с полным примером приложения
Запустите полный пример с proxy endpoints:
# Запуск полного примера
python examples/full_application/main.py --config configs/mtls_with_roles.json
Этот пример включает:
- Proxy discovery endpoint (
/proxy/discover) - Server registration endpoint (
/proxy/register) - Heartbeat endpoint (
/proxy/heartbeat) - Server unregistration endpoint (
/proxy/unregister)
Тестирование proxy endpoints
# Discovery - получение информации о proxy
curl -X GET "https://127.0.0.1:8443/proxy/discover" \
--cert ./certs/admin_cert.pem \
--key ./certs/admin_key.pem \
--cacert ./certs/ca_cert.pem
# Registration - регистрация сервера
curl -X POST "https://127.0.0.1:8443/proxy/register" \
-H "Content-Type: application/json" \
-d '{
"server_id": "test-server-1",
"server_url": "http://127.0.0.1:8001",
"server_name": "Test Server",
"description": "Test server for proxy registration",
"version": "1.0.0",
"capabilities": ["jsonrpc", "rest"],
"endpoints": {
"jsonrpc": "/api/jsonrpc",
"rest": "/cmd",
"health": "/health"
},
"auth_method": "certificate",
"security_enabled": true
}' \
--cert ./certs/admin_cert.pem \
--key ./certs/admin_key.pem \
--cacert ./certs/ca_cert.pem
# Heartbeat - отправка heartbeat
curl -X POST "https://127.0.0.1:8443/proxy/heartbeat" \
-H "Content-Type: application/json" \
-d '{
"server_id": "test-server-1",
"server_key": "returned_server_key",
"timestamp": 1234567890,
"status": "healthy"
}' \
--cert ./certs/admin_cert.pem \
--key ./certs/admin_key.pem \
--cacert ./certs/ca_cert.pem
Step 8: Создание собственных команд
Создайте собственную команду, наследуясь от базового класса:
from mcp_proxy_adapter.commands.base import Command
from mcp_proxy_adapter.core.result import SuccessResult, ErrorResult
class MyCustomCommand(Command):
name = "my_command"
description = "Моя собственная команда"
async def execute(self, **kwargs) -> SuccessResult:
param1 = kwargs.get("param1", "default_value")
# Ваша логика здесь
result = f"Выполнена команда с параметром: {param1}"
return SuccessResult(result)
Структура созданного рабочего окружения
После выполнения init_working_environment.py у вас будет следующая структура:
my_test_env/
├── examples/ # Примеры приложений
│ ├── basic_framework/
│ ├── full_application/
│ └── universal_client.py
├── scripts/ # Скрипты для тестирования
│ ├── generate_test_configs.py
│ ├── test_proxy_registration.py
│ ├── test_config.py
│ └── ...
├── configs/ # Сгенерированные конфигурации
│ ├── http_simple.json
│ ├── https_simple.json
│ ├── mtls_no_roles.json
│ ├── mtls_with_roles.json
│ └── roles.json
├── certs/ # Сертификаты для SSL/mTLS
│ ├── ca_cert.pem
│ ├── server_cert.pem
│ ├── admin_cert.pem
│ ├── user_cert.pem
│ └── ...
├── keys/ # Приватные ключи
│ ├── server_key.pem
│ ├── admin_key.pem
│ └── ...
└── README.md # Локальная документация
Troubleshooting
Распространенные проблемы и решения
1. Проблемы с сертификатами mTLS:
# Проверьте, что сертификаты созданы
ls -la certs/
ls -la keys/
# Проверьте содержимое сертификатов
openssl x509 -in certs/admin_cert.pem -text -noout
openssl x509 -in certs/ca_cert.pem -text -noout
2. Ошибки подключения:
# Проверьте, что порт свободен
netstat -tlnp | grep :8443
# Или используйте lsof
lsof -i :8443
3. Ошибки импортов:
# Убедитесь, что виртуальное окружение активировано
source .venv/bin/activate
# Проверьте установку зависимостей
pip list | grep mcp
pip list | grep hypercorn
4. Проблемы с правами доступа:
# Убедитесь, что файлы сертификатов доступны для чтения
chmod 644 certs/*.pem
chmod 600 keys/*.pem
Конфигурационные файлы
Структура конфигурации сервера
{
"server": {
"host": "127.0.0.1",
"port": 8000
},
"ssl": {
"enabled": true,
"cert_file": "./certs/server_cert.pem",
"key_file": "./certs/server_key.pem",
"ca_cert": "./certs/ca_cert.pem",
"verify_client": true
},
"security": {
"enabled": true,
"auth": {
"enabled": true,
"methods": ["certificate"]
},
"permissions": {
"enabled": true,
"roles_file": "./configs/roles.json"
}
},
"commands": {
"auto_discovery": true,
"builtin_commands": ["echo", "health", "config"]
},
"logging": {
"level": "INFO",
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
}
Структура конфигурации клиента
{
"server_url": "https://127.0.0.1:8443",
"timeout": 30,
"retry_attempts": 3,
"retry_delay": 1,
"security": {
"auth_method": "certificate",
"ssl": {
"enabled": true,
"check_hostname": false,
"verify": false,
"ca_cert_file": "./certs/ca_cert.pem"
},
"certificate": {
"enabled": true,
"cert_file": "./certs/admin_cert.pem",
"key_file": "./certs/admin_key.pem"
}
}
}
API Reference
Основные endpoints
GET /health- Проверка здоровья сервисаPOST /api/jsonrpc- JSON-RPC endpointGET /proxy/discover- Proxy discovery (только в full_application)POST /proxy/register- Регистрация сервера в proxyPOST /proxy/heartbeat- Отправка heartbeatPOST /proxy/unregister- Отмена регистрации сервера
JSON-RPC методы
echo- Возврат переданных параметровhelp- Список доступных командconfig- Информация о конфигурацииproxy_discover- Обнаружение proxyproxy_register- Регистрация в proxyproxy_heartbeat- Отправка heartbeat
Development
Настройка среды разработки
# Клонирование репозитория
git clone https://github.com/maverikod/mcp-proxy-adapter.git
cd mcp-proxy-adapter
# Создание виртуального окружения
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Установка зависимостей
pip install -e ".[dev]"
Запуск тестов
# Запуск всех тестов
pytest tests/
# Запуск с покрытием кода
pytest --cov=mcp_proxy_adapter tests/
# Запуск конкретного теста
pytest tests/test_proxy_registration.py -v
Запуск примеров в режиме разработки
# Запуск сервера в режиме разработки
python -m mcp_proxy_adapter.main --config examples/server_configs/config_simple.json --reload
# Запуск с отладкой
PYTHONPATH=. python examples/basic_framework/main.py --config configs/http_simple.json --debug
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
MIT License - see LICENSE file for details.
Author
Vasiliy Zdanovskiy - vasilyvz@gmail.com
🤝 Support & Contributing
- 📧 Email: vasilyvz@gmail.com
- 🐛 Issues: GitHub Issues
- 📚 Documentation: GitHub Wiki
- 💬 Discussions: GitHub Discussions
📄 License
MIT License - see LICENSE file for details.
📊 Version
6.2.9 - Production-ready release with comprehensive security, proxy registration, and PyPI optimization.
Built with ❤️ for secure microservices development
Быстрый старт (быстрая справка)
# 1. Создание рабочего окружения
python scripts/init_working_environment.py test_env
cd test_env
# 2. Генерация конфигураций
python scripts/generate_test_configs.py --output-dir configs
# 3. Запуск сервера
python examples/basic_framework/main.py --config configs/http_simple.json
# 4. Тестирование (в другом терминале)
python scripts/test_config.py --config configs/http_simple.json
# 5. Полный тест proxy registration
python scripts/test_proxy_registration.py
🎉 Готово! Теперь вы можете использовать MCP Proxy Adapter для создания безопасных JSON-RPC микросервисов с полной поддержкой аутентификации, авторизации и proxy registration.
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_proxy_adapter-6.3.11.tar.gz.
File metadata
- Download URL: mcp_proxy_adapter-6.3.11.tar.gz
- Upload date:
- Size: 20.4 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a9a0f059d8353f52f7389f1b6fb0c2f101bbc71342546210d7c56dc9d5b04acf
|
|
| MD5 |
8095b8a33fcbb794f4bc8b677d61d1a9
|
|
| BLAKE2b-256 |
0e877c3efa48ec93b6075f500c51187817507c3d0efe2b16e22dbcf8994db2c6
|
File details
Details for the file mcp_proxy_adapter-6.3.11-py3-none-any.whl.
File metadata
- Download URL: mcp_proxy_adapter-6.3.11-py3-none-any.whl
- Upload date:
- Size: 334.2 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 |
e27c834025362cff7697e945389c28711b0b657e3ad0ee4c1089796fd4adfcc4
|
|
| MD5 |
b79f87d8e69015f614c75ac2db468c9e
|
|
| BLAKE2b-256 |
9aa522e96a4671c9507c52471004e002f363d05300753422f00dca1ea9f38e01
|