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.
Files changed (118) hide show
  1. mcp_proxy_adapter/api/app.py +65 -27
  2. mcp_proxy_adapter/api/handlers.py +1 -1
  3. mcp_proxy_adapter/api/middleware/error_handling.py +11 -10
  4. mcp_proxy_adapter/api/tool_integration.py +5 -2
  5. mcp_proxy_adapter/api/tools.py +3 -3
  6. mcp_proxy_adapter/commands/base.py +19 -1
  7. mcp_proxy_adapter/commands/command_registry.py +254 -8
  8. mcp_proxy_adapter/commands/hooks.py +260 -0
  9. mcp_proxy_adapter/commands/reload_command.py +211 -0
  10. mcp_proxy_adapter/commands/reload_settings_command.py +125 -0
  11. mcp_proxy_adapter/commands/settings_command.py +189 -0
  12. mcp_proxy_adapter/config.py +16 -1
  13. mcp_proxy_adapter/core/__init__.py +44 -0
  14. mcp_proxy_adapter/core/logging.py +87 -34
  15. mcp_proxy_adapter/core/settings.py +376 -0
  16. mcp_proxy_adapter/core/utils.py +2 -2
  17. mcp_proxy_adapter/custom_openapi.py +81 -2
  18. mcp_proxy_adapter/examples/README.md +124 -0
  19. mcp_proxy_adapter/examples/__init__.py +7 -0
  20. mcp_proxy_adapter/examples/basic_server/README.md +60 -0
  21. mcp_proxy_adapter/examples/basic_server/__init__.py +7 -0
  22. mcp_proxy_adapter/examples/basic_server/basic_custom_settings.json +39 -0
  23. mcp_proxy_adapter/examples/basic_server/config.json +35 -0
  24. mcp_proxy_adapter/examples/basic_server/custom_settings_example.py +238 -0
  25. mcp_proxy_adapter/examples/basic_server/server.py +98 -0
  26. mcp_proxy_adapter/examples/custom_commands/README.md +127 -0
  27. mcp_proxy_adapter/examples/custom_commands/__init__.py +27 -0
  28. mcp_proxy_adapter/examples/custom_commands/advanced_hooks.py +250 -0
  29. mcp_proxy_adapter/examples/custom_commands/auto_commands/__init__.py +6 -0
  30. mcp_proxy_adapter/examples/custom_commands/auto_commands/auto_echo_command.py +103 -0
  31. mcp_proxy_adapter/examples/custom_commands/auto_commands/auto_info_command.py +111 -0
  32. mcp_proxy_adapter/examples/custom_commands/config.json +62 -0
  33. mcp_proxy_adapter/examples/custom_commands/custom_health_command.py +169 -0
  34. mcp_proxy_adapter/examples/custom_commands/custom_help_command.py +215 -0
  35. mcp_proxy_adapter/examples/custom_commands/custom_openapi_generator.py +76 -0
  36. mcp_proxy_adapter/examples/custom_commands/custom_settings.json +96 -0
  37. mcp_proxy_adapter/examples/custom_commands/custom_settings_manager.py +241 -0
  38. mcp_proxy_adapter/examples/custom_commands/data_transform_command.py +135 -0
  39. mcp_proxy_adapter/examples/custom_commands/echo_command.py +122 -0
  40. mcp_proxy_adapter/examples/custom_commands/hooks.py +230 -0
  41. mcp_proxy_adapter/examples/custom_commands/intercept_command.py +123 -0
  42. mcp_proxy_adapter/examples/custom_commands/manual_echo_command.py +103 -0
  43. mcp_proxy_adapter/examples/custom_commands/server.py +223 -0
  44. mcp_proxy_adapter/examples/custom_commands/test_hooks.py +176 -0
  45. mcp_proxy_adapter/examples/deployment/README.md +49 -0
  46. mcp_proxy_adapter/examples/deployment/__init__.py +7 -0
  47. mcp_proxy_adapter/examples/deployment/config.development.json +8 -0
  48. {examples/basic_example → mcp_proxy_adapter/examples/deployment}/config.json +11 -7
  49. mcp_proxy_adapter/examples/deployment/config.production.json +12 -0
  50. mcp_proxy_adapter/examples/deployment/config.staging.json +11 -0
  51. mcp_proxy_adapter/examples/deployment/docker-compose.yml +31 -0
  52. mcp_proxy_adapter/examples/deployment/run.sh +43 -0
  53. mcp_proxy_adapter/examples/deployment/run_docker.sh +84 -0
  54. mcp_proxy_adapter/openapi.py +3 -2
  55. mcp_proxy_adapter/tests/api/test_custom_openapi.py +617 -0
  56. mcp_proxy_adapter/tests/api/test_handlers.py +522 -0
  57. mcp_proxy_adapter/tests/api/test_schemas.py +546 -0
  58. mcp_proxy_adapter/tests/api/test_tool_integration.py +531 -0
  59. mcp_proxy_adapter/tests/unit/test_base_command.py +391 -85
  60. mcp_proxy_adapter/version.py +1 -1
  61. {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/METADATA +3 -3
  62. mcp_proxy_adapter-4.1.0.dist-info/RECORD +110 -0
  63. {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/WHEEL +1 -1
  64. {mcp_proxy_adapter-3.1.6.dist-info → mcp_proxy_adapter-4.1.0.dist-info}/top_level.txt +0 -1
  65. examples/__init__.py +0 -19
  66. examples/anti_patterns/README.md +0 -51
  67. examples/anti_patterns/__init__.py +0 -9
  68. examples/anti_patterns/bad_design/README.md +0 -72
  69. examples/anti_patterns/bad_design/global_state.py +0 -170
  70. examples/anti_patterns/bad_design/monolithic_command.py +0 -272
  71. examples/basic_example/README.md +0 -245
  72. examples/basic_example/__init__.py +0 -8
  73. examples/basic_example/commands/__init__.py +0 -5
  74. examples/basic_example/commands/echo_command.py +0 -95
  75. examples/basic_example/commands/math_command.py +0 -151
  76. examples/basic_example/commands/time_command.py +0 -152
  77. examples/basic_example/docs/EN/README.md +0 -177
  78. examples/basic_example/docs/RU/README.md +0 -177
  79. examples/basic_example/server.py +0 -151
  80. examples/basic_example/tests/conftest.py +0 -243
  81. examples/check_vstl_schema.py +0 -106
  82. examples/commands/echo_command.py +0 -52
  83. examples/commands/echo_command_di.py +0 -152
  84. examples/commands/echo_result.py +0 -65
  85. examples/commands/get_date_command.py +0 -98
  86. examples/commands/new_uuid4_command.py +0 -91
  87. examples/complete_example/Dockerfile +0 -24
  88. examples/complete_example/README.md +0 -92
  89. examples/complete_example/__init__.py +0 -8
  90. examples/complete_example/commands/__init__.py +0 -5
  91. examples/complete_example/commands/system_command.py +0 -328
  92. examples/complete_example/config.json +0 -41
  93. examples/complete_example/configs/config.dev.yaml +0 -40
  94. examples/complete_example/configs/config.docker.yaml +0 -40
  95. examples/complete_example/docker-compose.yml +0 -35
  96. examples/complete_example/requirements.txt +0 -20
  97. examples/complete_example/server.py +0 -113
  98. examples/di_example/.pytest_cache/README.md +0 -8
  99. examples/di_example/server.py +0 -249
  100. examples/fix_vstl_help.py +0 -123
  101. examples/minimal_example/README.md +0 -65
  102. examples/minimal_example/__init__.py +0 -8
  103. examples/minimal_example/config.json +0 -14
  104. examples/minimal_example/main.py +0 -136
  105. examples/minimal_example/simple_server.py +0 -163
  106. examples/minimal_example/tests/conftest.py +0 -171
  107. examples/minimal_example/tests/test_hello_command.py +0 -111
  108. examples/minimal_example/tests/test_integration.py +0 -181
  109. examples/patch_vstl_service.py +0 -105
  110. examples/patch_vstl_service_mcp.py +0 -108
  111. examples/server.py +0 -69
  112. examples/simple_server.py +0 -128
  113. examples/test_package_3.1.4.py +0 -177
  114. examples/test_server.py +0 -134
  115. examples/tool_description_example.py +0 -82
  116. mcp_proxy_adapter/py.typed +0 -0
  117. mcp_proxy_adapter-3.1.6.dist-info/RECORD +0 -118
  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"
@@ -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()