mcp-proxy-adapter 3.1.6__py3-none-any.whl → 4.1.0__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.
- mcp_proxy_adapter/api/app.py +65 -27
- mcp_proxy_adapter/api/handlers.py +1 -1
- mcp_proxy_adapter/api/middleware/error_handling.py +11 -10
- mcp_proxy_adapter/api/tool_integration.py +5 -2
- mcp_proxy_adapter/api/tools.py +3 -3
- mcp_proxy_adapter/commands/base.py +19 -1
- mcp_proxy_adapter/commands/command_registry.py +254 -8
- mcp_proxy_adapter/commands/hooks.py +260 -0
- mcp_proxy_adapter/commands/reload_command.py +211 -0
- mcp_proxy_adapter/commands/reload_settings_command.py +125 -0
- mcp_proxy_adapter/commands/settings_command.py +189 -0
- mcp_proxy_adapter/config.py +16 -1
- mcp_proxy_adapter/core/__init__.py +44 -0
- mcp_proxy_adapter/core/logging.py +87 -34
- mcp_proxy_adapter/core/settings.py +376 -0
- mcp_proxy_adapter/core/utils.py +2 -2
- mcp_proxy_adapter/custom_openapi.py +81 -2
- mcp_proxy_adapter/examples/README.md +124 -0
- mcp_proxy_adapter/examples/__init__.py +7 -0
- mcp_proxy_adapter/examples/basic_server/README.md +60 -0
- mcp_proxy_adapter/examples/basic_server/__init__.py +7 -0
- mcp_proxy_adapter/examples/basic_server/basic_custom_settings.json +39 -0
- mcp_proxy_adapter/examples/basic_server/config.json +35 -0
- mcp_proxy_adapter/examples/basic_server/custom_settings_example.py +238 -0
- mcp_proxy_adapter/examples/basic_server/server.py +98 -0
- mcp_proxy_adapter/examples/custom_commands/README.md +127 -0
- mcp_proxy_adapter/examples/custom_commands/__init__.py +27 -0
- mcp_proxy_adapter/examples/custom_commands/advanced_hooks.py +250 -0
- mcp_proxy_adapter/examples/custom_commands/auto_commands/__init__.py +6 -0
- mcp_proxy_adapter/examples/custom_commands/auto_commands/auto_echo_command.py +103 -0
- mcp_proxy_adapter/examples/custom_commands/auto_commands/auto_info_command.py +111 -0
- mcp_proxy_adapter/examples/custom_commands/config.json +62 -0
- mcp_proxy_adapter/examples/custom_commands/custom_health_command.py +169 -0
- mcp_proxy_adapter/examples/custom_commands/custom_help_command.py +215 -0
- mcp_proxy_adapter/examples/custom_commands/custom_openapi_generator.py +76 -0
- mcp_proxy_adapter/examples/custom_commands/custom_settings.json +96 -0
- mcp_proxy_adapter/examples/custom_commands/custom_settings_manager.py +241 -0
- mcp_proxy_adapter/examples/custom_commands/data_transform_command.py +135 -0
- mcp_proxy_adapter/examples/custom_commands/echo_command.py +122 -0
- mcp_proxy_adapter/examples/custom_commands/hooks.py +230 -0
- mcp_proxy_adapter/examples/custom_commands/intercept_command.py +123 -0
- mcp_proxy_adapter/examples/custom_commands/manual_echo_command.py +103 -0
- mcp_proxy_adapter/examples/custom_commands/server.py +223 -0
- mcp_proxy_adapter/examples/custom_commands/test_hooks.py +176 -0
- mcp_proxy_adapter/examples/deployment/README.md +49 -0
- mcp_proxy_adapter/examples/deployment/__init__.py +7 -0
- mcp_proxy_adapter/examples/deployment/config.development.json +8 -0
- {examples/basic_example → mcp_proxy_adapter/examples/deployment}/config.json +11 -7
- mcp_proxy_adapter/examples/deployment/config.production.json +12 -0
- mcp_proxy_adapter/examples/deployment/config.staging.json +11 -0
- mcp_proxy_adapter/examples/deployment/docker-compose.yml +31 -0
- mcp_proxy_adapter/examples/deployment/run.sh +43 -0
- mcp_proxy_adapter/examples/deployment/run_docker.sh +84 -0
- mcp_proxy_adapter/openapi.py +3 -2
- mcp_proxy_adapter/tests/api/test_custom_openapi.py +617 -0
- mcp_proxy_adapter/tests/api/test_handlers.py +522 -0
- mcp_proxy_adapter/tests/api/test_schemas.py +546 -0
- mcp_proxy_adapter/tests/api/test_tool_integration.py +531 -0
- mcp_proxy_adapter/tests/unit/test_base_command.py +391 -85
- mcp_proxy_adapter/version.py +1 -1
- {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/METADATA +3 -3
- mcp_proxy_adapter-4.1.0.dist-info/RECORD +110 -0
- {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/WHEEL +1 -1
- {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/top_level.txt +0 -1
- examples/__init__.py +0 -19
- examples/anti_patterns/README.md +0 -51
- examples/anti_patterns/__init__.py +0 -9
- examples/anti_patterns/bad_design/README.md +0 -72
- examples/anti_patterns/bad_design/global_state.py +0 -170
- examples/anti_patterns/bad_design/monolithic_command.py +0 -272
- examples/basic_example/README.md +0 -245
- examples/basic_example/__init__.py +0 -8
- examples/basic_example/commands/__init__.py +0 -5
- examples/basic_example/commands/echo_command.py +0 -95
- examples/basic_example/commands/math_command.py +0 -151
- examples/basic_example/commands/time_command.py +0 -152
- examples/basic_example/docs/EN/README.md +0 -177
- examples/basic_example/docs/RU/README.md +0 -177
- examples/basic_example/server.py +0 -151
- examples/basic_example/tests/conftest.py +0 -243
- examples/check_vstl_schema.py +0 -106
- examples/commands/echo_command.py +0 -52
- examples/commands/echo_command_di.py +0 -152
- examples/commands/echo_result.py +0 -65
- examples/commands/get_date_command.py +0 -98
- examples/commands/new_uuid4_command.py +0 -91
- examples/complete_example/Dockerfile +0 -24
- examples/complete_example/README.md +0 -92
- examples/complete_example/__init__.py +0 -8
- examples/complete_example/commands/__init__.py +0 -5
- examples/complete_example/commands/system_command.py +0 -328
- examples/complete_example/config.json +0 -41
- examples/complete_example/configs/config.dev.yaml +0 -40
- examples/complete_example/configs/config.docker.yaml +0 -40
- examples/complete_example/docker-compose.yml +0 -35
- examples/complete_example/requirements.txt +0 -20
- examples/complete_example/server.py +0 -113
- examples/di_example/.pytest_cache/README.md +0 -8
- examples/di_example/server.py +0 -249
- examples/fix_vstl_help.py +0 -123
- examples/minimal_example/README.md +0 -65
- examples/minimal_example/__init__.py +0 -8
- examples/minimal_example/config.json +0 -14
- examples/minimal_example/main.py +0 -136
- examples/minimal_example/simple_server.py +0 -163
- examples/minimal_example/tests/conftest.py +0 -171
- examples/minimal_example/tests/test_hello_command.py +0 -111
- examples/minimal_example/tests/test_integration.py +0 -181
- examples/patch_vstl_service.py +0 -105
- examples/patch_vstl_service_mcp.py +0 -108
- examples/server.py +0 -69
- examples/simple_server.py +0 -128
- examples/test_package_3.1.4.py +0 -177
- examples/test_server.py +0 -134
- examples/tool_description_example.py +0 -82
- mcp_proxy_adapter/py.typed +0 -0
- mcp_proxy_adapter-3.1.6.dist-info/RECORD +0 -118
- {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/licenses/LICENSE +0 -0
examples/basic_example/README.md
DELETED
@@ -1,245 +0,0 @@
|
|
1
|
-
# Basic MCP Proxy Adapter Example
|
2
|
-
|
3
|
-
This example demonstrates how to use MCP Proxy Adapter to create a microservice with multiple commands organized in separate files.
|
4
|
-
|
5
|
-
## English Documentation
|
6
|
-
|
7
|
-
### Overview
|
8
|
-
|
9
|
-
This example shows:
|
10
|
-
- Creating a microservice using MCP Proxy Adapter
|
11
|
-
- Configuring the service using JSON configuration file
|
12
|
-
- Automatic command discovery from a package
|
13
|
-
- Implementing various command types with their result classes
|
14
|
-
- Running the service with auto-reload for development
|
15
|
-
|
16
|
-
### Setup
|
17
|
-
|
18
|
-
1. Make sure you have installed MCP Proxy Adapter package
|
19
|
-
2. Install additional dependencies:
|
20
|
-
```
|
21
|
-
pip install pytz uvicorn
|
22
|
-
```
|
23
|
-
|
24
|
-
### Configuration
|
25
|
-
|
26
|
-
The service uses `config.json` for configuration. The key settings are:
|
27
|
-
- Server host and port
|
28
|
-
- Logging configuration
|
29
|
-
- Command discovery settings
|
30
|
-
|
31
|
-
### Available Commands
|
32
|
-
|
33
|
-
The example includes several commands:
|
34
|
-
- `echo` - Echo back a message
|
35
|
-
- `time` - Get current time in different formats and timezones
|
36
|
-
- `math` - Perform basic math operations
|
37
|
-
|
38
|
-
### Running the Example
|
39
|
-
|
40
|
-
```bash
|
41
|
-
cd examples/basic_example
|
42
|
-
python server.py
|
43
|
-
```
|
44
|
-
|
45
|
-
The service will start on http://localhost:8000 by default, with API documentation available at http://localhost:8000/docs
|
46
|
-
|
47
|
-
### Testing Commands
|
48
|
-
|
49
|
-
You can test commands using curl:
|
50
|
-
|
51
|
-
```bash
|
52
|
-
# Echo command
|
53
|
-
curl -X POST http://localhost:8000/cmd -H "Content-Type: application/json" -d '{"command": "echo", "params": {"message": "Hello, world!"}}'
|
54
|
-
|
55
|
-
# Time command
|
56
|
-
curl -X POST http://localhost:8000/cmd -H "Content-Type: application/json" -d '{"command": "time", "params": {"timezone": "Europe/London"}}'
|
57
|
-
|
58
|
-
# JSON-RPC style request
|
59
|
-
curl -X POST http://localhost:8000/api/jsonrpc -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "echo", "params": {"message": "Hello RPC!"}, "id": 1}'
|
60
|
-
```
|
61
|
-
|
62
|
-
## Русская документация
|
63
|
-
|
64
|
-
### Обзор
|
65
|
-
|
66
|
-
Этот пример демонстрирует:
|
67
|
-
- Создание микросервиса с использованием MCP Proxy Adapter
|
68
|
-
- Настройку сервиса с использованием JSON-файла конфигурации
|
69
|
-
- Автоматическое обнаружение команд из пакета
|
70
|
-
- Реализацию различных типов команд с их классами результатов
|
71
|
-
- Запуск сервиса с автоперезагрузкой для разработки
|
72
|
-
|
73
|
-
### Настройка
|
74
|
-
|
75
|
-
1. Убедитесь, что у вас установлен пакет MCP Proxy Adapter
|
76
|
-
2. Установите дополнительные зависимости:
|
77
|
-
```
|
78
|
-
pip install pytz uvicorn
|
79
|
-
```
|
80
|
-
|
81
|
-
### Конфигурация
|
82
|
-
|
83
|
-
Сервис использует `config.json` для конфигурации. Основные настройки:
|
84
|
-
- Хост и порт сервера
|
85
|
-
- Настройки логирования
|
86
|
-
- Настройки обнаружения команд
|
87
|
-
|
88
|
-
### Доступные команды
|
89
|
-
|
90
|
-
Пример включает несколько команд:
|
91
|
-
- `echo` - Эхо-ответ сообщения
|
92
|
-
- `time` - Получение текущего времени в разных форматах и часовых поясах
|
93
|
-
- `math` - Выполнение базовых математических операций
|
94
|
-
|
95
|
-
### Запуск примера
|
96
|
-
|
97
|
-
```bash
|
98
|
-
cd examples/basic_example
|
99
|
-
python server.py
|
100
|
-
```
|
101
|
-
|
102
|
-
Сервис запустится на http://localhost:8000 по умолчанию, документация API доступна по адресу http://localhost:8000/docs
|
103
|
-
|
104
|
-
### Тестирование команд
|
105
|
-
|
106
|
-
Вы можете тестировать команды с помощью curl:
|
107
|
-
|
108
|
-
```bash
|
109
|
-
# Команда echo
|
110
|
-
curl -X POST http://localhost:8000/cmd -H "Content-Type: application/json" -d '{"command": "echo", "params": {"message": "Привет, мир!"}}'
|
111
|
-
|
112
|
-
# Команда time
|
113
|
-
curl -X POST http://localhost:8000/cmd -H "Content-Type: application/json" -d '{"command": "time", "params": {"timezone": "Europe/Moscow"}}'
|
114
|
-
|
115
|
-
# Запрос в стиле JSON-RPC
|
116
|
-
curl -X POST http://localhost:8000/api/jsonrpc -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "echo", "params": {"message": "Привет RPC!"}, "id": 1}'
|
117
|
-
```
|
118
|
-
|
119
|
-
## Структура примера
|
120
|
-
|
121
|
-
```
|
122
|
-
basic_example/
|
123
|
-
├── commands/ # Директория с командами
|
124
|
-
│ ├── __init__.py # Инициализация пакета команд
|
125
|
-
│ ├── echo_command.py # Команда эхо
|
126
|
-
│ ├── math_command.py # Математическая команда
|
127
|
-
│ └── time_command.py # Команда времени
|
128
|
-
├── config.json # Файл конфигурации JSON
|
129
|
-
├── README.md # Документация
|
130
|
-
└── server.py # Файл запуска сервера
|
131
|
-
```
|
132
|
-
|
133
|
-
## Запуск примера
|
134
|
-
|
135
|
-
```bash
|
136
|
-
# Перейти в директорию проекта
|
137
|
-
cd examples/basic_example
|
138
|
-
|
139
|
-
# Создать директорию для логов, если она не существует
|
140
|
-
mkdir -p logs
|
141
|
-
|
142
|
-
# Запустить сервер
|
143
|
-
python server.py
|
144
|
-
```
|
145
|
-
|
146
|
-
После запуска сервер будет доступен по адресу [http://localhost:8000](http://localhost:8000).
|
147
|
-
|
148
|
-
## Доступные команды
|
149
|
-
|
150
|
-
### 1. `echo` - Эхо-команда
|
151
|
-
|
152
|
-
Возвращает переданное сообщение.
|
153
|
-
|
154
|
-
**Параметры:**
|
155
|
-
- `message` (string) - Сообщение для эхо
|
156
|
-
|
157
|
-
**Пример запроса:**
|
158
|
-
```json
|
159
|
-
{
|
160
|
-
"jsonrpc": "2.0",
|
161
|
-
"method": "echo",
|
162
|
-
"params": {
|
163
|
-
"message": "Hello, World!"
|
164
|
-
},
|
165
|
-
"id": 1
|
166
|
-
}
|
167
|
-
```
|
168
|
-
|
169
|
-
### 2. `math` - Математическая команда
|
170
|
-
|
171
|
-
Выполняет математическую операцию над двумя числами.
|
172
|
-
|
173
|
-
**Параметры:**
|
174
|
-
- `a` (number) - Первое число
|
175
|
-
- `b` (number) - Второе число
|
176
|
-
- `operation` (string) - Операция (add, subtract, multiply, divide)
|
177
|
-
|
178
|
-
**Пример запроса:**
|
179
|
-
```json
|
180
|
-
{
|
181
|
-
"jsonrpc": "2.0",
|
182
|
-
"method": "math",
|
183
|
-
"params": {
|
184
|
-
"a": 10,
|
185
|
-
"b": 5,
|
186
|
-
"operation": "add"
|
187
|
-
},
|
188
|
-
"id": 1
|
189
|
-
}
|
190
|
-
```
|
191
|
-
|
192
|
-
### 3. `time` - Команда времени
|
193
|
-
|
194
|
-
Возвращает текущее время и дату.
|
195
|
-
|
196
|
-
**Параметры:**
|
197
|
-
- `format` (string, optional) - Формат времени (default: "%Y-%m-%d %H:%M:%S")
|
198
|
-
- `timezone` (string, optional) - Часовой пояс (default: "UTC")
|
199
|
-
|
200
|
-
**Пример запроса:**
|
201
|
-
```json
|
202
|
-
{
|
203
|
-
"jsonrpc": "2.0",
|
204
|
-
"method": "time",
|
205
|
-
"params": {
|
206
|
-
"format": "%d.%m.%Y %H:%M:%S",
|
207
|
-
"timezone": "Europe/Moscow"
|
208
|
-
},
|
209
|
-
"id": 1
|
210
|
-
}
|
211
|
-
```
|
212
|
-
|
213
|
-
## Тестирование API
|
214
|
-
|
215
|
-
### Через веб-интерфейс
|
216
|
-
|
217
|
-
Откройте в браузере [http://localhost:8000/docs](http://localhost:8000/docs) для доступа к интерактивной документации Swagger UI.
|
218
|
-
|
219
|
-
### Через командную строку
|
220
|
-
|
221
|
-
```bash
|
222
|
-
# Вызов команды echo через JSON-RPC
|
223
|
-
curl -X POST "http://localhost:8000/api/jsonrpc" \
|
224
|
-
-H "Content-Type: application/json" \
|
225
|
-
-d '{"jsonrpc": "2.0", "method": "echo", "params": {"message": "Hello!"}, "id": 1}'
|
226
|
-
|
227
|
-
# Вызов команды math через упрощенный эндпоинт
|
228
|
-
curl -X POST "http://localhost:8000/cmd" \
|
229
|
-
-H "Content-Type: application/json" \
|
230
|
-
-d '{"command": "math", "params": {"a": 10, "b": 5, "operation": "add"}}'
|
231
|
-
|
232
|
-
# Вызов команды time через endpoint /api/command/{command_name}
|
233
|
-
curl -X POST "http://localhost:8000/api/command/time" \
|
234
|
-
-H "Content-Type: application/json" \
|
235
|
-
-d '{"format": "%d.%m.%Y %H:%M:%S", "timezone": "UTC"}'
|
236
|
-
```
|
237
|
-
|
238
|
-
## Что демонстрирует этот пример
|
239
|
-
|
240
|
-
1. Прямое использование FastAPI и uvicorn с MCP Proxy Adapter
|
241
|
-
2. Организация команд в отдельные файлы
|
242
|
-
3. Автоматическое обнаружение и регистрация команд
|
243
|
-
4. Различные типы команд и параметров
|
244
|
-
5. Обработка ошибок
|
245
|
-
6. Различные способы вызова команд (JSON-RPC, /cmd, /api/command/{command_name})
|
@@ -1,95 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Echo command module.
|
3
|
-
|
4
|
-
This module contains a simple echo command that returns the input message.
|
5
|
-
"""
|
6
|
-
|
7
|
-
from typing import Dict, Any
|
8
|
-
|
9
|
-
from mcp_proxy_adapter import Command, SuccessResult
|
10
|
-
|
11
|
-
|
12
|
-
class EchoResult(SuccessResult):
|
13
|
-
"""
|
14
|
-
Result of echo command.
|
15
|
-
|
16
|
-
Attributes:
|
17
|
-
message (str): Echo message
|
18
|
-
"""
|
19
|
-
|
20
|
-
def __init__(self, message: str):
|
21
|
-
"""
|
22
|
-
Initialize result.
|
23
|
-
|
24
|
-
Args:
|
25
|
-
message: Message to echo back
|
26
|
-
"""
|
27
|
-
self.message = message
|
28
|
-
|
29
|
-
def to_dict(self) -> Dict[str, Any]:
|
30
|
-
"""
|
31
|
-
Convert result to dictionary.
|
32
|
-
|
33
|
-
Returns:
|
34
|
-
Dictionary representation
|
35
|
-
"""
|
36
|
-
return {"message": self.message}
|
37
|
-
|
38
|
-
@classmethod
|
39
|
-
def get_schema(cls) -> Dict[str, Any]:
|
40
|
-
"""
|
41
|
-
Get JSON schema for result.
|
42
|
-
|
43
|
-
Returns:
|
44
|
-
JSON schema
|
45
|
-
"""
|
46
|
-
return {
|
47
|
-
"type": "object",
|
48
|
-
"properties": {
|
49
|
-
"message": {"type": "string", "description": "Echo message"}
|
50
|
-
},
|
51
|
-
"required": ["message"]
|
52
|
-
}
|
53
|
-
|
54
|
-
|
55
|
-
class EchoCommand(Command):
|
56
|
-
"""
|
57
|
-
Command that echoes back input message.
|
58
|
-
|
59
|
-
This command demonstrates simple parameter handling.
|
60
|
-
"""
|
61
|
-
|
62
|
-
name = "echo"
|
63
|
-
result_class = EchoResult
|
64
|
-
|
65
|
-
async def execute(self, message: str) -> EchoResult:
|
66
|
-
"""
|
67
|
-
Execute command.
|
68
|
-
|
69
|
-
Args:
|
70
|
-
message: Message to echo back
|
71
|
-
|
72
|
-
Returns:
|
73
|
-
Echo result containing the input message
|
74
|
-
"""
|
75
|
-
return EchoResult(message)
|
76
|
-
|
77
|
-
@classmethod
|
78
|
-
def get_schema(cls) -> Dict[str, Any]:
|
79
|
-
"""
|
80
|
-
Get JSON schema for command parameters.
|
81
|
-
|
82
|
-
Returns:
|
83
|
-
JSON schema
|
84
|
-
"""
|
85
|
-
return {
|
86
|
-
"type": "object",
|
87
|
-
"properties": {
|
88
|
-
"message": {
|
89
|
-
"type": "string",
|
90
|
-
"description": "Message to echo back"
|
91
|
-
}
|
92
|
-
},
|
93
|
-
"required": ["message"],
|
94
|
-
"additionalProperties": False
|
95
|
-
}
|
@@ -1,151 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Math command module.
|
3
|
-
|
4
|
-
This module contains a command for performing math operations on two numbers.
|
5
|
-
"""
|
6
|
-
|
7
|
-
from typing import Dict, Any, Literal, Union
|
8
|
-
|
9
|
-
from mcp_proxy_adapter import Command, SuccessResult, ErrorResult, InvalidParamsError
|
10
|
-
|
11
|
-
|
12
|
-
class MathResult(SuccessResult):
|
13
|
-
"""
|
14
|
-
Result of math command.
|
15
|
-
|
16
|
-
Attributes:
|
17
|
-
result (float): Result of the math operation
|
18
|
-
operation (str): Operation that was performed
|
19
|
-
a (float): First operand
|
20
|
-
b (float): Second operand
|
21
|
-
"""
|
22
|
-
|
23
|
-
def __init__(self, result: float, operation: str, a: float, b: float):
|
24
|
-
"""
|
25
|
-
Initialize result.
|
26
|
-
|
27
|
-
Args:
|
28
|
-
result: Result of the operation
|
29
|
-
operation: Operation performed
|
30
|
-
a: First operand
|
31
|
-
b: Second operand
|
32
|
-
"""
|
33
|
-
self.result = result
|
34
|
-
self.operation = operation
|
35
|
-
self.a = a
|
36
|
-
self.b = b
|
37
|
-
|
38
|
-
def to_dict(self) -> Dict[str, Any]:
|
39
|
-
"""
|
40
|
-
Convert result to dictionary.
|
41
|
-
|
42
|
-
Returns:
|
43
|
-
Dictionary representation
|
44
|
-
"""
|
45
|
-
return {
|
46
|
-
"result": self.result,
|
47
|
-
"operation": self.operation,
|
48
|
-
"a": self.a,
|
49
|
-
"b": self.b
|
50
|
-
}
|
51
|
-
|
52
|
-
@classmethod
|
53
|
-
def get_schema(cls) -> Dict[str, Any]:
|
54
|
-
"""
|
55
|
-
Get JSON schema for result.
|
56
|
-
|
57
|
-
Returns:
|
58
|
-
JSON schema
|
59
|
-
"""
|
60
|
-
return {
|
61
|
-
"type": "object",
|
62
|
-
"properties": {
|
63
|
-
"result": {"type": "number", "description": "Result of the operation"},
|
64
|
-
"operation": {"type": "string", "description": "Operation performed"},
|
65
|
-
"a": {"type": "number", "description": "First operand"},
|
66
|
-
"b": {"type": "number", "description": "Second operand"}
|
67
|
-
},
|
68
|
-
"required": ["result", "operation", "a", "b"]
|
69
|
-
}
|
70
|
-
|
71
|
-
|
72
|
-
class MathCommand(Command):
|
73
|
-
"""
|
74
|
-
Command that performs math operations.
|
75
|
-
|
76
|
-
This command demonstrates parameter validation and error handling.
|
77
|
-
"""
|
78
|
-
|
79
|
-
name = "math"
|
80
|
-
result_class = MathResult
|
81
|
-
|
82
|
-
async def execute(
|
83
|
-
self,
|
84
|
-
a: float,
|
85
|
-
b: float,
|
86
|
-
operation: Literal["add", "subtract", "multiply", "divide"]
|
87
|
-
) -> Union[MathResult, ErrorResult]:
|
88
|
-
"""
|
89
|
-
Execute command.
|
90
|
-
|
91
|
-
Args:
|
92
|
-
a: First number
|
93
|
-
b: Second number
|
94
|
-
operation: Math operation to perform (add, subtract, multiply, divide)
|
95
|
-
|
96
|
-
Returns:
|
97
|
-
Math result containing the result of the operation
|
98
|
-
|
99
|
-
Raises:
|
100
|
-
InvalidParamsError: If operation is invalid or division by zero
|
101
|
-
"""
|
102
|
-
try:
|
103
|
-
if operation == "add":
|
104
|
-
result = a + b
|
105
|
-
elif operation == "subtract":
|
106
|
-
result = a - b
|
107
|
-
elif operation == "multiply":
|
108
|
-
result = a * b
|
109
|
-
elif operation == "divide":
|
110
|
-
if b == 0:
|
111
|
-
raise InvalidParamsError("Division by zero is not allowed")
|
112
|
-
result = a / b
|
113
|
-
else:
|
114
|
-
raise InvalidParamsError(
|
115
|
-
f"Invalid operation: {operation}. Must be one of: add, subtract, multiply, divide"
|
116
|
-
)
|
117
|
-
|
118
|
-
return MathResult(result, operation, a, b)
|
119
|
-
except Exception as e:
|
120
|
-
if not isinstance(e, InvalidParamsError):
|
121
|
-
raise InvalidParamsError(f"Error performing math operation: {str(e)}")
|
122
|
-
raise
|
123
|
-
|
124
|
-
@classmethod
|
125
|
-
def get_schema(cls) -> Dict[str, Any]:
|
126
|
-
"""
|
127
|
-
Get JSON schema for command parameters.
|
128
|
-
|
129
|
-
Returns:
|
130
|
-
JSON schema
|
131
|
-
"""
|
132
|
-
return {
|
133
|
-
"type": "object",
|
134
|
-
"properties": {
|
135
|
-
"a": {
|
136
|
-
"type": "number",
|
137
|
-
"description": "First number"
|
138
|
-
},
|
139
|
-
"b": {
|
140
|
-
"type": "number",
|
141
|
-
"description": "Second number"
|
142
|
-
},
|
143
|
-
"operation": {
|
144
|
-
"type": "string",
|
145
|
-
"enum": ["add", "subtract", "multiply", "divide"],
|
146
|
-
"description": "Math operation to perform"
|
147
|
-
}
|
148
|
-
},
|
149
|
-
"required": ["a", "b", "operation"],
|
150
|
-
"additionalProperties": False
|
151
|
-
}
|
@@ -1,152 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Time command module.
|
3
|
-
|
4
|
-
This module contains a command for getting current time in different formats and timezones.
|
5
|
-
"""
|
6
|
-
|
7
|
-
import datetime
|
8
|
-
from typing import Dict, Any, Optional
|
9
|
-
|
10
|
-
import pytz
|
11
|
-
|
12
|
-
from mcp_proxy_adapter import Command, SuccessResult, InvalidParamsError
|
13
|
-
|
14
|
-
|
15
|
-
class TimeResult(SuccessResult):
|
16
|
-
"""
|
17
|
-
Result of time command.
|
18
|
-
|
19
|
-
Attributes:
|
20
|
-
time (str): Formatted time string
|
21
|
-
timestamp (int): Unix timestamp
|
22
|
-
timezone (str): Timezone used
|
23
|
-
format (str): Format string used
|
24
|
-
"""
|
25
|
-
|
26
|
-
def __init__(self, time: str, timestamp: int, timezone: str, format: str):
|
27
|
-
"""
|
28
|
-
Initialize result.
|
29
|
-
|
30
|
-
Args:
|
31
|
-
time: Formatted time string
|
32
|
-
timestamp: Unix timestamp
|
33
|
-
timezone: Timezone used
|
34
|
-
format: Format string used
|
35
|
-
"""
|
36
|
-
self.time = time
|
37
|
-
self.timestamp = timestamp
|
38
|
-
self.timezone = timezone
|
39
|
-
self.format = format
|
40
|
-
|
41
|
-
def to_dict(self) -> Dict[str, Any]:
|
42
|
-
"""
|
43
|
-
Convert result to dictionary.
|
44
|
-
|
45
|
-
Returns:
|
46
|
-
Dictionary representation
|
47
|
-
"""
|
48
|
-
return {
|
49
|
-
"time": self.time,
|
50
|
-
"timestamp": self.timestamp,
|
51
|
-
"timezone": self.timezone,
|
52
|
-
"format": self.format
|
53
|
-
}
|
54
|
-
|
55
|
-
@classmethod
|
56
|
-
def get_schema(cls) -> Dict[str, Any]:
|
57
|
-
"""
|
58
|
-
Get JSON schema for result.
|
59
|
-
|
60
|
-
Returns:
|
61
|
-
JSON schema
|
62
|
-
"""
|
63
|
-
return {
|
64
|
-
"type": "object",
|
65
|
-
"properties": {
|
66
|
-
"time": {"type": "string", "description": "Formatted time string"},
|
67
|
-
"timestamp": {"type": "integer", "description": "Unix timestamp"},
|
68
|
-
"timezone": {"type": "string", "description": "Timezone used"},
|
69
|
-
"format": {"type": "string", "description": "Format string used"}
|
70
|
-
},
|
71
|
-
"required": ["time", "timestamp", "timezone", "format"]
|
72
|
-
}
|
73
|
-
|
74
|
-
|
75
|
-
class TimeCommand(Command):
|
76
|
-
"""
|
77
|
-
Command that returns current time.
|
78
|
-
|
79
|
-
This command demonstrates optional parameters and timezone handling.
|
80
|
-
"""
|
81
|
-
|
82
|
-
name = "time"
|
83
|
-
result_class = TimeResult
|
84
|
-
|
85
|
-
async def execute(
|
86
|
-
self,
|
87
|
-
format: str = "%Y-%m-%d %H:%M:%S",
|
88
|
-
timezone: str = "UTC"
|
89
|
-
) -> TimeResult:
|
90
|
-
"""
|
91
|
-
Execute command.
|
92
|
-
|
93
|
-
Args:
|
94
|
-
format: Time format string (strftime format)
|
95
|
-
timezone: Timezone name (e.g., "UTC", "Europe/London")
|
96
|
-
|
97
|
-
Returns:
|
98
|
-
Time result with formatted time
|
99
|
-
|
100
|
-
Raises:
|
101
|
-
InvalidParamsError: If timezone is invalid
|
102
|
-
"""
|
103
|
-
try:
|
104
|
-
# Validate timezone
|
105
|
-
if timezone not in pytz.all_timezones:
|
106
|
-
raise InvalidParamsError(f"Invalid timezone: {timezone}")
|
107
|
-
|
108
|
-
# Get current time in the specified timezone
|
109
|
-
tz = pytz.timezone(timezone)
|
110
|
-
now = datetime.datetime.now(tz)
|
111
|
-
|
112
|
-
# Format time according to the format string
|
113
|
-
formatted_time = now.strftime(format)
|
114
|
-
|
115
|
-
# Get Unix timestamp
|
116
|
-
timestamp = int(now.timestamp())
|
117
|
-
|
118
|
-
return TimeResult(
|
119
|
-
time=formatted_time,
|
120
|
-
timestamp=timestamp,
|
121
|
-
timezone=timezone,
|
122
|
-
format=format
|
123
|
-
)
|
124
|
-
except Exception as e:
|
125
|
-
if not isinstance(e, InvalidParamsError):
|
126
|
-
raise InvalidParamsError(f"Error processing time: {str(e)}")
|
127
|
-
raise
|
128
|
-
|
129
|
-
@classmethod
|
130
|
-
def get_schema(cls) -> Dict[str, Any]:
|
131
|
-
"""
|
132
|
-
Get JSON schema for command parameters.
|
133
|
-
|
134
|
-
Returns:
|
135
|
-
JSON schema
|
136
|
-
"""
|
137
|
-
return {
|
138
|
-
"type": "object",
|
139
|
-
"properties": {
|
140
|
-
"format": {
|
141
|
-
"type": "string",
|
142
|
-
"description": "Time format string (strftime format)",
|
143
|
-
"default": "%Y-%m-%d %H:%M:%S"
|
144
|
-
},
|
145
|
-
"timezone": {
|
146
|
-
"type": "string",
|
147
|
-
"description": "Timezone name (e.g., 'UTC', 'Europe/London')",
|
148
|
-
"default": "UTC"
|
149
|
-
}
|
150
|
-
},
|
151
|
-
"additionalProperties": False
|
152
|
-
}
|