mcp-proxy-adapter 2.1.1__py3-none-any.whl → 2.1.3__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.
Files changed (50) hide show
  1. {mcp_proxy_adapter-2.1.1.dist-info → mcp_proxy_adapter-2.1.3.dist-info}/METADATA +1 -1
  2. mcp_proxy_adapter-2.1.3.dist-info/RECORD +18 -0
  3. mcp_proxy_adapter-2.1.3.dist-info/top_level.txt +1 -0
  4. docs/README.md +0 -172
  5. docs/README_ru.md +0 -172
  6. docs/architecture.md +0 -251
  7. docs/architecture_ru.md +0 -343
  8. docs/command_development.md +0 -250
  9. docs/command_development_ru.md +0 -593
  10. docs/deployment.md +0 -251
  11. docs/deployment_ru.md +0 -1298
  12. docs/examples.md +0 -254
  13. docs/examples_ru.md +0 -401
  14. docs/mcp_proxy_adapter.md +0 -251
  15. docs/mcp_proxy_adapter_ru.md +0 -405
  16. docs/quickstart.md +0 -251
  17. docs/quickstart_ru.md +0 -397
  18. docs/testing.md +0 -255
  19. docs/testing_ru.md +0 -469
  20. docs/validation_ru.md +0 -287
  21. examples/analyze_config.py +0 -141
  22. examples/basic_integration.py +0 -161
  23. examples/docstring_and_schema_example.py +0 -60
  24. examples/extension_example.py +0 -60
  25. examples/help_best_practices.py +0 -67
  26. examples/help_usage.py +0 -64
  27. examples/mcp_proxy_client.py +0 -131
  28. examples/mcp_proxy_config.json +0 -175
  29. examples/openapi_server.py +0 -369
  30. examples/project_structure_example.py +0 -47
  31. examples/testing_example.py +0 -53
  32. mcp_proxy_adapter-2.1.1.dist-info/RECORD +0 -61
  33. mcp_proxy_adapter-2.1.1.dist-info/top_level.txt +0 -5
  34. scripts/code_analyzer/code_analyzer.py +0 -328
  35. scripts/code_analyzer/register_commands.py +0 -446
  36. scripts/publish.py +0 -85
  37. tests/conftest.py +0 -12
  38. tests/test_adapter.py +0 -529
  39. tests/test_adapter_coverage.py +0 -274
  40. tests/test_basic_dispatcher.py +0 -169
  41. tests/test_command_registry.py +0 -328
  42. tests/test_examples.py +0 -32
  43. tests/test_mcp_proxy_adapter.py +0 -568
  44. tests/test_mcp_proxy_adapter_basic.py +0 -262
  45. tests/test_part1.py +0 -348
  46. tests/test_part2.py +0 -524
  47. tests/test_schema.py +0 -358
  48. tests/test_simple_adapter.py +0 -251
  49. {mcp_proxy_adapter-2.1.1.dist-info → mcp_proxy_adapter-2.1.3.dist-info}/WHEEL +0 -0
  50. {mcp_proxy_adapter-2.1.1.dist-info → mcp_proxy_adapter-2.1.3.dist-info}/licenses/LICENSE +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mcp-proxy-adapter
3
- Version: 2.1.1
3
+ Version: 2.1.3
4
4
  Summary: Adapter for exposing Command Registry commands as tools for AI models via MCP Proxy.
5
5
  Home-page: https://github.com/vasilyvz/mcp-proxy-adapter
6
6
  Author: Vasiliy VZ
@@ -0,0 +1,18 @@
1
+ mcp_proxy_adapter/__init__.py,sha256=_6D-TfANWp9zc550M5LUeGPvioFqG1bAl3tZj-gNmJU,463
2
+ mcp_proxy_adapter/adapter.py,sha256=76dkVeDuqLsJ5AhuftzLlwy2M6yr_PfNbmNfo9dXVhc,28844
3
+ mcp_proxy_adapter/models.py,sha256=acqVQBYAojHXeJ1MJyvpMyT6-J6aMxWuZMszn_-RsOU,2338
4
+ mcp_proxy_adapter/registry.py,sha256=jgC4TKaPbMbAsoxvGp2ToaOE4drD-VfZug7WJbm4IW4,15853
5
+ mcp_proxy_adapter/schema.py,sha256=HZM0TTQTSi8ha1TEeVevdCyGZOUPoT1soB7Nex0hV50,10947
6
+ mcp_proxy_adapter/analyzers/__init__.py,sha256=2rcYZDP-bXq078MQpxP32lAwYYyRhOwAQGBcefBfBzY,368
7
+ mcp_proxy_adapter/analyzers/docstring_analyzer.py,sha256=T3FLJEo_uChShfiEKRl8GpVoHvh5HiudZkxnj4KixfA,7541
8
+ mcp_proxy_adapter/analyzers/type_analyzer.py,sha256=6Wac7osKwF03waFSwQ8ZM0Wqn_zAP2D-I4WMEpR0hQM,5230
9
+ mcp_proxy_adapter/dispatchers/__init__.py,sha256=FWgimgInGphIjCEnvA3-ZExiapUzYAVis2H9C5IWivU,365
10
+ mcp_proxy_adapter/dispatchers/base_dispatcher.py,sha256=S5_Xri058jAmOWeit1tedB_GMZQ9RLcNcYabA83ZF6k,2288
11
+ mcp_proxy_adapter/dispatchers/json_rpc_dispatcher.py,sha256=ffu1M32E1AdC7IB44mlbV2L56eJQMsp-7fYi_r4rmHc,6331
12
+ mcp_proxy_adapter/validators/docstring_validator.py,sha256=Onpq2iNJ1qF4ejkJJIlBkLROuSNIVALHVmXIgkCpaFI,2934
13
+ mcp_proxy_adapter/validators/metadata_validator.py,sha256=uCrn38-VYYn89l6f5CC_GoTAHAweaOW2Z6Esro1rtGw,3155
14
+ mcp_proxy_adapter-2.1.3.dist-info/licenses/LICENSE,sha256=OkApFEwdgMCt_mbvUI-eIwKMSTe38K3XnU2DT5ub-wI,1072
15
+ mcp_proxy_adapter-2.1.3.dist-info/METADATA,sha256=Y--HJ-YuTBaOOn0IUEIYPDvncaYfpjJwiZztUUkWwc8,8150
16
+ mcp_proxy_adapter-2.1.3.dist-info/WHEEL,sha256=wXxTzcEDnjrTwFYjLPcsW_7_XihufBwmpiBeiXNBGEA,91
17
+ mcp_proxy_adapter-2.1.3.dist-info/top_level.txt,sha256=JZT7vPLBYrtroX-ij68JBhJYbjDdghcV-DFySRy-Nnw,18
18
+ mcp_proxy_adapter-2.1.3.dist-info/RECORD,,
@@ -0,0 +1 @@
1
+ mcp_proxy_adapter
docs/README.md DELETED
@@ -1,172 +0,0 @@
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 DELETED
@@ -1,172 +0,0 @@
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 DELETED
@@ -1,251 +0,0 @@
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
- ![Components Diagram](../diagrams/command_registry_components.png)
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
- ```