mcp-proxy-adapter 2.1.0__py3-none-any.whl → 2.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/README.md +172 -0
- docs/README_ru.md +172 -0
- docs/architecture.md +251 -0
- docs/architecture_ru.md +343 -0
- docs/command_development.md +250 -0
- docs/command_development_ru.md +593 -0
- docs/deployment.md +251 -0
- docs/deployment_ru.md +1298 -0
- docs/examples.md +254 -0
- docs/examples_ru.md +401 -0
- docs/mcp_proxy_adapter.md +251 -0
- docs/mcp_proxy_adapter_ru.md +405 -0
- docs/quickstart.md +251 -0
- docs/quickstart_ru.md +397 -0
- docs/testing.md +255 -0
- docs/testing_ru.md +469 -0
- docs/validation_ru.md +287 -0
- examples/analyze_config.py +141 -0
- examples/basic_integration.py +161 -0
- examples/docstring_and_schema_example.py +60 -0
- examples/extension_example.py +60 -0
- examples/help_best_practices.py +67 -0
- examples/help_usage.py +64 -0
- examples/mcp_proxy_client.py +131 -0
- examples/mcp_proxy_config.json +175 -0
- examples/openapi_server.py +369 -0
- examples/project_structure_example.py +47 -0
- examples/testing_example.py +53 -0
- mcp_proxy_adapter/__init__.py +17 -0
- mcp_proxy_adapter/adapter.py +697 -0
- mcp_proxy_adapter/models.py +47 -0
- mcp_proxy_adapter/registry.py +439 -0
- mcp_proxy_adapter/schema.py +257 -0
- {mcp_proxy_adapter-2.1.0.dist-info → mcp_proxy_adapter-2.1.2.dist-info}/METADATA +2 -2
- mcp_proxy_adapter-2.1.2.dist-info/RECORD +61 -0
- mcp_proxy_adapter-2.1.2.dist-info/top_level.txt +5 -0
- scripts/code_analyzer/code_analyzer.py +328 -0
- scripts/code_analyzer/register_commands.py +446 -0
- scripts/publish.py +85 -0
- tests/conftest.py +12 -0
- tests/test_adapter.py +529 -0
- tests/test_adapter_coverage.py +274 -0
- tests/test_basic_dispatcher.py +169 -0
- tests/test_command_registry.py +328 -0
- tests/test_examples.py +32 -0
- tests/test_mcp_proxy_adapter.py +568 -0
- tests/test_mcp_proxy_adapter_basic.py +262 -0
- tests/test_part1.py +348 -0
- tests/test_part2.py +524 -0
- tests/test_schema.py +358 -0
- tests/test_simple_adapter.py +251 -0
- adapters/__init__.py +0 -16
- cli/__init__.py +0 -12
- cli/__main__.py +0 -79
- cli/command_runner.py +0 -233
- generators/__init__.py +0 -14
- generators/endpoint_generator.py +0 -172
- generators/openapi_generator.py +0 -254
- generators/rest_api_generator.py +0 -207
- mcp_proxy_adapter-2.1.0.dist-info/RECORD +0 -28
- mcp_proxy_adapter-2.1.0.dist-info/top_level.txt +0 -7
- openapi_schema/__init__.py +0 -38
- openapi_schema/command_registry.py +0 -312
- openapi_schema/rest_schema.py +0 -510
- openapi_schema/rpc_generator.py +0 -307
- openapi_schema/rpc_schema.py +0 -416
- validators/__init__.py +0 -14
- validators/base_validator.py +0 -23
- {analyzers → mcp_proxy_adapter/analyzers}/__init__.py +0 -0
- {analyzers → mcp_proxy_adapter/analyzers}/docstring_analyzer.py +0 -0
- {analyzers → mcp_proxy_adapter/analyzers}/type_analyzer.py +0 -0
- {dispatchers → mcp_proxy_adapter/dispatchers}/__init__.py +0 -0
- {dispatchers → mcp_proxy_adapter/dispatchers}/base_dispatcher.py +0 -0
- {dispatchers → mcp_proxy_adapter/dispatchers}/json_rpc_dispatcher.py +0 -0
- {validators → mcp_proxy_adapter/validators}/docstring_validator.py +0 -0
- {validators → mcp_proxy_adapter/validators}/metadata_validator.py +0 -0
- {mcp_proxy_adapter-2.1.0.dist-info → mcp_proxy_adapter-2.1.2.dist-info}/WHEEL +0 -0
- {mcp_proxy_adapter-2.1.0.dist-info → mcp_proxy_adapter-2.1.2.dist-info}/licenses/LICENSE +0 -0
docs/README.md
ADDED
@@ -0,0 +1,172 @@
|
|
1
|
+
# Command Registry
|
2
|
+
|
3
|
+
## Overview
|
4
|
+
|
5
|
+
Command Registry is a high-level system for centralized command management in applications. It provides a unified mechanism for defining, registering, executing, and documenting commands through various interfaces.
|
6
|
+
|
7
|
+
## Key Features
|
8
|
+
|
9
|
+
- **Single access point** for application commands
|
10
|
+
- **Automatic metadata extraction** from Python docstrings and type hints
|
11
|
+
- **Integration with various protocols** (REST, JSON-RPC, WebSockets)
|
12
|
+
- **API documentation generation** based on command metadata
|
13
|
+
- **Input parameters and output values validation**
|
14
|
+
- **Metadata compliance verification** with actual function signatures
|
15
|
+
- **Extensibility** through interfaces for dispatchers, adapters, and schema generators
|
16
|
+
- **AI model integration** via MCP Proxy Adapter
|
17
|
+
|
18
|
+
## Getting Started
|
19
|
+
|
20
|
+
### Installation
|
21
|
+
|
22
|
+
```bash
|
23
|
+
pip install command-registry
|
24
|
+
```
|
25
|
+
|
26
|
+
For MCP Proxy integration, also install:
|
27
|
+
|
28
|
+
```bash
|
29
|
+
pip install mcp-proxy-adapter
|
30
|
+
```
|
31
|
+
|
32
|
+
### Simple Example
|
33
|
+
|
34
|
+
```python
|
35
|
+
from command_registry import CommandRegistry
|
36
|
+
|
37
|
+
# Create a command registry instance
|
38
|
+
registry = CommandRegistry()
|
39
|
+
|
40
|
+
# Define a command
|
41
|
+
def add_numbers(a: int, b: int) -> int:
|
42
|
+
"""Adds two numbers.
|
43
|
+
|
44
|
+
Args:
|
45
|
+
a: First number
|
46
|
+
b: Second number
|
47
|
+
|
48
|
+
Returns:
|
49
|
+
Sum of numbers a and b
|
50
|
+
"""
|
51
|
+
return a + b
|
52
|
+
|
53
|
+
# Register the command
|
54
|
+
registry.register_command("add", add_numbers)
|
55
|
+
|
56
|
+
# Execute the command
|
57
|
+
result = registry.execute("add", {"a": 5, "b": 3}) # Returns 8
|
58
|
+
```
|
59
|
+
|
60
|
+
### FastAPI Export
|
61
|
+
|
62
|
+
```python
|
63
|
+
from fastapi import FastAPI
|
64
|
+
from command_registry.adapters import RESTAdapter
|
65
|
+
|
66
|
+
app = FastAPI()
|
67
|
+
adapter = RESTAdapter(registry)
|
68
|
+
adapter.register_endpoints(app)
|
69
|
+
```
|
70
|
+
|
71
|
+
### MCP Proxy Integration for AI Models
|
72
|
+
|
73
|
+
```python
|
74
|
+
from fastapi import FastAPI
|
75
|
+
from mcp_proxy_adapter.adapter import MCPProxyAdapter
|
76
|
+
|
77
|
+
app = FastAPI()
|
78
|
+
adapter = MCPProxyAdapter(registry)
|
79
|
+
adapter.register_endpoints(app)
|
80
|
+
|
81
|
+
# Create configuration for MCP Proxy
|
82
|
+
adapter.save_config_to_file("mcp_proxy_config.json")
|
83
|
+
```
|
84
|
+
|
85
|
+
### Automatic Command Registration from Module
|
86
|
+
|
87
|
+
```python
|
88
|
+
# Scan module and register all found commands
|
89
|
+
registry.scan_module("myapp.commands")
|
90
|
+
```
|
91
|
+
|
92
|
+
## Documentation
|
93
|
+
|
94
|
+
- [Architecture](architecture.md) - detailed component description
|
95
|
+
- [Command Development Guide](command_development.md) - best practices
|
96
|
+
- [Examples](examples.md) - usage examples for various scenarios
|
97
|
+
- [Validation](validation.md) - command validation mechanisms
|
98
|
+
- [MCP Proxy Adapter](mcp_proxy_adapter.md) - AI model integration via MCP Proxy
|
99
|
+
|
100
|
+
## Project Structure
|
101
|
+
|
102
|
+
```
|
103
|
+
command_registry/
|
104
|
+
├── __init__.py # Main public API
|
105
|
+
├── core.py # Core CommandRegistry logic
|
106
|
+
├── dispatchers/ # Command dispatchers
|
107
|
+
│ ├── __init__.py
|
108
|
+
│ ├── base_dispatcher.py # Abstract base class
|
109
|
+
│ └── command_dispatcher.py # Main implementation
|
110
|
+
├── metadata/ # Metadata extraction
|
111
|
+
│ ├── __init__.py
|
112
|
+
│ ├── docstring_parser.py # Docstring parser
|
113
|
+
│ └── type_analyzer.py # Type analyzer
|
114
|
+
├── validators/ # Validators
|
115
|
+
│ ├── __init__.py
|
116
|
+
│ └── parameter_validator.py # Parameter validation
|
117
|
+
├── adapters/ # Protocol adapters
|
118
|
+
│ ├── __init__.py
|
119
|
+
│ ├── rest_adapter.py # REST API
|
120
|
+
│ └── json_rpc_adapter.py # JSON-RPC
|
121
|
+
└── schema/ # Schema generators
|
122
|
+
├── __init__.py
|
123
|
+
├── openapi_generator.py # OpenAPI
|
124
|
+
└── json_schema_generator.py # JSON Schema
|
125
|
+
```
|
126
|
+
|
127
|
+
## Integration with Existing Systems
|
128
|
+
|
129
|
+
Command Registry is designed for easy integration with existing systems and frameworks:
|
130
|
+
|
131
|
+
- **FastAPI** - via RESTAdapter
|
132
|
+
- **Flask** - via RESTAdapter with modifications
|
133
|
+
- **aiohttp** - via WebSockets adapter
|
134
|
+
- **Click** - via CLI adapter
|
135
|
+
- **GraphQL** - via GraphQL adapter
|
136
|
+
- **MCP Proxy** - via MCPProxyAdapter for AI model integration
|
137
|
+
|
138
|
+
## Usage Examples
|
139
|
+
|
140
|
+
### REST API
|
141
|
+
|
142
|
+
```python
|
143
|
+
from fastapi import FastAPI
|
144
|
+
from command_registry import CommandRegistry
|
145
|
+
from command_registry.adapters import RESTAdapter
|
146
|
+
|
147
|
+
app = FastAPI()
|
148
|
+
registry = CommandRegistry()
|
149
|
+
registry.scan_module("myapp.commands")
|
150
|
+
|
151
|
+
adapter = RESTAdapter(registry)
|
152
|
+
adapter.register_endpoints(app)
|
153
|
+
```
|
154
|
+
|
155
|
+
### JSON-RPC via MCP Proxy Adapter
|
156
|
+
|
157
|
+
```python
|
158
|
+
from fastapi import FastAPI
|
159
|
+
from command_registry import CommandRegistry
|
160
|
+
from mcp_proxy_adapter.adapter import MCPProxyAdapter
|
161
|
+
|
162
|
+
app = FastAPI()
|
163
|
+
registry = CommandRegistry()
|
164
|
+
registry.scan_module("myapp.commands")
|
165
|
+
|
166
|
+
adapter = MCPProxyAdapter(registry)
|
167
|
+
adapter.register_endpoints(app)
|
168
|
+
```
|
169
|
+
|
170
|
+
## License
|
171
|
+
|
172
|
+
MIT
|
docs/README_ru.md
ADDED
@@ -0,0 +1,172 @@
|
|
1
|
+
# Command Registry
|
2
|
+
|
3
|
+
## Обзор
|
4
|
+
|
5
|
+
Command Registry - это высокоуровневая система для централизованного управления командами в приложении. Она предоставляет унифицированный механизм определения, регистрации, выполнения и документирования команд через различные интерфейсы.
|
6
|
+
|
7
|
+
## Основные возможности
|
8
|
+
|
9
|
+
- **Единая точка доступа** к командам приложения
|
10
|
+
- **Автоматическое извлечение метаданных** из докстрингов и типизации Python
|
11
|
+
- **Интеграция с различными протоколами** (REST, JSON-RPC, WebSockets)
|
12
|
+
- **Генерация документации API** на основе метаданных команд
|
13
|
+
- **Валидация входных параметров** и выходных значений
|
14
|
+
- **Проверка соответствия метаданных** фактической сигнатуре функций
|
15
|
+
- **Расширяемость** через интерфейсы для диспетчеров, адаптеров и генераторов схем
|
16
|
+
- **Интеграция с моделями ИИ** через MCP Proxy Adapter
|
17
|
+
|
18
|
+
## Начало работы
|
19
|
+
|
20
|
+
### Установка
|
21
|
+
|
22
|
+
```bash
|
23
|
+
pip install command-registry
|
24
|
+
```
|
25
|
+
|
26
|
+
Для работы с MCP Proxy также установите:
|
27
|
+
|
28
|
+
```bash
|
29
|
+
pip install mcp-proxy-adapter
|
30
|
+
```
|
31
|
+
|
32
|
+
### Простой пример
|
33
|
+
|
34
|
+
```python
|
35
|
+
from command_registry import CommandRegistry
|
36
|
+
|
37
|
+
# Создание экземпляра реестра команд
|
38
|
+
registry = CommandRegistry()
|
39
|
+
|
40
|
+
# Определение команды
|
41
|
+
def add_numbers(a: int, b: int) -> int:
|
42
|
+
"""Складывает два числа.
|
43
|
+
|
44
|
+
Args:
|
45
|
+
a: Первое число
|
46
|
+
b: Второе число
|
47
|
+
|
48
|
+
Returns:
|
49
|
+
Сумма чисел a и b
|
50
|
+
"""
|
51
|
+
return a + b
|
52
|
+
|
53
|
+
# Регистрация команды
|
54
|
+
registry.register_command("add", add_numbers)
|
55
|
+
|
56
|
+
# Выполнение команды
|
57
|
+
result = registry.execute("add", {"a": 5, "b": 3}) # Вернёт 8
|
58
|
+
```
|
59
|
+
|
60
|
+
### Экспорт через FastAPI
|
61
|
+
|
62
|
+
```python
|
63
|
+
from fastapi import FastAPI
|
64
|
+
from command_registry.adapters import RESTAdapter
|
65
|
+
|
66
|
+
app = FastAPI()
|
67
|
+
adapter = RESTAdapter(registry)
|
68
|
+
adapter.register_endpoints(app)
|
69
|
+
```
|
70
|
+
|
71
|
+
### Интеграция с MCP Proxy для моделей ИИ
|
72
|
+
|
73
|
+
```python
|
74
|
+
from fastapi import FastAPI
|
75
|
+
from mcp_proxy_adapter.adapter import MCPProxyAdapter
|
76
|
+
|
77
|
+
app = FastAPI()
|
78
|
+
adapter = MCPProxyAdapter(registry)
|
79
|
+
adapter.register_endpoints(app)
|
80
|
+
|
81
|
+
# Создание конфигурации для MCP Proxy
|
82
|
+
adapter.save_config_to_file("mcp_proxy_config.json")
|
83
|
+
```
|
84
|
+
|
85
|
+
### Автоматическая регистрация команд из модуля
|
86
|
+
|
87
|
+
```python
|
88
|
+
# Сканирование модуля и регистрация всех найденных команд
|
89
|
+
registry.scan_module("myapp.commands")
|
90
|
+
```
|
91
|
+
|
92
|
+
## Документация
|
93
|
+
|
94
|
+
- [Архитектура](architecture.md) - подробное описание компонентов
|
95
|
+
- [Руководство по разработке команд](command_development.md) - лучшие практики
|
96
|
+
- [Примеры](examples.md) - примеры использования для различных сценариев
|
97
|
+
- [Валидация](validation.md) - механизмы проверки команд
|
98
|
+
- [MCP Proxy Adapter](mcp_proxy_adapter.md) - интеграция с моделями ИИ через MCP Proxy
|
99
|
+
|
100
|
+
## Структура проекта
|
101
|
+
|
102
|
+
```
|
103
|
+
command_registry/
|
104
|
+
├── __init__.py # Основные публичные API
|
105
|
+
├── core.py # Основная логика CommandRegistry
|
106
|
+
├── dispatchers/ # Диспетчеры команд
|
107
|
+
│ ├── __init__.py
|
108
|
+
│ ├── base_dispatcher.py # Абстрактный базовый класс
|
109
|
+
│ └── command_dispatcher.py # Основная реализация
|
110
|
+
├── metadata/ # Извлечение метаданных
|
111
|
+
│ ├── __init__.py
|
112
|
+
│ ├── docstring_parser.py # Парсер докстрингов
|
113
|
+
│ └── type_analyzer.py # Анализатор типов
|
114
|
+
├── validators/ # Валидаторы
|
115
|
+
│ ├── __init__.py
|
116
|
+
│ └── parameter_validator.py # Валидация параметров
|
117
|
+
├── adapters/ # Адаптеры протоколов
|
118
|
+
│ ├── __init__.py
|
119
|
+
│ ├── rest_adapter.py # REST API
|
120
|
+
│ └── json_rpc_adapter.py # JSON-RPC
|
121
|
+
└── schema/ # Генераторы схем
|
122
|
+
├── __init__.py
|
123
|
+
├── openapi_generator.py # OpenAPI
|
124
|
+
└── json_schema_generator.py # JSON Schema
|
125
|
+
```
|
126
|
+
|
127
|
+
## Интеграция с существующими системами
|
128
|
+
|
129
|
+
Command Registry спроектирован для легкой интеграции с существующими системами и фреймворками:
|
130
|
+
|
131
|
+
- **FastAPI** - через RESTAdapter
|
132
|
+
- **Flask** - через RESTAdapter с модификациями
|
133
|
+
- **aiohttp** - через адаптер для WebSockets
|
134
|
+
- **Click** - через CLI адаптер
|
135
|
+
- **GraphQL** - через GraphQL адаптер
|
136
|
+
- **MCP Proxy** - через MCPProxyAdapter для интеграции с моделями ИИ
|
137
|
+
|
138
|
+
## Примеры использования
|
139
|
+
|
140
|
+
### REST API
|
141
|
+
|
142
|
+
```python
|
143
|
+
from fastapi import FastAPI
|
144
|
+
from command_registry import CommandRegistry
|
145
|
+
from command_registry.adapters import RESTAdapter
|
146
|
+
|
147
|
+
app = FastAPI()
|
148
|
+
registry = CommandRegistry()
|
149
|
+
registry.scan_module("myapp.commands")
|
150
|
+
|
151
|
+
adapter = RESTAdapter(registry)
|
152
|
+
adapter.register_endpoints(app)
|
153
|
+
```
|
154
|
+
|
155
|
+
### JSON-RPC через MCP Proxy Adapter
|
156
|
+
|
157
|
+
```python
|
158
|
+
from fastapi import FastAPI
|
159
|
+
from command_registry import CommandRegistry
|
160
|
+
from mcp_proxy_adapter.adapter import MCPProxyAdapter
|
161
|
+
|
162
|
+
app = FastAPI()
|
163
|
+
registry = CommandRegistry()
|
164
|
+
registry.scan_module("myapp.commands")
|
165
|
+
|
166
|
+
adapter = MCPProxyAdapter(registry)
|
167
|
+
adapter.register_endpoints(app)
|
168
|
+
```
|
169
|
+
|
170
|
+
## Лицензия
|
171
|
+
|
172
|
+
MIT
|
docs/architecture.md
ADDED
@@ -0,0 +1,251 @@
|
|
1
|
+
# Command Registry Architecture
|
2
|
+
|
3
|
+
This document describes the architecture of the Command Registry system, its key components, their interactions, and extension principles.
|
4
|
+
|
5
|
+
## Architecture Overview
|
6
|
+
|
7
|
+
Command Registry is a modular system built around the concept of centralized command storage and management. The architecture ensures flexibility, extensibility, and adherence to SOLID principles.
|
8
|
+
|
9
|
+
Key system capabilities:
|
10
|
+
|
11
|
+
1. **Defining commands as Python functions** using type hints and docstrings
|
12
|
+
2. **Metadata extraction** from function signatures and their documentation
|
13
|
+
3. **Command registration** in a central registry
|
14
|
+
4. **Providing a unified interface** for command execution
|
15
|
+
5. **API documentation generation** based on command metadata
|
16
|
+
6. **Command export** through various protocols (REST, JSON-RPC, CLI, etc.)
|
17
|
+
|
18
|
+
## System Components
|
19
|
+
|
20
|
+

|
21
|
+
|
22
|
+
### Core Components:
|
23
|
+
|
24
|
+
1. **Command Definition** - Command definition (Python function with type hints and docstrings)
|
25
|
+
2. **Dispatcher Component** - Command dispatcher responsible for registration and execution
|
26
|
+
3. **Metadata Extractor** - Extracts metadata from docstrings and function signatures
|
27
|
+
4. **Protocol Adapter** - Adapter for exporting commands through various protocols
|
28
|
+
|
29
|
+
### CommandRegistry
|
30
|
+
|
31
|
+
The central system component that:
|
32
|
+
|
33
|
+
- Initializes and configures dispatchers
|
34
|
+
- Provides an interface for command registration
|
35
|
+
- Manages command metadata
|
36
|
+
- Coordinates interaction between components
|
37
|
+
|
38
|
+
## Command Lifecycle
|
39
|
+
|
40
|
+
### 1. Command Definition
|
41
|
+
|
42
|
+
```python
|
43
|
+
def calculate_total(
|
44
|
+
prices: List[float],
|
45
|
+
discount: float = 0.0,
|
46
|
+
tax_rate: float = 0.0
|
47
|
+
) -> float:
|
48
|
+
"""
|
49
|
+
Calculates total cost including discount and tax.
|
50
|
+
|
51
|
+
Args:
|
52
|
+
prices: List of item prices
|
53
|
+
discount: Discount percentage (0-100)
|
54
|
+
tax_rate: Tax rate percentage (0-100)
|
55
|
+
|
56
|
+
Returns:
|
57
|
+
Total cost including discount and tax
|
58
|
+
"""
|
59
|
+
subtotal = sum(prices)
|
60
|
+
discounted = subtotal * (1 - discount / 100)
|
61
|
+
total = discounted * (1 + tax_rate / 100)
|
62
|
+
return round(total, 2)
|
63
|
+
```
|
64
|
+
|
65
|
+
### 2. Command Registration
|
66
|
+
|
67
|
+
```python
|
68
|
+
from command_registry import CommandRegistry
|
69
|
+
from command_registry.dispatchers import CommandDispatcher
|
70
|
+
|
71
|
+
# Create command registry
|
72
|
+
registry = CommandRegistry(CommandDispatcher())
|
73
|
+
|
74
|
+
# Register command
|
75
|
+
registry.register_command("calculate_total", calculate_total)
|
76
|
+
```
|
77
|
+
|
78
|
+
### 3. Command Execution
|
79
|
+
|
80
|
+
```python
|
81
|
+
# Execute command
|
82
|
+
result = registry.execute(
|
83
|
+
"calculate_total",
|
84
|
+
{
|
85
|
+
"prices": [10.0, 20.0, 30.0],
|
86
|
+
"discount": 10.0,
|
87
|
+
"tax_rate": 7.0
|
88
|
+
}
|
89
|
+
)
|
90
|
+
print(result) # 57.33
|
91
|
+
```
|
92
|
+
|
93
|
+
### 4. API Export
|
94
|
+
|
95
|
+
```python
|
96
|
+
from fastapi import FastAPI
|
97
|
+
from command_registry.adapters import RESTAdapter
|
98
|
+
|
99
|
+
app = FastAPI()
|
100
|
+
adapter = RESTAdapter(registry)
|
101
|
+
adapter.register_endpoints(app)
|
102
|
+
```
|
103
|
+
|
104
|
+
## Data Flow Diagrams
|
105
|
+
|
106
|
+
### Command Registration Process
|
107
|
+
|
108
|
+
```
|
109
|
+
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────┐
|
110
|
+
│ │ │ │ │ │
|
111
|
+
│ Python Function├─────►│ Metadata Extractor ├─────►│ Metadata │
|
112
|
+
│ │ │ │ │ │
|
113
|
+
└─────────────────┘ └────────────────────┘ └────────┬────────┘
|
114
|
+
│
|
115
|
+
▼
|
116
|
+
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────┐
|
117
|
+
│ │ │ │ │ │
|
118
|
+
│ CommandRegistry│◄─────┤ Data Validation │◄─────┤ Parameters │
|
119
|
+
│ │ │ │ │ │
|
120
|
+
└────────┬────────┘ └────────────────────┘ └─────────────────┘
|
121
|
+
│
|
122
|
+
▼
|
123
|
+
┌─────────────────┐
|
124
|
+
│ │
|
125
|
+
│ Dispatcher │
|
126
|
+
│ │
|
127
|
+
└─────────────────┘
|
128
|
+
```
|
129
|
+
|
130
|
+
### Command Execution Process
|
131
|
+
|
132
|
+
```
|
133
|
+
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────┐
|
134
|
+
│ │ │ │ │ │
|
135
|
+
│ Command Name │ │ │ │ Parameter │
|
136
|
+
│ + Parameters ├─────►│ CommandRegistry ├─────►│ Validation │
|
137
|
+
│ │ │ │ │ │
|
138
|
+
└─────────────────┘ └────────────────────┘ └────────┬────────┘
|
139
|
+
│
|
140
|
+
▼
|
141
|
+
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────┐
|
142
|
+
│ │ │ │ │ │
|
143
|
+
│ Result │◄─────┤ Error Handling │◄─────┤ Dispatcher │
|
144
|
+
│ │ │ │ │ (execution) │
|
145
|
+
└─────────────────┘ └────────────────────┘ └─────────────────┘
|
146
|
+
```
|
147
|
+
|
148
|
+
### API Documentation Generation
|
149
|
+
|
150
|
+
```
|
151
|
+
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────┐
|
152
|
+
│ │ │ │ │ │
|
153
|
+
│ Command │ │ Schema Generator │ │ OpenAPI/ │
|
154
|
+
│ Metadata ├─────►│ ├─────►│ JSON Schema │
|
155
|
+
│ │ │ │ │ │
|
156
|
+
└─────────────────┘ └────────────────────┘ └────────┬────────┘
|
157
|
+
│
|
158
|
+
▼
|
159
|
+
┌─────────────────┐
|
160
|
+
│ │
|
161
|
+
│ API Docs UI │
|
162
|
+
│ (Swagger/ │
|
163
|
+
│ ReDoc) │
|
164
|
+
└─────────────────┘
|
165
|
+
```
|
166
|
+
|
167
|
+
## System Extension
|
168
|
+
|
169
|
+
### Creating a Custom Dispatcher
|
170
|
+
|
171
|
+
```python
|
172
|
+
from command_registry.dispatchers import BaseDispatcher
|
173
|
+
from typing import Dict, Any, List, Optional, Callable
|
174
|
+
|
175
|
+
class MyCustomDispatcher(BaseDispatcher):
|
176
|
+
def __init__(self):
|
177
|
+
self._commands = {}
|
178
|
+
self._info = {}
|
179
|
+
|
180
|
+
def register_handler(
|
181
|
+
self,
|
182
|
+
command_name: str,
|
183
|
+
handler: Callable,
|
184
|
+
description: str = None,
|
185
|
+
summary: str = None,
|
186
|
+
params: Dict[str, Any] = None
|
187
|
+
) -> None:
|
188
|
+
self._commands[command_name] = handler
|
189
|
+
self._info[command_name] = {
|
190
|
+
"description": description,
|
191
|
+
"summary": summary,
|
192
|
+
"params": params or {}
|
193
|
+
}
|
194
|
+
|
195
|
+
def execute(self, command_name: str, params: Dict[str, Any] = None) -> Any:
|
196
|
+
if command_name not in self._commands:
|
197
|
+
raise ValueError(f"Command '{command_name}' not found")
|
198
|
+
|
199
|
+
handler = self._commands[command_name]
|
200
|
+
return handler(**params or {})
|
201
|
+
|
202
|
+
def get_valid_commands(self) -> List[str]:
|
203
|
+
return list(self._commands.keys())
|
204
|
+
|
205
|
+
def get_command_info(self, command_name: str) -> Optional[Dict[str, Any]]:
|
206
|
+
return self._info.get(command_name)
|
207
|
+
|
208
|
+
def get_commands_info(self) -> Dict[str, Dict[str, Any]]:
|
209
|
+
return self._info
|
210
|
+
```
|
211
|
+
|
212
|
+
### Creating a Custom Protocol Adapter
|
213
|
+
|
214
|
+
```python
|
215
|
+
from command_registry import CommandRegistry
|
216
|
+
from typing import Dict, Any
|
217
|
+
|
218
|
+
class GraphQLAdapter:
|
219
|
+
def __init__(self, registry: CommandRegistry):
|
220
|
+
self.registry = registry
|
221
|
+
|
222
|
+
def generate_schema(self) -> str:
|
223
|
+
"""Generates GraphQL schema based on command metadata."""
|
224
|
+
commands_info = self.registry.get_all_commands_info()
|
225
|
+
schema_types = []
|
226
|
+
query_fields = []
|
227
|
+
|
228
|
+
for cmd_name, info in commands_info.items():
|
229
|
+
# Generate types for input and output data
|
230
|
+
input_type = self._generate_input_type(cmd_name, info["params"])
|
231
|
+
output_type = self._generate_output_type(cmd_name, info.get("returns"))
|
232
|
+
|
233
|
+
schema_types.extend([input_type, output_type])
|
234
|
+
|
235
|
+
# Add field to Query
|
236
|
+
query_fields.append(
|
237
|
+
f"{cmd_name}(input: {cmd_name}Input): {cmd_name}Output"
|
238
|
+
)
|
239
|
+
|
240
|
+
# Form final schema
|
241
|
+
schema = "\n".join(schema_types)
|
242
|
+
schema += f"\ntype Query {{\n {chr(10).join(query_fields)}\n}}"
|
243
|
+
|
244
|
+
return schema
|
245
|
+
|
246
|
+
def _generate_input_type(self, cmd_name: str, params: Dict[str, Any]) -> str:
|
247
|
+
fields = []
|
248
|
+
for name, param_info in params.items():
|
249
|
+
field_type = self._map_type(param_info.get("type", "String"))
|
250
|
+
required = "!" if param_info.get("required", False) else ""
|
251
|
+
```
|