universal-mcp 0.1.18rc3__tar.gz → 0.1.18rc4__tar.gz

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 (55) hide show
  1. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/PKG-INFO +1 -1
  2. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/pyproject.toml +1 -1
  3. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/config.py +1 -4
  4. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/exceptions.py +4 -0
  5. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/servers/server.py +125 -54
  6. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/tools/manager.py +0 -2
  7. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/agentr.py +10 -14
  8. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/openapi.py +6 -1
  9. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/.gitignore +0 -0
  10. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/LICENSE +0 -0
  11. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/README.md +0 -0
  12. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/__init__.py +0 -0
  13. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/conftest.py +0 -0
  14. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_api_generator.py +0 -0
  15. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_api_integration.py +0 -0
  16. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_applications.py +0 -0
  17. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_localserver.py +0 -0
  18. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_stores.py +0 -0
  19. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_tool.py +0 -0
  20. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_tool_manager.py +0 -0
  21. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/tests/test_zenquotes.py +0 -0
  22. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/__init__.py +0 -0
  23. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/analytics.py +0 -0
  24. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/applications/README.md +0 -0
  25. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/applications/__init__.py +0 -0
  26. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/applications/application.py +0 -0
  27. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/cli.py +0 -0
  28. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/integrations/README.md +0 -0
  29. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/integrations/__init__.py +0 -0
  30. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/integrations/integration.py +0 -0
  31. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/logger.py +0 -0
  32. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/py.typed +0 -0
  33. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/servers/README.md +0 -0
  34. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/servers/__init__.py +0 -0
  35. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/stores/README.md +0 -0
  36. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/stores/__init__.py +0 -0
  37. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/stores/store.py +0 -0
  38. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/tools/README.md +0 -0
  39. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/tools/__init__.py +0 -0
  40. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/tools/adapters.py +0 -0
  41. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/tools/func_metadata.py +0 -0
  42. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/tools/tools.py +0 -0
  43. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/__init__.py +0 -0
  44. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/common.py +0 -0
  45. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/docstring_parser.py +0 -0
  46. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/installation.py +0 -0
  47. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/__inti__.py +0 -0
  48. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/api_generator.py +0 -0
  49. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/api_splitter.py +0 -0
  50. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/docgen.py +0 -0
  51. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/preprocessor.py +0 -0
  52. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/openapi/readme.py +0 -0
  53. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/singleton.py +0 -0
  54. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/templates/README.md.j2 +0 -0
  55. {universal_mcp-0.1.18rc3 → universal_mcp-0.1.18rc4}/src/universal_mcp/utils/templates/api_client.py.j2 +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: universal-mcp
3
- Version: 0.1.18rc3
3
+ Version: 0.1.18rc4
4
4
  Summary: Universal MCP acts as a middle ware for your API applications. It can store your credentials, authorize, enable disable apps on the fly and much more.
5
5
  Author-email: Manoj Bajaj <manojbajaj95@gmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "universal-mcp"
7
- version = "0.1.18-rc3"
7
+ version = "0.1.18-rc4"
8
8
  description = "Universal MCP acts as a middle ware for your API applications. It can store your credentials, authorize, enable disable apps on the fly and much more."
9
9
  readme = "README.md"
10
10
  authors = [
@@ -38,7 +38,6 @@ class ServerConfig(BaseSettings):
38
38
  """Main server configuration."""
39
39
 
40
40
  model_config = SettingsConfigDict(
41
- env_prefix="MCP_",
42
41
  env_file=".env",
43
42
  env_file_encoding="utf-8",
44
43
  case_sensitive=True,
@@ -52,14 +51,12 @@ class ServerConfig(BaseSettings):
52
51
  transport: Literal["stdio", "sse", "streamable-http"] = Field(
53
52
  default="stdio", description="Transport protocol to use"
54
53
  )
55
- port: int = Field(default=8005, description="Port to run the server on (if applicable)")
54
+ port: int = Field(default=8005, description="Port to run the server on (if applicable)", ge=1024, le=65535)
56
55
  host: str = Field(default="localhost", description="Host to bind the server to (if applicable)")
57
56
  apps: list[AppConfig] | None = Field(default=None, description="List of configured applications")
58
57
  store: StoreConfig | None = Field(default=None, description="Default store configuration")
59
58
  debug: bool = Field(default=False, description="Enable debug mode")
60
59
  log_level: str = Field(default="INFO", description="Logging level")
61
- max_connections: int = Field(default=100, description="Maximum number of concurrent connections")
62
- request_timeout: int = Field(default=60, description="Default request timeout in seconds")
63
60
 
64
61
  @field_validator("log_level", mode="before")
65
62
  def validate_log_level(cls, v: str) -> str:
@@ -19,3 +19,7 @@ class StoreError(Exception):
19
19
 
20
20
  class KeyNotFoundError(StoreError):
21
21
  """Exception raised when a key is not found in the store."""
22
+
23
+
24
+ class ConfigurationError(Exception):
25
+ """Exception raised when a configuration error occurs."""
@@ -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, ABC):
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
- super().__init__(config.name, config.description, port=config.port, **kwargs)
31
- logger.info(f"Initializing server: {config.name} ({config.type}) with store: {config.store}")
32
-
33
- self.config = config # Store config at base level for consistency
34
- self._tool_manager = ToolManager(warn_on_duplicate_tools=True)
35
-
36
- @abstractmethod
37
- def _load_apps(self) -> None:
38
- """Load and register applications."""
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
- result = await self._tool_manager.call_tool(name, arguments)
89
- logger.info(f"Tool '{name}' completed successfully")
90
- return self._format_tool_result(result)
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
- store = store_from_config(store_config)
119
- self.add_tool(store.set)
120
- self.add_tool(store.delete)
121
- return store
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
- integration_from_config(app_config.integration, store=self.store) if app_config.integration else None
135
- )
136
- return app_from_slug(app_config.name)(integration=integration)
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
- logger.info(f"Loading apps: {self.config.apps}")
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
- self._tool_manager.register_tools_from_app(app, app_config.actions)
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.client = AgentrClient(api_key=api_key)
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
- return [AppConfig.model_validate(app) for app in apps]
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
- return app_from_slug(app_config.name)(integration=integration)
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
- for app_config in self._fetch_apps():
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
- if app_instance
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)
@@ -85,7 +85,6 @@ class ToolManager:
85
85
  tools = list(self._tools.values())
86
86
  if tags:
87
87
  tools = _filter_by_tags(tools, tags)
88
-
89
88
  if format == ToolFormat.MCP:
90
89
  tools = [convert_tool_to_mcp_tool(tool) for tool in tools]
91
90
  elif format == ToolFormat.LANGCHAIN:
@@ -94,7 +93,6 @@ class ToolManager:
94
93
  tools = [convert_tool_to_openai_tool(tool) for tool in tools]
95
94
  else:
96
95
  raise ValueError(f"Invalid format: {format}")
97
-
98
96
  return tools
99
97
 
100
98
  def add_tool(self, fn: Callable[..., Any] | Tool, name: str | None = None) -> Tool:
@@ -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(metaclass=Singleton):
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 = httpx.get(
45
- f"{self.base_url}/api/{integration_name}/credentials/",
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 = httpx.get(
68
- f"{self.base_url}/api/{integration_name}/authorize/",
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[dict]:
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 = httpx.get(
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]
@@ -897,7 +897,12 @@ def _generate_method_code(path, method, operation):
897
897
 
898
898
  # --- Handle Response ---
899
899
  body_lines.append(" response.raise_for_status()")
900
- body_lines.append(" return response.json()")
900
+ body_lines.append(" if response.status_code == 204 or not response.content or not response.text.strip():")
901
+ body_lines.append(" return None")
902
+ body_lines.append(" try:")
903
+ body_lines.append(" return response.json()")
904
+ body_lines.append(" except ValueError:")
905
+ body_lines.append(" return None")
901
906
 
902
907
  # --- Combine Signature, Docstring, and Body for Final Method Code ---
903
908
  method_code = signature + formatted_docstring + "\n" + "\n".join(body_lines)