mcp-proxy-adapter 2.1.16__py3-none-any.whl → 3.0.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 (84) hide show
  1. examples/__init__.py +19 -0
  2. examples/anti_patterns/README.md +51 -0
  3. examples/anti_patterns/__init__.py +9 -0
  4. examples/anti_patterns/bad_design/README.md +72 -0
  5. examples/anti_patterns/bad_design/global_state.py +170 -0
  6. examples/anti_patterns/bad_design/monolithic_command.py +272 -0
  7. examples/basic_example/README.md +131 -0
  8. examples/basic_example/__init__.py +8 -0
  9. examples/basic_example/commands/__init__.py +5 -0
  10. examples/basic_example/commands/echo_command.py +95 -0
  11. examples/basic_example/commands/math_command.py +151 -0
  12. examples/basic_example/commands/time_command.py +152 -0
  13. examples/basic_example/config.json +21 -0
  14. examples/basic_example/config.yaml +20 -0
  15. examples/basic_example/docs/EN/README.md +136 -0
  16. examples/basic_example/docs/RU/README.md +136 -0
  17. examples/basic_example/main.py +50 -0
  18. examples/basic_example/server.py +45 -0
  19. examples/basic_example/tests/conftest.py +243 -0
  20. examples/commands/echo_command.py +52 -0
  21. examples/commands/echo_result.py +65 -0
  22. examples/commands/get_date_command.py +98 -0
  23. examples/commands/new_uuid4_command.py +91 -0
  24. examples/complete_example/Dockerfile +24 -0
  25. examples/complete_example/README.md +92 -0
  26. examples/complete_example/__init__.py +8 -0
  27. examples/complete_example/commands/__init__.py +5 -0
  28. examples/complete_example/commands/system_command.py +327 -0
  29. examples/complete_example/config.json +41 -0
  30. examples/complete_example/configs/config.dev.yaml +40 -0
  31. examples/complete_example/configs/config.docker.yaml +40 -0
  32. examples/complete_example/docker-compose.yml +35 -0
  33. examples/complete_example/main.py +67 -0
  34. examples/complete_example/requirements.txt +20 -0
  35. examples/complete_example/server.py +85 -0
  36. examples/minimal_example/README.md +51 -0
  37. examples/minimal_example/__init__.py +8 -0
  38. examples/minimal_example/config.json +21 -0
  39. examples/minimal_example/config.yaml +26 -0
  40. examples/minimal_example/main.py +67 -0
  41. examples/minimal_example/simple_server.py +124 -0
  42. examples/minimal_example/tests/conftest.py +171 -0
  43. examples/minimal_example/tests/test_hello_command.py +111 -0
  44. examples/minimal_example/tests/test_integration.py +183 -0
  45. examples/server.py +69 -0
  46. examples/simple_server.py +137 -0
  47. examples/test_server.py +126 -0
  48. mcp_proxy_adapter/__init__.py +33 -1
  49. mcp_proxy_adapter/config.py +186 -0
  50. mcp_proxy_adapter/custom_openapi.py +125 -0
  51. mcp_proxy_adapter/framework.py +109 -0
  52. mcp_proxy_adapter/openapi.py +403 -0
  53. mcp_proxy_adapter/version.py +3 -0
  54. mcp_proxy_adapter-3.0.0.dist-info/METADATA +200 -0
  55. mcp_proxy_adapter-3.0.0.dist-info/RECORD +58 -0
  56. {mcp_proxy_adapter-2.1.16.dist-info → mcp_proxy_adapter-3.0.0.dist-info}/top_level.txt +1 -0
  57. mcp_proxy_adapter/adapter.py +0 -697
  58. mcp_proxy_adapter/analyzers/__init__.py +0 -1
  59. mcp_proxy_adapter/analyzers/docstring_analyzer.py +0 -199
  60. mcp_proxy_adapter/analyzers/type_analyzer.py +0 -151
  61. mcp_proxy_adapter/dispatchers/__init__.py +0 -1
  62. mcp_proxy_adapter/dispatchers/base_dispatcher.py +0 -85
  63. mcp_proxy_adapter/dispatchers/json_rpc_dispatcher.py +0 -235
  64. mcp_proxy_adapter/examples/analyze_config.py +0 -141
  65. mcp_proxy_adapter/examples/basic_integration.py +0 -155
  66. mcp_proxy_adapter/examples/docstring_and_schema_example.py +0 -69
  67. mcp_proxy_adapter/examples/extension_example.py +0 -72
  68. mcp_proxy_adapter/examples/help_best_practices.py +0 -67
  69. mcp_proxy_adapter/examples/help_usage.py +0 -64
  70. mcp_proxy_adapter/examples/mcp_proxy_client.py +0 -131
  71. mcp_proxy_adapter/examples/openapi_server.py +0 -383
  72. mcp_proxy_adapter/examples/project_structure_example.py +0 -47
  73. mcp_proxy_adapter/examples/testing_example.py +0 -64
  74. mcp_proxy_adapter/models.py +0 -47
  75. mcp_proxy_adapter/registry.py +0 -439
  76. mcp_proxy_adapter/schema.py +0 -257
  77. mcp_proxy_adapter/testing_utils.py +0 -112
  78. mcp_proxy_adapter/validators/__init__.py +0 -1
  79. mcp_proxy_adapter/validators/docstring_validator.py +0 -75
  80. mcp_proxy_adapter/validators/metadata_validator.py +0 -76
  81. mcp_proxy_adapter-2.1.16.dist-info/METADATA +0 -341
  82. mcp_proxy_adapter-2.1.16.dist-info/RECORD +0 -30
  83. {mcp_proxy_adapter-2.1.16.dist-info → mcp_proxy_adapter-3.0.0.dist-info}/WHEEL +0 -0
  84. {mcp_proxy_adapter-2.1.16.dist-info → mcp_proxy_adapter-3.0.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,131 @@
1
+ # Базовый пример MCP Microservice
2
+
3
+ Этот пример демонстрирует базовую функциональность MCP Microservice с несколькими командами,
4
+ организованными в отдельные файлы.
5
+
6
+ ## Структура примера
7
+
8
+ ```
9
+ basic_example/
10
+ ├── commands/ # Директория с командами
11
+ │ ├── __init__.py # Инициализация пакета команд
12
+ │ ├── echo_command.py # Команда эхо
13
+ │ ├── math_command.py # Математическая команда
14
+ │ └── time_command.py # Команда времени
15
+ ├── config.yaml # Файл конфигурации
16
+ ├── README.md # Документация
17
+ └── server.py # Файл запуска сервера
18
+ ```
19
+
20
+ ## Запуск примера
21
+
22
+ ```bash
23
+ # Перейти в директорию проекта
24
+ cd examples/basic_example
25
+
26
+ # Создать директорию для логов, если она не существует
27
+ mkdir -p logs
28
+
29
+ # Запустить сервер
30
+ python server.py
31
+ ```
32
+
33
+ После запуска сервер будет доступен по адресу [http://localhost:8000](http://localhost:8000).
34
+
35
+ ## Доступные команды
36
+
37
+ ### 1. `echo` - Эхо-команда
38
+
39
+ Возвращает переданное сообщение.
40
+
41
+ **Параметры:**
42
+ - `message` (string) - Сообщение для эхо
43
+
44
+ **Пример запроса:**
45
+ ```json
46
+ {
47
+ "jsonrpc": "2.0",
48
+ "method": "echo",
49
+ "params": {
50
+ "message": "Hello, World!"
51
+ },
52
+ "id": 1
53
+ }
54
+ ```
55
+
56
+ ### 2. `math` - Математическая команда
57
+
58
+ Выполняет математическую операцию над двумя числами.
59
+
60
+ **Параметры:**
61
+ - `a` (number) - Первое число
62
+ - `b` (number) - Второе число
63
+ - `operation` (string) - Операция (add, subtract, multiply, divide)
64
+
65
+ **Пример запроса:**
66
+ ```json
67
+ {
68
+ "jsonrpc": "2.0",
69
+ "method": "math",
70
+ "params": {
71
+ "a": 10,
72
+ "b": 5,
73
+ "operation": "add"
74
+ },
75
+ "id": 1
76
+ }
77
+ ```
78
+
79
+ ### 3. `time` - Команда времени
80
+
81
+ Возвращает текущее время и дату.
82
+
83
+ **Параметры:**
84
+ - `format` (string, optional) - Формат времени (default: "%Y-%m-%d %H:%M:%S")
85
+ - `timezone` (string, optional) - Часовой пояс (default: "UTC")
86
+
87
+ **Пример запроса:**
88
+ ```json
89
+ {
90
+ "jsonrpc": "2.0",
91
+ "method": "time",
92
+ "params": {
93
+ "format": "%d.%m.%Y %H:%M:%S",
94
+ "timezone": "Europe/Moscow"
95
+ },
96
+ "id": 1
97
+ }
98
+ ```
99
+
100
+ ## Тестирование API
101
+
102
+ ### Через веб-интерфейс
103
+
104
+ Откройте в браузере [http://localhost:8000/docs](http://localhost:8000/docs) для доступа к интерактивной документации Swagger UI.
105
+
106
+ ### Через командную строку
107
+
108
+ ```bash
109
+ # Вызов команды echo через JSON-RPC
110
+ curl -X POST "http://localhost:8000/api/jsonrpc" \
111
+ -H "Content-Type: application/json" \
112
+ -d '{"jsonrpc": "2.0", "method": "echo", "params": {"message": "Hello!"}, "id": 1}'
113
+
114
+ # Вызов команды math через упрощенный эндпоинт
115
+ curl -X POST "http://localhost:8000/cmd" \
116
+ -H "Content-Type: application/json" \
117
+ -d '{"command": "math", "params": {"a": 10, "b": 5, "operation": "add"}}'
118
+
119
+ # Вызов команды time через endpoint /api/command/{command_name}
120
+ curl -X POST "http://localhost:8000/api/command/time" \
121
+ -H "Content-Type: application/json" \
122
+ -d '{"format": "%d.%m.%Y %H:%M:%S", "timezone": "UTC"}'
123
+ ```
124
+
125
+ ## Что демонстрирует этот пример
126
+
127
+ 1. Организация команд в отдельные файлы
128
+ 2. Автоматическое обнаружение и регистрация команд
129
+ 3. Различные типы команд и параметров
130
+ 4. Обработка ошибок
131
+ 5. Различные способы вызова команд (JSON-RPC, /cmd, /api/command/{command_name})
@@ -0,0 +1,8 @@
1
+ """
2
+ Basic example for MCP Microservice.
3
+
4
+ This package contains a basic example of using MCP Microservice framework
5
+ with several commands, separate command files, and tests.
6
+ """
7
+
8
+ __all__ = []
@@ -0,0 +1,5 @@
1
+ """
2
+ Command package for basic example.
3
+
4
+ This package contains all commands for the basic microservice example.
5
+ """
@@ -0,0 +1,95 @@
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
+ }
@@ -0,0 +1,151 @@
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
+ }
@@ -0,0 +1,152 @@
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
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "service": {
3
+ "name": "Basic Example",
4
+ "version": "1.0.0"
5
+ },
6
+ "server": {
7
+ "host": "0.0.0.0",
8
+ "port": 8000,
9
+ "debug": true,
10
+ "log_level": "info"
11
+ },
12
+ "logging": {
13
+ "level": "INFO",
14
+ "file": "logs/basic_example.log",
15
+ "rotation": {
16
+ "type": "size",
17
+ "max_bytes": 10485760,
18
+ "backup_count": 5
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,20 @@
1
+ # Configuration for basic MCP Microservice example
2
+
3
+ # Server settings
4
+ server:
5
+ host: "localhost" # Host to bind server
6
+ port: 8000 # Port to bind server
7
+
8
+ # Logging settings
9
+ logging:
10
+ level: "INFO" # Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
11
+ file: "logs/basic_example.log" # Log file path
12
+ rotation:
13
+ type: "size" # Log rotation type (size, time)
14
+ max_bytes: 10485760 # Maximum log file size (10 MB)
15
+ backup_count: 5 # Number of backup files
16
+
17
+ # Command discovery settings
18
+ discovery:
19
+ enabled: true
20
+ package: "commands" # Package to discover commands