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
@@ -1,181 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Integration tests for the minimal example of MCP Proxy Adapter.
|
3
|
-
|
4
|
-
These tests start a real server instance and test the API endpoints.
|
5
|
-
"""
|
6
|
-
|
7
|
-
import os
|
8
|
-
import time
|
9
|
-
import pytest
|
10
|
-
import requests
|
11
|
-
from typing import Dict, Any, Callable
|
12
|
-
|
13
|
-
from conftest import ServerProcess
|
14
|
-
|
15
|
-
|
16
|
-
class TestHelloCommandIntegration:
|
17
|
-
"""Integration tests for the HelloCommand API."""
|
18
|
-
|
19
|
-
def test_jsonrpc_hello_default(self, server: ServerProcess, jsonrpc_client: Callable):
|
20
|
-
"""Test the hello command via JSON-RPC with default parameters."""
|
21
|
-
# Make JSON-RPC request
|
22
|
-
response = jsonrpc_client("hello", {})
|
23
|
-
|
24
|
-
# Check response
|
25
|
-
assert "jsonrpc" in response
|
26
|
-
assert response["jsonrpc"] == "2.0"
|
27
|
-
assert "id" in response
|
28
|
-
assert "result" in response
|
29
|
-
assert "message" in response["result"]
|
30
|
-
assert response["result"]["message"] == "Hello, World!"
|
31
|
-
|
32
|
-
def test_jsonrpc_hello_custom_name(self, server: ServerProcess, jsonrpc_client: Callable):
|
33
|
-
"""Test the hello command via JSON-RPC with custom name parameter."""
|
34
|
-
# Make JSON-RPC request
|
35
|
-
response = jsonrpc_client("hello", {"name": "Integration Test"})
|
36
|
-
|
37
|
-
# Check response
|
38
|
-
assert "result" in response
|
39
|
-
assert "message" in response["result"]
|
40
|
-
assert response["result"]["message"] == "Hello, Integration Test!"
|
41
|
-
|
42
|
-
def test_cmd_endpoint_hello(self, server: ServerProcess, api_url: str):
|
43
|
-
"""Test the hello command via the /cmd endpoint."""
|
44
|
-
# Prepare request
|
45
|
-
payload = {
|
46
|
-
"command": "hello",
|
47
|
-
"params": {"name": "CMD Endpoint"}
|
48
|
-
}
|
49
|
-
|
50
|
-
# Make request
|
51
|
-
response = requests.post(
|
52
|
-
f"{api_url}/cmd",
|
53
|
-
json=payload,
|
54
|
-
headers={"Content-Type": "application/json"}
|
55
|
-
)
|
56
|
-
|
57
|
-
# Check response
|
58
|
-
assert response.status_code == 200
|
59
|
-
data = response.json()
|
60
|
-
assert "result" in data
|
61
|
-
assert "message" in data["result"]
|
62
|
-
assert data["result"]["message"] == "Hello, CMD Endpoint!"
|
63
|
-
|
64
|
-
def test_api_command_endpoint_hello(self, server: ServerProcess, api_url: str):
|
65
|
-
"""Test the hello command via the /api/command/{command_name} endpoint."""
|
66
|
-
# Prepare params
|
67
|
-
params = {"name": "API Command Endpoint"}
|
68
|
-
|
69
|
-
# Make request
|
70
|
-
response = requests.post(
|
71
|
-
f"{api_url}/api/command/hello",
|
72
|
-
json=params,
|
73
|
-
headers={"Content-Type": "application/json"}
|
74
|
-
)
|
75
|
-
|
76
|
-
# Check response
|
77
|
-
assert response.status_code == 200
|
78
|
-
data = response.json()
|
79
|
-
assert "message" in data
|
80
|
-
assert data["message"] == "Hello, API Command Endpoint!"
|
81
|
-
|
82
|
-
def test_jsonrpc_batch_request(self, server: ServerProcess, api_url: str):
|
83
|
-
"""Test batch JSON-RPC requests with hello command."""
|
84
|
-
# Prepare batch request
|
85
|
-
batch = [
|
86
|
-
{
|
87
|
-
"jsonrpc": "2.0",
|
88
|
-
"method": "hello",
|
89
|
-
"params": {"name": "Batch 1"},
|
90
|
-
"id": 1
|
91
|
-
},
|
92
|
-
{
|
93
|
-
"jsonrpc": "2.0",
|
94
|
-
"method": "hello",
|
95
|
-
"params": {"name": "Batch 2"},
|
96
|
-
"id": 2
|
97
|
-
}
|
98
|
-
]
|
99
|
-
|
100
|
-
# Make request
|
101
|
-
response = requests.post(
|
102
|
-
f"{api_url}/api/jsonrpc",
|
103
|
-
json=batch,
|
104
|
-
headers={"Content-Type": "application/json"}
|
105
|
-
)
|
106
|
-
|
107
|
-
# Check response
|
108
|
-
assert response.status_code == 200
|
109
|
-
data = response.json()
|
110
|
-
assert isinstance(data, list)
|
111
|
-
assert len(data) == 2
|
112
|
-
|
113
|
-
# Check first result
|
114
|
-
assert data[0]["id"] == 1
|
115
|
-
assert data[0]["result"]["message"] == "Hello, Batch 1!"
|
116
|
-
|
117
|
-
# Check second result
|
118
|
-
assert data[1]["id"] == 2
|
119
|
-
assert data[1]["result"]["message"] == "Hello, Batch 2!"
|
120
|
-
|
121
|
-
|
122
|
-
class TestServerIntegration:
|
123
|
-
"""Integration tests for the server itself."""
|
124
|
-
|
125
|
-
def test_health_endpoint(self, server: ServerProcess, api_url: str):
|
126
|
-
"""Test the /health endpoint."""
|
127
|
-
response = requests.get(f"{api_url}/health")
|
128
|
-
|
129
|
-
# Check response
|
130
|
-
assert response.status_code == 200
|
131
|
-
data = response.json()
|
132
|
-
assert "status" in data
|
133
|
-
assert data["status"] == "ok"
|
134
|
-
|
135
|
-
def test_openapi_schema(self, server: ServerProcess, api_url: str):
|
136
|
-
"""Test the OpenAPI schema endpoint."""
|
137
|
-
response = requests.get(f"{api_url}/openapi.json")
|
138
|
-
|
139
|
-
# Check response
|
140
|
-
assert response.status_code == 200
|
141
|
-
schema = response.json()
|
142
|
-
|
143
|
-
# Check schema structure
|
144
|
-
assert "openapi" in schema
|
145
|
-
assert "info" in schema
|
146
|
-
assert "paths" in schema
|
147
|
-
|
148
|
-
# Проверяем наличие основных эндпоинтов
|
149
|
-
assert "/api/jsonrpc" in schema["paths"] or "/cmd" in schema["paths"]
|
150
|
-
assert "/api/commands" in schema["paths"]
|
151
|
-
|
152
|
-
def test_docs_endpoint(self, server: ServerProcess, api_url: str):
|
153
|
-
"""Test the Swagger UI endpoint."""
|
154
|
-
response = requests.get(f"{api_url}/docs")
|
155
|
-
|
156
|
-
# Check response
|
157
|
-
assert response.status_code == 200
|
158
|
-
assert "text/html" in response.headers["Content-Type"]
|
159
|
-
|
160
|
-
# Check if swagger UI is in the response
|
161
|
-
assert "swagger-ui" in response.text.lower()
|
162
|
-
|
163
|
-
def test_commands_list_endpoint(self, server: ServerProcess, api_url: str):
|
164
|
-
"""Test the commands list endpoint."""
|
165
|
-
response = requests.get(f"{api_url}/api/commands")
|
166
|
-
|
167
|
-
# Check response
|
168
|
-
assert response.status_code == 200
|
169
|
-
data = response.json()
|
170
|
-
|
171
|
-
# Check data structure
|
172
|
-
assert "commands" in data
|
173
|
-
assert isinstance(data["commands"], dict) # Теперь commands это словарь, а не список
|
174
|
-
|
175
|
-
# Check if hello command is in the list
|
176
|
-
assert "hello" in data["commands"]
|
177
|
-
|
178
|
-
# Check hello command details
|
179
|
-
hello_cmd = data["commands"]["hello"]
|
180
|
-
assert "name" in hello_cmd
|
181
|
-
assert hello_cmd["name"] == "hello"
|
examples/patch_vstl_service.py
DELETED
@@ -1,105 +0,0 @@
|
|
1
|
-
#!/usr/bin/env python3
|
2
|
-
"""
|
3
|
-
Скрипт для исправления ошибки 'name null is not defined' в сервисе VSTL.
|
4
|
-
|
5
|
-
Этот скрипт обходит проблему с обработкой null в сервисе vstl
|
6
|
-
при помощи модификации JSON-RPC запросов, чтобы заменять null на None.
|
7
|
-
|
8
|
-
Использование:
|
9
|
-
python patch_vstl_service.py
|
10
|
-
"""
|
11
|
-
|
12
|
-
import sys
|
13
|
-
import json
|
14
|
-
import requests
|
15
|
-
from typing import Dict, Any, Optional
|
16
|
-
|
17
|
-
# URL и заголовки для VSTL сервиса
|
18
|
-
VSTL_URL = "http://localhost:8000/cmd"
|
19
|
-
HEADERS = {"Content-Type": "application/json"}
|
20
|
-
|
21
|
-
def safe_call_vstl(command: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
22
|
-
"""
|
23
|
-
Безопасно вызывает команду в сервисе VSTL, обрабатывая null значения.
|
24
|
-
|
25
|
-
Args:
|
26
|
-
command: Имя команды
|
27
|
-
params: Параметры для команды
|
28
|
-
|
29
|
-
Returns:
|
30
|
-
Dict[str, Any]: Ответ от сервиса
|
31
|
-
"""
|
32
|
-
# Обработка null значений - заменяем null на None для Python
|
33
|
-
safe_params = {}
|
34
|
-
if params:
|
35
|
-
for key, value in params.items():
|
36
|
-
if value == "null" or value == "none":
|
37
|
-
safe_params[key] = None
|
38
|
-
else:
|
39
|
-
safe_params[key] = value
|
40
|
-
|
41
|
-
# Безопасно сериализуем параметры, чтобы null значения были корректно обработаны
|
42
|
-
payload = {
|
43
|
-
"jsonrpc": "2.0",
|
44
|
-
"method": command,
|
45
|
-
"params": safe_params or {},
|
46
|
-
"id": 1
|
47
|
-
}
|
48
|
-
|
49
|
-
# Отправляем запрос
|
50
|
-
response = requests.post(VSTL_URL, json=payload, headers=HEADERS)
|
51
|
-
return response.json()
|
52
|
-
|
53
|
-
def test_vstl_commands():
|
54
|
-
"""
|
55
|
-
Тестирует различные команды в сервисе VSTL с безопасной обработкой null.
|
56
|
-
"""
|
57
|
-
print("=== Тестирование команд VSTL с патчем для обработки null ===\n")
|
58
|
-
|
59
|
-
# Проверяем команду health
|
60
|
-
print("1. Команда health:")
|
61
|
-
response = safe_call_vstl("health", {})
|
62
|
-
print(f"Ответ: {json.dumps(response, indent=2)}\n")
|
63
|
-
|
64
|
-
# Проверяем команду help без параметров
|
65
|
-
print("2. Команда help без параметров:")
|
66
|
-
response = safe_call_vstl("help", {})
|
67
|
-
print(f"Ответ: {json.dumps(response, indent=2)}")
|
68
|
-
|
69
|
-
# Если команда help сработала, выведем список всех доступных команд
|
70
|
-
if response.get("result") and not response.get("error"):
|
71
|
-
commands_info = response["result"].get("commands", {})
|
72
|
-
print(f"\nДоступные команды ({len(commands_info)}):")
|
73
|
-
for cmd_name, cmd_info in commands_info.items():
|
74
|
-
print(f" - {cmd_name}: {cmd_info.get('summary', 'Нет описания')}")
|
75
|
-
|
76
|
-
# Проверяем команду help с параметром cmdname
|
77
|
-
print("\n3. Команда help с параметром cmdname:")
|
78
|
-
response = safe_call_vstl("help", {"cmdname": "health"})
|
79
|
-
print(f"Ответ: {json.dumps(response, indent=2)}\n")
|
80
|
-
|
81
|
-
# Проверяем команду config
|
82
|
-
print("4. Команда config:")
|
83
|
-
response = safe_call_vstl("config", {"operation": "get"})
|
84
|
-
print(f"Ответ: {json.dumps(response, indent=2)}\n")
|
85
|
-
|
86
|
-
# Выводим рекомендации по полному исправлению
|
87
|
-
print("\n=== Рекомендации по полному исправлению проблемы с null в VSTL ===")
|
88
|
-
print("""
|
89
|
-
1. Проверьте исходный код сервиса VSTL на наличие использования переменной 'null'
|
90
|
-
без её объявления (обратите внимание на файл help_command.py)
|
91
|
-
|
92
|
-
2. Замените все использования JavaScript-стиля null на Python None:
|
93
|
-
- Поиск: if value == null
|
94
|
-
- Замена: if value is None
|
95
|
-
|
96
|
-
3. Обновите сервис до последней версии mcp_proxy_adapter 3.1.6 и перезапустите
|
97
|
-
|
98
|
-
4. Если это невозможно, используйте этот скрипт как промежуточное решение,
|
99
|
-
чтобы безопасно вызывать команды VSTL с корректной обработкой null.
|
100
|
-
|
101
|
-
5. Внесите исправления в метод validate_params, как показано в fix_vstl_help.py
|
102
|
-
""")
|
103
|
-
|
104
|
-
if __name__ == "__main__":
|
105
|
-
test_vstl_commands()
|
@@ -1,108 +0,0 @@
|
|
1
|
-
#!/usr/bin/env python3
|
2
|
-
"""
|
3
|
-
Скрипт для исправления ошибки 'name null is not defined' в сервисе VSTL через MCP Proxy API.
|
4
|
-
|
5
|
-
Этот скрипт демонстрирует как обойти проблему с null в сервисе vstl,
|
6
|
-
используя стандартные средства MCP Proxy API.
|
7
|
-
"""
|
8
|
-
|
9
|
-
import os
|
10
|
-
import sys
|
11
|
-
import json
|
12
|
-
import subprocess
|
13
|
-
from typing import Dict, Any, Optional
|
14
|
-
|
15
|
-
def call_vstl_command(command: str, params: Optional[Dict[str, Any]] = None):
|
16
|
-
"""
|
17
|
-
Вызывает команду vstl через MCP Proxy API.
|
18
|
-
|
19
|
-
Args:
|
20
|
-
command: Название команды
|
21
|
-
params: Параметры команды
|
22
|
-
|
23
|
-
Returns:
|
24
|
-
Результат выполнения команды
|
25
|
-
"""
|
26
|
-
# Формируем параметры для команды mcp_MCP-Proxy_vstl
|
27
|
-
if params is None:
|
28
|
-
params = {}
|
29
|
-
|
30
|
-
# Сериализуем параметры в JSON
|
31
|
-
params_json = json.dumps(params)
|
32
|
-
|
33
|
-
# Формируем команду для вызова MCP Proxy API
|
34
|
-
cmd = [
|
35
|
-
"curl", "-s",
|
36
|
-
"-X", "POST",
|
37
|
-
"-H", "Content-Type: application/json",
|
38
|
-
"-d", f'{{"jsonrpc":"2.0","method":"{command}","params":{params_json},"id":1}}',
|
39
|
-
"http://localhost:8000/api/vstl"
|
40
|
-
]
|
41
|
-
|
42
|
-
# Выполняем команду
|
43
|
-
try:
|
44
|
-
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
45
|
-
# Парсим результат как JSON
|
46
|
-
return json.loads(result.stdout)
|
47
|
-
except subprocess.CalledProcessError as e:
|
48
|
-
print(f"Ошибка выполнения команды: {e}")
|
49
|
-
print(f"STDOUT: {e.stdout}")
|
50
|
-
print(f"STDERR: {e.stderr}")
|
51
|
-
return {"error": str(e)}
|
52
|
-
except json.JSONDecodeError as e:
|
53
|
-
print(f"Ошибка декодирования JSON: {e}")
|
54
|
-
print(f"Ответ: {result.stdout}")
|
55
|
-
return {"error": "Неверный формат JSON в ответе"}
|
56
|
-
|
57
|
-
def test_vstl_commands():
|
58
|
-
"""
|
59
|
-
Тестирует различные команды vstl с обходом проблемы null.
|
60
|
-
"""
|
61
|
-
print("=== Тестирование команд VSTL через MCP Proxy API ===\n")
|
62
|
-
|
63
|
-
# Проверяем команду health
|
64
|
-
print("1. Команда health:")
|
65
|
-
response = call_vstl_command("health", {})
|
66
|
-
print(f"Ответ: {json.dumps(response, indent=2)}\n")
|
67
|
-
|
68
|
-
# Проверяем команду help без параметров
|
69
|
-
print("2. Команда help без параметров:")
|
70
|
-
response = call_vstl_command("help", {})
|
71
|
-
print(f"Ответ: {json.dumps(response, indent=2)}")
|
72
|
-
|
73
|
-
# Если есть ошибка в команде help без параметров, попробуем еще несколько вариантов
|
74
|
-
if "error" in response:
|
75
|
-
print("\n2.1. Попытка обойти ошибку - вызов help с корректными параметрами:")
|
76
|
-
response = call_vstl_command("help", {"cmdname": None})
|
77
|
-
print(f"Ответ: {json.dumps(response, indent=2)}")
|
78
|
-
|
79
|
-
# Проверяем команду help с параметром cmdname
|
80
|
-
print("\n3. Команда help с параметром cmdname:")
|
81
|
-
response = call_vstl_command("help", {"cmdname": "health"})
|
82
|
-
print(f"Ответ: {json.dumps(response, indent=2)}\n")
|
83
|
-
|
84
|
-
# Проверяем команду config
|
85
|
-
print("4. Команда config:")
|
86
|
-
response = call_vstl_command("config", {"operation": "get"})
|
87
|
-
print(f"Ответ: {json.dumps(response, indent=2)}\n")
|
88
|
-
|
89
|
-
# Выводим рекомендации по исправлению
|
90
|
-
print("\n=== Рекомендации по исправлению проблемы с null в VSTL ===")
|
91
|
-
print("""
|
92
|
-
1. Проблема с обработкой null в JavaScript-совместимых API - это распространенная ошибка.
|
93
|
-
В JavaScript null - это ключевое слово, а в Python - это None.
|
94
|
-
|
95
|
-
2. Для полного решения проблемы необходимо исправить реализацию сервиса VSTL:
|
96
|
-
- Найти в коде места, где используется 'null' как переменная
|
97
|
-
- Заменить на корректное использование None
|
98
|
-
- Добавить к аргументам метода execute в help_command.py параметр **kwargs
|
99
|
-
- Обновить метод validate_params для обработки строковых представлений null
|
100
|
-
|
101
|
-
3. До исправления сервера можно использовать следующие обходные пути:
|
102
|
-
- Использовать MCP Proxy API с корректными значениями параметров (None вместо null)
|
103
|
-
- Использовать промежуточный слой, который будет преобразовывать запросы
|
104
|
-
- Избегать отправки параметров null/None в командах, где это возможно
|
105
|
-
""")
|
106
|
-
|
107
|
-
if __name__ == "__main__":
|
108
|
-
test_vstl_commands()
|
examples/server.py
DELETED
@@ -1,69 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Main application module.
|
3
|
-
"""
|
4
|
-
|
5
|
-
import os
|
6
|
-
import sys
|
7
|
-
import uvicorn
|
8
|
-
import logging
|
9
|
-
|
10
|
-
from mcp_proxy_adapter import create_app
|
11
|
-
|
12
|
-
app = create_app()
|
13
|
-
from mcp_proxy_adapter.config import config
|
14
|
-
from mcp_proxy_adapter.core.logging import logger, setup_logging
|
15
|
-
|
16
|
-
|
17
|
-
def main():
|
18
|
-
"""
|
19
|
-
Main function to run the application.
|
20
|
-
"""
|
21
|
-
# Убедимся что логирование настроено
|
22
|
-
logger.info("Initializing logging configuration")
|
23
|
-
|
24
|
-
try:
|
25
|
-
# Получаем настройки логирования
|
26
|
-
log_level = config.get("logging.level", "INFO")
|
27
|
-
log_file = config.get("logging.file")
|
28
|
-
rotation_type = config.get("logging.rotation.type", "size")
|
29
|
-
|
30
|
-
# Выводим информацию о настройках логирования
|
31
|
-
logger.info(f"Log level: {log_level}")
|
32
|
-
if log_file:
|
33
|
-
logger.info(f"Log file: {log_file}")
|
34
|
-
logger.info(f"Log rotation type: {rotation_type}")
|
35
|
-
|
36
|
-
if rotation_type.lower() == "time":
|
37
|
-
when = config.get("logging.rotation.when", "D")
|
38
|
-
interval = config.get("logging.rotation.interval", 1)
|
39
|
-
logger.info(f"Log rotation: every {interval} {when}")
|
40
|
-
else:
|
41
|
-
max_bytes = config.get("logging.rotation.max_bytes", 10 * 1024 * 1024)
|
42
|
-
logger.info(f"Log rotation: when size reaches {max_bytes / (1024*1024):.1f} MB")
|
43
|
-
|
44
|
-
backup_count = config.get("logging.rotation.backup_count", 5)
|
45
|
-
logger.info(f"Log backups: {backup_count}")
|
46
|
-
else:
|
47
|
-
logger.info("File logging is disabled")
|
48
|
-
|
49
|
-
# Get server settings
|
50
|
-
host = config.get("server.host", "0.0.0.0")
|
51
|
-
port = config.get("server.port", 8000)
|
52
|
-
|
53
|
-
logger.info(f"Starting server on {host}:{port}")
|
54
|
-
|
55
|
-
# Run server
|
56
|
-
uvicorn.run(
|
57
|
-
"mcp_proxy_adapter.api.app:app",
|
58
|
-
host=host,
|
59
|
-
port=port,
|
60
|
-
reload=True if os.environ.get("DEBUG") else False,
|
61
|
-
log_level=log_level.lower()
|
62
|
-
)
|
63
|
-
except Exception as e:
|
64
|
-
logger.exception(f"Error during application startup: {e}")
|
65
|
-
sys.exit(1)
|
66
|
-
|
67
|
-
|
68
|
-
if __name__ == "__main__":
|
69
|
-
main()
|
examples/simple_server.py
DELETED
@@ -1,128 +0,0 @@
|
|
1
|
-
#!/usr/bin/env python3
|
2
|
-
"""
|
3
|
-
Простой пример запуска сервера JSON-RPC с использованием MCP Proxy Adapter.
|
4
|
-
|
5
|
-
Этот скрипт демонстрирует минимальную конфигурацию для запуска сервера JSON-RPC.
|
6
|
-
Он создаёт экземпляр приложения FastAPI с MCP Proxy Adapter и регистрирует пользовательские команды.
|
7
|
-
"""
|
8
|
-
|
9
|
-
import os
|
10
|
-
import argparse
|
11
|
-
import sys
|
12
|
-
from pathlib import Path
|
13
|
-
import uvicorn
|
14
|
-
|
15
|
-
# Добавляем родительскую директорию в PYTHONPATH для импорта mcp_proxy_adapter
|
16
|
-
sys.path.insert(0, str(Path(__file__).parent.parent))
|
17
|
-
|
18
|
-
from mcp_proxy_adapter import Command, SuccessResult, create_app
|
19
|
-
from mcp_proxy_adapter.commands.command_registry import registry
|
20
|
-
from typing import Dict, Any, Optional
|
21
|
-
|
22
|
-
|
23
|
-
class HelloResult(SuccessResult):
|
24
|
-
"""Result of hello command."""
|
25
|
-
|
26
|
-
def __init__(self, message: str):
|
27
|
-
"""
|
28
|
-
Initialize result.
|
29
|
-
|
30
|
-
Args:
|
31
|
-
message: Hello message
|
32
|
-
"""
|
33
|
-
self.message = message
|
34
|
-
|
35
|
-
def to_dict(self) -> Dict[str, Any]:
|
36
|
-
"""
|
37
|
-
Convert result to dictionary.
|
38
|
-
|
39
|
-
Returns:
|
40
|
-
Dictionary representation
|
41
|
-
"""
|
42
|
-
return {"message": self.message}
|
43
|
-
|
44
|
-
@classmethod
|
45
|
-
def get_schema(cls) -> Dict[str, Any]:
|
46
|
-
"""
|
47
|
-
Get JSON schema for result.
|
48
|
-
|
49
|
-
Returns:
|
50
|
-
JSON schema
|
51
|
-
"""
|
52
|
-
return {
|
53
|
-
"type": "object",
|
54
|
-
"properties": {
|
55
|
-
"message": {"type": "string"}
|
56
|
-
},
|
57
|
-
"required": ["message"]
|
58
|
-
}
|
59
|
-
|
60
|
-
|
61
|
-
class HelloCommand(Command):
|
62
|
-
"""Command that returns hello message."""
|
63
|
-
|
64
|
-
name = "hello"
|
65
|
-
result_class = HelloResult
|
66
|
-
|
67
|
-
async def execute(self, name: str = "World") -> HelloResult:
|
68
|
-
"""
|
69
|
-
Execute command.
|
70
|
-
|
71
|
-
Args:
|
72
|
-
name: Name to greet
|
73
|
-
|
74
|
-
Returns:
|
75
|
-
Hello result
|
76
|
-
"""
|
77
|
-
return HelloResult(f"Hello, {name}!")
|
78
|
-
|
79
|
-
@classmethod
|
80
|
-
def get_schema(cls) -> Dict[str, Any]:
|
81
|
-
"""
|
82
|
-
Get JSON schema for command parameters.
|
83
|
-
|
84
|
-
Returns:
|
85
|
-
JSON schema
|
86
|
-
"""
|
87
|
-
return {
|
88
|
-
"type": "object",
|
89
|
-
"properties": {
|
90
|
-
"name": {"type": "string"}
|
91
|
-
},
|
92
|
-
"additionalProperties": False
|
93
|
-
}
|
94
|
-
|
95
|
-
|
96
|
-
def main():
|
97
|
-
"""
|
98
|
-
Основная функция для запуска сервера.
|
99
|
-
"""
|
100
|
-
parser = argparse.ArgumentParser(description="JSON-RPC Microservice Server")
|
101
|
-
parser.add_argument("--host", default="0.0.0.0", help="Host to bind server")
|
102
|
-
parser.add_argument("--port", type=int, default=8000, help="Port to bind server")
|
103
|
-
parser.add_argument("--reload", action="store_true", help="Enable auto-reload")
|
104
|
-
|
105
|
-
args = parser.parse_args()
|
106
|
-
|
107
|
-
# Регистрируем только свою пользовательскую команду
|
108
|
-
# встроенные команды и примеры регистрируются автоматически
|
109
|
-
registry.register(HelloCommand)
|
110
|
-
|
111
|
-
# Создаем приложение FastAPI
|
112
|
-
app = create_app()
|
113
|
-
|
114
|
-
# Запускаем сервер
|
115
|
-
uvicorn.run(
|
116
|
-
app,
|
117
|
-
host=args.host,
|
118
|
-
port=args.port,
|
119
|
-
reload=args.reload
|
120
|
-
)
|
121
|
-
|
122
|
-
|
123
|
-
if __name__ == "__main__":
|
124
|
-
# Run the simple server example
|
125
|
-
# To test, open http://localhost:8000/docs in your browser
|
126
|
-
# or use curl:
|
127
|
-
# curl -X POST http://localhost:8000/api/cmd -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"hello","params":{"name":"PyPI"},"id":1}'
|
128
|
-
main()
|