Skip to main content

Async client for Embedding Service API with comprehensive authentication, SSL/TLS, and mTLS support. Uses mcp-proxy-adapter for unified command execution and queue management.

Project description

embed-client

Асинхронный клиент для Embedding Service API с поддержкой всех режимов безопасности.

Возможности

  • Асинхронный API - полная поддержка async/await
  • Все режимы безопасности - HTTP, HTTPS, mTLS
  • Аутентификация - API Key, JWT, Basic Auth, Certificate
  • SSL/TLS поддержка - полная интеграция с mcp_security_framework
  • Конфигурация - файлы конфигурации, переменные окружения, аргументы
  • Обратная совместимость - API формат не изменился, добавлена только безопасность
  • Типизация - 100% type-annotated код
  • Тестирование - 84+ тестов с полным покрытием

Quick Start: Примеры запуска

Базовое использование

Вариант 1: через аргументы командной строки

# HTTP без аутентификации
python embed_client/example_async_usage.py --base-url http://localhost --port 8001

# HTTP с API ключом
python embed_client/example_async_usage.py --base-url http://localhost --port 8001 \
  --auth-method api_key --api-key admin_key_123

# HTTPS с SSL
python embed_client/example_async_usage.py --base-url https://localhost --port 9443 \
  --ssl-verify-mode CERT_REQUIRED

# mTLS с сертификатами
python embed_client/example_async_usage.py --base-url https://localhost --port 9443 \
  --cert-file certs/client.crt --key-file keys/client.key --ca-cert-file certs/ca.crt

Вариант 2: через переменные окружения

export EMBED_CLIENT_BASE_URL=http://localhost
export EMBED_CLIENT_PORT=8001
export EMBED_CLIENT_AUTH_METHOD=api_key
export EMBED_CLIENT_API_KEY=admin_key_123
python embed_client/example_async_usage.py

Вариант 3: через файл конфигурации

python embed_client/example_async_usage.py --config configs/https_token.json

Режимы безопасности

1. HTTP (без аутентификации)

from embed_client.async_client import EmbeddingServiceAsyncClient

client = EmbeddingServiceAsyncClient(
    base_url="http://localhost",
    port=8001
)

2. HTTP + Token

from embed_client.config import ClientConfig

# API Key
config = ClientConfig.create_http_token_config(
    "http://localhost", 8001, {"user": "api_key_123"}
)

# JWT
config = ClientConfig.create_http_jwt_config(
    "http://localhost", 8001, "secret", "username", "password"
)

# Basic Auth
config = ClientConfig.create_http_basic_config(
    "http://localhost", 8001, "username", "password"
)

3. HTTPS

config = ClientConfig.create_https_config(
    "https://localhost", 9443,
    ca_cert_file="certs/ca.crt"
)

4. mTLS (взаимная аутентификация)

config = ClientConfig.create_mtls_config(
    "https://localhost", 9443,
    cert_file="certs/client.crt",
    key_file="keys/client.key",
    ca_cert_file="certs/ca.crt"
)

Программное использование

import asyncio
from embed_client.async_client import EmbeddingServiceAsyncClient


async def main():
    # Minimal configuration for HTTPS + token on localhost:8001 via MCP Proxy Adapter
    config_dict = {
        "server": {"host": "localhost", "port": 8001},
        "auth": {"method": "api_key", "api_keys": {"user": "user-secret-key"}},
        "ssl": {
            "enabled": True,
            "verify_mode": "CERT_NONE",
            "check_hostname": False,
            # Paths from mtls_certificates used by test environment
            "cert_file": "mtls_certificates/client/embedding-service.crt",
            "key_file": "mtls_certificates/client/embedding-service.key",
            "ca_cert_file": "mtls_certificates/ca/ca.crt",
        },
    }

    texts = ["valid text", "   ", "!!!"]

    async with EmbeddingServiceAsyncClient(config_dict=config_dict) as client:
        # High-level helper: always uses error_policy="continue"
        data = await client.embed(texts, error_policy="continue")

        # Iterate over per-item results
        for idx, item in enumerate(data["results"]):
            err = item["error"]
            if err is None:
                embedding = item["embedding"]
                print(f"{idx}: OK, embedding length={len(embedding)}")
            else:
                print(f"{idx}: ERROR {err['code']} - {err['message']}")


if __name__ == "__main__":
    asyncio.run(main())

Vectorization methods (English)

1. Python async client – high-level embed()

  • Use EmbeddingServiceAsyncClient.embed() for batch vectorization with per-item errors.
  • Always pass error_policy="continue" to keep positional mapping between texts[i] and results[i].

Example (see above): run python embed_client/example_async_usage.py or a custom script with EmbeddingServiceAsyncClient.embed().

2. Python async client – low-level cmd("embed")

  • For advanced scenarios you can call client.cmd("embed", params=...) directly and use helpers from response_parsers.
params = {"texts": texts, "error_policy": "continue"}
raw_result = await client.cmd("embed", params=params)
data = extract_embedding_data(raw_result)

3. CLI – embed-vectorize

The package installs a CLI tool for vectorization:

# HTTP (no auth) on localhost:8001
embed-config-generator --mode http --host localhost --port 8001 --output ./configs/http_8001.json
embed-vectorize --config ./configs/http_8001.json "hello world" "another text"

# HTTPS + token + mTLS certificates (recommended for production-like tests)
embed-config-generator --mode https_token --host localhost --port 8001 \
  --cert-file mtls_certificates/client/embedding-service.crt \
  --key-file mtls_certificates/client/embedding-service.key \
  --ca-cert-file mtls_certificates/ca/ca.crt \
  --output ./configs/https_token_8001.json

embed-vectorize --config ./configs/https_token_8001.json "valid text" "   " "!!!"

4. Full embed contract example on localhost:8001

For a complete contract test of error_policy="continue" across all 8 security modes, use:

python tests/test_embed_contract_8001.py

This script uses ClientConfigGenerator and EmbeddingServiceAsyncClient.embed() and is regularly validated against a real server on localhost:8001.

Установка

# Установка из PyPI
pip install embed-client

# Установка в режиме разработки
git clone <repository>
cd embed-client
pip install -e .

Dependencies (runtime)

  • mcp-proxy-adapter - JSON-RPC transport for Embedding Service via MCP Proxy Adapter
  • PyJWT>=2.0.0 - JWT tokens (used for diagnostics and compatibility)
  • cryptography>=3.0.0 - certificates and crypto primitives
  • pydantic>=2.0.0 - configuration validation

Тестирование

# Запуск всех тестов
pytest tests/

# Запуск тестов с покрытием
pytest tests/ --cov=embed_client

# Запуск конкретных тестов
pytest tests/test_async_client.py -v
pytest tests/test_config.py -v
pytest tests/test_auth.py -v
pytest tests/test_ssl_manager.py -v

Документация

Безопасность

Рекомендации

  1. Используйте HTTPS для продакшена
  2. Включите проверку сертификатов (CERT_REQUIRED)
  3. Используйте mTLS для критически важных систем
  4. Регулярно обновляйте сертификаты
  5. Храните приватные ключи в безопасном месте

Поддерживаемые протоколы

  • TLS 1.2
  • TLS 1.3
  • SSL 3.0 (устаревший, не рекомендуется)

Лицензия

MIT License

Автор

Vasiliy Zdanovskiy
Email: vasilyvz@gmail.com


Важно:

  • Используйте --base-url (через дефис), а не --base_url (через подчеркивание).
  • Значение base_url должно содержать http:// или https://.
  • Аргументы должны быть отдельными (через пробел), а не через =.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

embed_client-3.1.7.8.tar.gz (129.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

embed_client-3.1.7.8-py3-none-any.whl (75.5 kB view details)

Uploaded Python 3

File details

Details for the file embed_client-3.1.7.8.tar.gz.

File metadata

  • Download URL: embed_client-3.1.7.8.tar.gz
  • Upload date:
  • Size: 129.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for embed_client-3.1.7.8.tar.gz
Algorithm Hash digest
SHA256 edf9dbbb4c646649f50f0c5c8d12425c4d70437e3d810dc18a5189b2fbfd0bfb
MD5 70507e2ce541e0ead0b222eafeb12193
BLAKE2b-256 d707ea1192948d55d958b197507af01dc48d602fab292ec5cad6180d9b7ca6b7

See more details on using hashes here.

File details

Details for the file embed_client-3.1.7.8-py3-none-any.whl.

File metadata

  • Download URL: embed_client-3.1.7.8-py3-none-any.whl
  • Upload date:
  • Size: 75.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for embed_client-3.1.7.8-py3-none-any.whl
Algorithm Hash digest
SHA256 c50a3b8fc6217ad4783c0bf3fbef3200941e79c2003671b5813be3f95d06f6b3
MD5 76332a4fc8532b1b179e648cdb2c18be
BLAKE2b-256 7c7f2160f59cbd309ffc79247fe614bca6dd4cc8532822c7850d7ef3c179dfeb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page