universal-mcp 0.1.16__py3-none-any.whl → 0.1.18__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.
- universal_mcp/applications/__init__.py +6 -1
- universal_mcp/applications/application.py +106 -16
- universal_mcp/cli.py +44 -4
- universal_mcp/config.py +4 -5
- universal_mcp/exceptions.py +4 -0
- universal_mcp/integrations/__init__.py +1 -1
- universal_mcp/integrations/integration.py +9 -9
- universal_mcp/servers/__init__.py +2 -2
- universal_mcp/servers/server.py +125 -54
- universal_mcp/tools/manager.py +24 -10
- universal_mcp/utils/agentr.py +10 -14
- universal_mcp/utils/installation.py +1 -1
- universal_mcp/utils/openapi/api_splitter.py +400 -0
- universal_mcp/utils/openapi/openapi.py +299 -116
- {universal_mcp-0.1.16.dist-info → universal_mcp-0.1.18.dist-info}/METADATA +2 -2
- {universal_mcp-0.1.16.dist-info → universal_mcp-0.1.18.dist-info}/RECORD +19 -18
- {universal_mcp-0.1.16.dist-info → universal_mcp-0.1.18.dist-info}/WHEEL +0 -0
- {universal_mcp-0.1.16.dist-info → universal_mcp-0.1.18.dist-info}/entry_points.txt +0 -0
- {universal_mcp-0.1.16.dist-info → universal_mcp-0.1.18.dist-info}/licenses/LICENSE +0 -0
universal_mcp/servers/server.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1
|
-
from abc import ABC, abstractmethod
|
2
1
|
from collections.abc import Callable
|
3
2
|
from typing import Any
|
4
3
|
|
@@ -6,16 +5,18 @@ import httpx
|
|
6
5
|
from loguru import logger
|
7
6
|
from mcp.server.fastmcp import FastMCP
|
8
7
|
from mcp.types import TextContent
|
8
|
+
from pydantic import ValidationError
|
9
9
|
|
10
10
|
from universal_mcp.applications import BaseApplication, app_from_slug
|
11
11
|
from universal_mcp.config import AppConfig, ServerConfig, StoreConfig
|
12
|
+
from universal_mcp.exceptions import ConfigurationError, ToolError
|
12
13
|
from universal_mcp.integrations import AgentRIntegration, integration_from_config
|
13
14
|
from universal_mcp.stores import BaseStore, store_from_config
|
14
15
|
from universal_mcp.tools import ToolManager
|
15
16
|
from universal_mcp.utils.agentr import AgentrClient
|
16
17
|
|
17
18
|
|
18
|
-
class BaseServer(FastMCP
|
19
|
+
class BaseServer(FastMCP):
|
19
20
|
"""Base server class with common functionality.
|
20
21
|
|
21
22
|
This class provides core server functionality including store setup,
|
@@ -26,24 +27,27 @@ class BaseServer(FastMCP, ABC):
|
|
26
27
|
**kwargs: Additional keyword arguments passed to FastMCP
|
27
28
|
"""
|
28
29
|
|
29
|
-
def __init__(self, config: ServerConfig, **kwargs):
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
pass
|
30
|
+
def __init__(self, config: ServerConfig, tool_manager: ToolManager | None = None, **kwargs):
|
31
|
+
try:
|
32
|
+
super().__init__(config.name, config.description, port=config.port, **kwargs)
|
33
|
+
logger.info(f"Initializing server: {config.name} ({config.type}) with store: {config.store}")
|
34
|
+
self.config = config
|
35
|
+
self._tool_manager = tool_manager or ToolManager(warn_on_duplicate_tools=True)
|
36
|
+
ServerConfig.model_validate(config)
|
37
|
+
except Exception as e:
|
38
|
+
logger.error(f"Failed to initialize server: {e}", exc_info=True)
|
39
|
+
raise ConfigurationError(f"Server initialization failed: {str(e)}") from e
|
40
40
|
|
41
41
|
def add_tool(self, tool: Callable) -> None:
|
42
42
|
"""Add a tool to the server.
|
43
43
|
|
44
44
|
Args:
|
45
45
|
tool: Tool to add
|
46
|
+
|
47
|
+
Raises:
|
48
|
+
ValueError: If tool is invalid
|
46
49
|
"""
|
50
|
+
|
47
51
|
self._tool_manager.add_tool(tool)
|
48
52
|
|
49
53
|
async def list_tools(self) -> list[dict]:
|
@@ -83,11 +87,21 @@ class BaseServer(FastMCP, ABC):
|
|
83
87
|
|
84
88
|
Raises:
|
85
89
|
ToolError: If tool execution fails
|
90
|
+
ValueError: If tool name is invalid or arguments are malformed
|
86
91
|
"""
|
92
|
+
if not name:
|
93
|
+
raise ValueError("Tool name is required")
|
94
|
+
if not isinstance(arguments, dict):
|
95
|
+
raise ValueError("Arguments must be a dictionary")
|
96
|
+
|
87
97
|
logger.info(f"Calling tool: {name} with arguments: {arguments}")
|
88
|
-
|
89
|
-
|
90
|
-
|
98
|
+
try:
|
99
|
+
result = await self._tool_manager.call_tool(name, arguments)
|
100
|
+
logger.info(f"Tool '{name}' completed successfully")
|
101
|
+
return self._format_tool_result(result)
|
102
|
+
except Exception as e:
|
103
|
+
logger.error(f"Tool '{name}' failed: {e}", exc_info=True)
|
104
|
+
raise ToolError(f"Tool execution failed: {str(e)}") from e
|
91
105
|
|
92
106
|
|
93
107
|
class LocalServer(BaseServer):
|
@@ -111,14 +125,23 @@ class LocalServer(BaseServer):
|
|
111
125
|
|
112
126
|
Returns:
|
113
127
|
Configured store instance or None if no config provided
|
128
|
+
|
129
|
+
Raises:
|
130
|
+
ConfigurationError: If store configuration is invalid
|
114
131
|
"""
|
115
132
|
if not store_config:
|
133
|
+
logger.info("No store configuration provided")
|
116
134
|
return None
|
117
135
|
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
136
|
+
try:
|
137
|
+
store = store_from_config(store_config)
|
138
|
+
self.add_tool(store.set)
|
139
|
+
self.add_tool(store.delete)
|
140
|
+
logger.info(f"Successfully configured store: {store_config.type}")
|
141
|
+
return store
|
142
|
+
except Exception as e:
|
143
|
+
logger.error(f"Failed to setup store: {e}", exc_info=True)
|
144
|
+
raise ConfigurationError(f"Store setup failed: {str(e)}") from e
|
122
145
|
|
123
146
|
def _load_app(self, app_config: AppConfig) -> BaseApplication | None:
|
124
147
|
"""Load a single application with its integration.
|
@@ -129,22 +152,57 @@ class LocalServer(BaseServer):
|
|
129
152
|
Returns:
|
130
153
|
Configured application instance or None if loading fails
|
131
154
|
"""
|
155
|
+
if not app_config.name:
|
156
|
+
logger.error("App configuration missing name")
|
157
|
+
return None
|
158
|
+
|
132
159
|
try:
|
133
|
-
integration =
|
134
|
-
|
135
|
-
|
136
|
-
|
160
|
+
integration = None
|
161
|
+
if app_config.integration:
|
162
|
+
try:
|
163
|
+
integration = integration_from_config(app_config.integration, store=self.store)
|
164
|
+
logger.debug(f"Successfully configured integration for {app_config.name}")
|
165
|
+
except Exception as e:
|
166
|
+
logger.error(f"Failed to setup integration for {app_config.name}: {e}", exc_info=True)
|
167
|
+
# Continue without integration if it fails
|
168
|
+
|
169
|
+
app = app_from_slug(app_config.name)(integration=integration)
|
170
|
+
logger.info(f"Successfully loaded app: {app_config.name}")
|
171
|
+
return app
|
137
172
|
except Exception as e:
|
138
173
|
logger.error(f"Failed to load app {app_config.name}: {e}", exc_info=True)
|
139
174
|
return None
|
140
175
|
|
141
176
|
def _load_apps(self) -> None:
|
142
|
-
"""Load all configured applications."""
|
143
|
-
|
177
|
+
"""Load all configured applications with graceful degradation."""
|
178
|
+
if not self.config.apps:
|
179
|
+
logger.warning("No applications configured")
|
180
|
+
return
|
181
|
+
|
182
|
+
logger.info(f"Loading {len(self.config.apps)} apps")
|
183
|
+
loaded_apps = 0
|
184
|
+
failed_apps = []
|
185
|
+
|
144
186
|
for app_config in self.config.apps:
|
145
187
|
app = self._load_app(app_config)
|
146
188
|
if app:
|
147
|
-
|
189
|
+
try:
|
190
|
+
self._tool_manager.register_tools_from_app(app, app_config.actions)
|
191
|
+
loaded_apps += 1
|
192
|
+
logger.info(f"Successfully registered tools for {app_config.name}")
|
193
|
+
except Exception as e:
|
194
|
+
logger.error(f"Failed to register tools for {app_config.name}: {e}", exc_info=True)
|
195
|
+
failed_apps.append(app_config.name)
|
196
|
+
else:
|
197
|
+
failed_apps.append(app_config.name)
|
198
|
+
|
199
|
+
if failed_apps:
|
200
|
+
logger.warning(f"Failed to load {len(failed_apps)} apps: {', '.join(failed_apps)}")
|
201
|
+
|
202
|
+
if loaded_apps == 0:
|
203
|
+
logger.error("No apps were successfully loaded")
|
204
|
+
else:
|
205
|
+
logger.info(f"Successfully loaded {loaded_apps}/{len(self.config.apps)} apps")
|
148
206
|
|
149
207
|
|
150
208
|
class AgentRServer(BaseServer):
|
@@ -154,27 +212,38 @@ class AgentRServer(BaseServer):
|
|
154
212
|
config: Server configuration
|
155
213
|
api_key: Optional API key for AgentR authentication. If not provided,
|
156
214
|
will attempt to read from AGENTR_API_KEY environment variable.
|
215
|
+
max_retries: Maximum number of retries for API calls (default: 3)
|
216
|
+
retry_delay: Delay between retries in seconds (default: 1)
|
157
217
|
**kwargs: Additional keyword arguments passed to FastMCP
|
158
218
|
"""
|
159
219
|
|
160
220
|
def __init__(self, config: ServerConfig, api_key: str | None = None, **kwargs):
|
161
|
-
self.
|
221
|
+
self.api_key = api_key or str(config.api_key)
|
222
|
+
self.client = AgentrClient(api_key=self.api_key)
|
162
223
|
super().__init__(config, **kwargs)
|
163
224
|
self.integration = AgentRIntegration(name="agentr", api_key=self.client.api_key)
|
164
225
|
self._load_apps()
|
165
226
|
|
166
227
|
def _fetch_apps(self) -> list[AppConfig]:
|
167
|
-
"""Fetch available apps from AgentR API.
|
228
|
+
"""Fetch available apps from AgentR API with retry logic.
|
168
229
|
|
169
230
|
Returns:
|
170
231
|
List of application configurations
|
171
232
|
|
172
233
|
Raises:
|
173
|
-
httpx.HTTPError: If API request fails
|
234
|
+
httpx.HTTPError: If API request fails after all retries
|
235
|
+
ValidationError: If app configuration validation fails
|
174
236
|
"""
|
175
237
|
try:
|
176
238
|
apps = self.client.fetch_apps()
|
177
|
-
|
239
|
+
validated_apps = []
|
240
|
+
for app in apps:
|
241
|
+
try:
|
242
|
+
validated_apps.append(AppConfig.model_validate(app))
|
243
|
+
except ValidationError as e:
|
244
|
+
logger.error(f"Failed to validate app config: {e}", exc_info=True)
|
245
|
+
continue
|
246
|
+
return validated_apps
|
178
247
|
except httpx.HTTPError as e:
|
179
248
|
logger.error(f"Failed to fetch apps from AgentR: {e}", exc_info=True)
|
180
249
|
raise
|
@@ -194,21 +263,37 @@ class AgentRServer(BaseServer):
|
|
194
263
|
if app_config.integration
|
195
264
|
else None
|
196
265
|
)
|
197
|
-
|
266
|
+
app = app_from_slug(app_config.name)(integration=integration)
|
267
|
+
logger.info(f"Successfully loaded app: {app_config.name}")
|
268
|
+
return app
|
198
269
|
except Exception as e:
|
199
270
|
logger.error(f"Failed to load app {app_config.name}: {e}", exc_info=True)
|
200
271
|
return None
|
201
272
|
|
202
273
|
def _load_apps(self) -> None:
|
203
|
-
"""Load all apps available from AgentR."""
|
274
|
+
"""Load all apps available from AgentR with graceful degradation."""
|
204
275
|
try:
|
205
|
-
|
276
|
+
app_configs = self._fetch_apps()
|
277
|
+
if not app_configs:
|
278
|
+
logger.warning("No apps found from AgentR API")
|
279
|
+
return
|
280
|
+
|
281
|
+
loaded_apps = 0
|
282
|
+
for app_config in app_configs:
|
206
283
|
app = self._load_app(app_config)
|
207
284
|
if app:
|
208
285
|
self._tool_manager.register_tools_from_app(app, app_config.actions)
|
286
|
+
loaded_apps += 1
|
287
|
+
|
288
|
+
if loaded_apps == 0:
|
289
|
+
logger.error("Failed to load any apps from AgentR")
|
290
|
+
else:
|
291
|
+
logger.info(f"Successfully loaded {loaded_apps}/{len(app_configs)} apps from AgentR")
|
292
|
+
|
209
293
|
except Exception:
|
210
294
|
logger.error("Failed to load apps", exc_info=True)
|
211
|
-
raise
|
295
|
+
# Don't raise the exception to allow server to start with partial functionality
|
296
|
+
logger.warning("Server will start with limited functionality due to app loading failures")
|
212
297
|
|
213
298
|
|
214
299
|
class SingleMCPServer(BaseServer):
|
@@ -234,27 +319,13 @@ class SingleMCPServer(BaseServer):
|
|
234
319
|
config: ServerConfig | None = None,
|
235
320
|
**kwargs,
|
236
321
|
):
|
322
|
+
if not app_instance:
|
323
|
+
raise ValueError("app_instance is required")
|
237
324
|
if not config:
|
238
325
|
config = ServerConfig(
|
239
326
|
type="local",
|
240
|
-
name=f"{app_instance.name.title()} MCP Server for Local Development"
|
241
|
-
|
242
|
-
else "Unnamed MCP Server",
|
243
|
-
description=f"Minimal MCP server for the local {app_instance.name} application."
|
244
|
-
if app_instance
|
245
|
-
else "Minimal MCP server with no application loaded.",
|
327
|
+
name=f"{app_instance.name.title()} MCP Server for Local Development",
|
328
|
+
description=f"Minimal MCP server for the local {app_instance.name} application.",
|
246
329
|
)
|
247
330
|
super().__init__(config, **kwargs)
|
248
|
-
|
249
|
-
self.app_instance = app_instance
|
250
|
-
self._load_apps()
|
251
|
-
|
252
|
-
def _load_apps(self) -> None:
|
253
|
-
"""Registers tools from the single provided application instance."""
|
254
|
-
if not self.app_instance:
|
255
|
-
logger.warning("No app_instance provided. No tools registered.")
|
256
|
-
return
|
257
|
-
|
258
|
-
tool_functions = self.app_instance.list_tools()
|
259
|
-
for tool_func in tool_functions:
|
260
|
-
self._tool_manager.add_tool(tool_func)
|
331
|
+
self._tool_manager.register_tools_from_app(app_instance)
|
universal_mcp/tools/manager.py
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
import re
|
1
2
|
from collections.abc import Callable
|
2
3
|
from typing import Any
|
3
4
|
|
@@ -19,14 +20,21 @@ DEFAULT_IMPORTANT_TAG = "important"
|
|
19
20
|
TOOL_NAME_SEPARATOR = "_"
|
20
21
|
|
21
22
|
|
22
|
-
def _filter_by_name(tools: list[Tool], tool_names: list[str]) -> list[Tool]:
|
23
|
+
def _filter_by_name(tools: list[Tool], tool_names: list[str] | None) -> list[Tool]:
|
23
24
|
if not tool_names:
|
24
25
|
return tools
|
25
|
-
|
26
|
+
logger.debug(f"Filtering tools by name: {tool_names}")
|
27
|
+
filtered_tools = []
|
28
|
+
for tool in tools:
|
29
|
+
for name in tool_names:
|
30
|
+
if re.search(name, tool.name):
|
31
|
+
filtered_tools.append(tool)
|
32
|
+
return filtered_tools
|
26
33
|
|
27
34
|
|
28
35
|
def _filter_by_tags(tools: list[Tool], tags: list[str] | None) -> list[Tool]:
|
29
|
-
|
36
|
+
if not tags:
|
37
|
+
return tools
|
30
38
|
return [tool for tool in tools if any(tag in tool.tags for tag in tags)]
|
31
39
|
|
32
40
|
|
@@ -77,7 +85,6 @@ class ToolManager:
|
|
77
85
|
tools = list(self._tools.values())
|
78
86
|
if tags:
|
79
87
|
tools = _filter_by_tags(tools, tags)
|
80
|
-
|
81
88
|
if format == ToolFormat.MCP:
|
82
89
|
tools = [convert_tool_to_mcp_tool(tool) for tool in tools]
|
83
90
|
elif format == ToolFormat.LANGCHAIN:
|
@@ -86,7 +93,6 @@ class ToolManager:
|
|
86
93
|
tools = [convert_tool_to_openai_tool(tool) for tool in tools]
|
87
94
|
else:
|
88
95
|
raise ValueError(f"Invalid format: {format}")
|
89
|
-
|
90
96
|
return tools
|
91
97
|
|
92
98
|
def add_tool(self, fn: Callable[..., Any] | Tool, name: str | None = None) -> Tool:
|
@@ -148,14 +154,14 @@ class ToolManager:
|
|
148
154
|
def register_tools_from_app(
|
149
155
|
self,
|
150
156
|
app: BaseApplication,
|
151
|
-
tool_names: list[str] = None,
|
152
|
-
tags: list[str] = None,
|
157
|
+
tool_names: list[str] | None = None,
|
158
|
+
tags: list[str] | None = None,
|
153
159
|
) -> None:
|
154
160
|
"""Register tools from an application.
|
155
161
|
|
156
162
|
Args:
|
157
163
|
app: The application to register tools from.
|
158
|
-
|
164
|
+
tool_names: Optional list of specific tool names to register.
|
159
165
|
tags: Optional list of tags to filter tools by.
|
160
166
|
"""
|
161
167
|
try:
|
@@ -186,8 +192,16 @@ class ToolManager:
|
|
186
192
|
tool_name = getattr(function, "__name__", "unknown")
|
187
193
|
logger.error(f"Failed to create Tool from '{tool_name}' in {app.name}: {e}")
|
188
194
|
|
189
|
-
|
190
|
-
|
195
|
+
if tags:
|
196
|
+
tools = _filter_by_tags(tools, tags)
|
197
|
+
|
198
|
+
if tool_names:
|
199
|
+
tools = _filter_by_name(tools, tool_names)
|
200
|
+
|
201
|
+
# If no tool names or tags are provided, use the default important tag
|
202
|
+
if not tool_names and not tags:
|
203
|
+
tools = _filter_by_tags(tools, [DEFAULT_IMPORTANT_TAG])
|
204
|
+
|
191
205
|
self.register_tools(tools)
|
192
206
|
return
|
193
207
|
|
universal_mcp/utils/agentr.py
CHANGED
@@ -5,10 +5,9 @@ from loguru import logger
|
|
5
5
|
|
6
6
|
from universal_mcp.config import AppConfig
|
7
7
|
from universal_mcp.exceptions import NotAuthorizedError
|
8
|
-
from universal_mcp.utils.singleton import Singleton
|
9
8
|
|
10
9
|
|
11
|
-
class AgentrClient
|
10
|
+
class AgentrClient:
|
12
11
|
"""Helper class for AgentR API operations.
|
13
12
|
|
14
13
|
This class provides utility methods for interacting with the AgentR API,
|
@@ -27,6 +26,9 @@ class AgentrClient(metaclass=Singleton):
|
|
27
26
|
)
|
28
27
|
raise ValueError("AgentR API key required - get one at https://agentr.dev")
|
29
28
|
self.base_url = (base_url or os.getenv("AGENTR_BASE_URL", "https://api.agentr.dev")).rstrip("/")
|
29
|
+
self.client = httpx.Client(
|
30
|
+
base_url=self.base_url, headers={"X-API-KEY": self.api_key}, timeout=30, follow_redirects=True
|
31
|
+
)
|
30
32
|
|
31
33
|
def get_credentials(self, integration_name: str) -> dict:
|
32
34
|
"""Get credentials for an integration from the AgentR API.
|
@@ -41,9 +43,8 @@ class AgentrClient(metaclass=Singleton):
|
|
41
43
|
NotAuthorizedError: If credentials are not found (404 response)
|
42
44
|
HTTPError: For other API errors
|
43
45
|
"""
|
44
|
-
response =
|
45
|
-
f"
|
46
|
-
headers={"accept": "application/json", "X-API-KEY": self.api_key},
|
46
|
+
response = self.client.get(
|
47
|
+
f"/api/{integration_name}/credentials/",
|
47
48
|
)
|
48
49
|
if response.status_code == 404:
|
49
50
|
logger.warning(f"No credentials found for {integration_name}. Requesting authorization...")
|
@@ -64,15 +65,14 @@ class AgentrClient(metaclass=Singleton):
|
|
64
65
|
Raises:
|
65
66
|
HTTPError: If API request fails
|
66
67
|
"""
|
67
|
-
response =
|
68
|
-
f"
|
69
|
-
headers={"X-API-KEY": self.api_key},
|
68
|
+
response = self.client.get(
|
69
|
+
f"/api/{integration_name}/authorize/",
|
70
70
|
)
|
71
71
|
response.raise_for_status()
|
72
72
|
url = response.json()
|
73
73
|
return f"Please ask the user to visit the following url to authorize the application: {url}. Render the url in proper markdown format with a clickable link."
|
74
74
|
|
75
|
-
def fetch_apps(self) -> list[
|
75
|
+
def fetch_apps(self) -> list[AppConfig]:
|
76
76
|
"""Fetch available apps from AgentR API.
|
77
77
|
|
78
78
|
Returns:
|
@@ -81,11 +81,7 @@ class AgentrClient(metaclass=Singleton):
|
|
81
81
|
Raises:
|
82
82
|
httpx.HTTPError: If API request fails
|
83
83
|
"""
|
84
|
-
response =
|
85
|
-
f"{self.base_url}/api/apps/",
|
86
|
-
headers={"X-API-KEY": self.api_key},
|
87
|
-
timeout=10,
|
88
|
-
)
|
84
|
+
response = self.client.get("/api/apps/")
|
89
85
|
response.raise_for_status()
|
90
86
|
data = response.json()
|
91
87
|
return [AppConfig.model_validate(app) for app in data]
|