Skip to content

Personal AI, On Personal Devices

Python

feat(mcp): support external JSON file for server configuration (#119)

Manuel Richarza929efc29b3a
diff --git a/docs/user-guide/mcp-external-servers.md b/docs/user-guide/mcp-external-servers.md
index 7fd316e0..99a54616 100644
--- a/docs/user-guide/mcp-external-servers.md
+++ b/docs/user-guide/mcp-external-servers.md
@@ -15,7 +15,8 @@ If a server is unreachable or returns an error, OpenJarvis logs a warning and co
## Configuration
-External MCP servers are configured in `config.toml` under `[tools.mcp]`:
+External MCP servers are configured in `config.toml` under `[tools.mcp]`. The
+`servers` field accepts either inline JSON or a path to a JSON file:
```toml
[tools.mcp]
@@ -23,10 +24,40 @@ enabled = true
servers = '[{"name": "homeassistant", "url": "http://172.16.3.1:9583/private_abc123"}]'
```
-The `servers` value is a **JSON-encoded string** containing an array of server objects. Each object defines one external MCP server.
+For larger configurations, keep the server objects in a separate file next to
+`config.toml`:
+
+```toml
+[tools.mcp]
+enabled = true
+servers = "mcp-servers.json"
+```
+
+```json
+[
+ {
+ "name": "homeassistant",
+ "url": "http://172.16.3.1:9583/private_abc123"
+ },
+ {
+ "name": "database",
+ "command": "db-mcp-server",
+ "args": ["--db", "postgres://localhost/mydb"]
+ }
+]
+```
+
+Relative paths are resolved from the directory containing `config.toml` and
+must remain inside that directory. Absolute paths (including paths expanded
+from `~`) are also supported. A file may contain either an array of server
+objects or one server object, which OpenJarvis wraps in an array.
+
+Inline `servers` values are **JSON-encoded strings** containing an array of
+server objects. Each object defines one external MCP server.
!!! note
- The value must be a JSON string (with single-quote TOML delimiters around it), not a native TOML array. This is because the configuration system passes it through as a single string field.
+ An inline value must be a JSON string (with single-quote TOML delimiters
+ around it), not a native TOML array. A file path is a normal TOML string.
## Server Config Schema
@@ -136,7 +167,9 @@ No single server failure causes OpenJarvis to crash or prevents other tools from
### Server not discovered
1. Check that `[tools.mcp]` has `enabled = true`.
-2. Verify the `servers` JSON is valid. A common mistake is using TOML arrays instead of a JSON string.
+2. Verify the inline `servers` JSON is valid, or that the configured JSON file
+ exists and is readable. A common mistake is using TOML arrays instead of a
+ JSON string.
3. Check the OpenJarvis logs for warnings like `Failed to discover external MCP tools`.
### Connection refused / timeout
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index 0ed53829..b3ed8999 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -966,6 +966,112 @@ class MCPConfig:
servers: str = "" # JSON list of MCP server configs
+_MAX_EXTERNAL_JSON_BYTES = 4 * 1024 * 1024
+
+
+def resolve_json_or_file(raw: str, config_dir: Path) -> Any:
+ """Resolve a config value that is either inline JSON or a path to a JSON file.
+
+ Parameters
+ ----------
+ raw:
+ Either a JSON string (starts with '[' or '{') or a file path
+ to a .json file containing the data.
+ config_dir:
+ Directory of config.toml, used to resolve relative file paths.
+
+ Returns
+ -------
+ Parsed JSON value (dict, list, etc.), or ``None`` if *raw* is empty.
+
+ Raises
+ ------
+ ValueError: If a relative path escapes the config directory.
+ FileNotFoundError: If the referenced file does not exist.
+ json.JSONDecodeError: If the JSON content is malformed.
+ """
+ import json
+
+ if not isinstance(raw, str):
+ raise TypeError("JSON config value must be a string")
+
+ stripped = raw.strip()
+ if not stripped:
+ return None
+
+ # Inline JSON
+ if stripped.startswith("[") or stripped.startswith("{"):
+ return json.loads(stripped)
+
+ # File path reference
+ file_path = Path(stripped).expanduser()
+ was_relative = not file_path.is_absolute()
+ if was_relative:
+ file_path = config_dir / file_path
+
+ resolved = file_path.resolve()
+
+ # Security check: relative paths must not escape the config directory
+ if was_relative:
+ config_resolved = config_dir.expanduser().resolve()
+ try:
+ resolved.relative_to(config_resolved)
+ except ValueError as exc:
+ raise ValueError(
+ f"Path '{stripped}' resolves to '{resolved}' which is outside "
+ f"the config directory '{config_resolved}'"
+ ) from exc
+
+ if not resolved.exists():
+ raise FileNotFoundError(
+ f"MCP config file not found: {resolved} (from '{stripped}')"
+ )
+ if not resolved.is_file():
+ raise ValueError(f"JSON config path is not a regular file: {resolved}")
+ if resolved.stat().st_size > _MAX_EXTERNAL_JSON_BYTES:
+ raise ValueError(
+ f"JSON config file exceeds {_MAX_EXTERNAL_JSON_BYTES} bytes: {resolved}"
+ )
+
+ content = resolved.read_text(encoding="utf-8")
+ return json.loads(content)
+
+
+def resolve_mcp_servers(raw: str, config_dir: Path) -> list[dict[str, Any]]:
+ """Resolve MCP server configuration from inline JSON or an external file.
+
+ Wraps :func:`resolve_json_or_file` with MCP-specific validation:
+ a single server object ``{...}`` is automatically wrapped in a list,
+ and the result must be a ``list``.
+ """
+ import json
+
+ result = resolve_json_or_file(raw, config_dir)
+ if result is None:
+ return []
+ if isinstance(result, dict):
+ result = [result]
+ if not isinstance(result, list):
+ raise ValueError(
+ "MCP servers config must be a JSON array or object, "
+ f"got {type(result).__name__}"
+ )
+
+ servers: list[dict[str, Any]] = []
+ for index, server in enumerate(result):
+ if isinstance(server, str):
+ try:
+ server = json.loads(server)
+ except json.JSONDecodeError as exc:
+ raise ValueError(
+ f"MCP server entry {index} is not a valid JSON object"
+ ) from exc
+ if not isinstance(server, dict):
+ raise ValueError(f"MCP server entry {index} must be a JSON object")
+ servers.append(server)
+ return servers
+
+
@dataclass(slots=True)
class BrowserConfig:
"""Browser automation settings (Playwright)."""
@@ -1622,6 +1728,15 @@ class JarvisConfig:
proactive: ProactiveConfig = field(default_factory=ProactiveConfig)
mining: Optional["MiningConfig"] = None
+ @property
+ def _config_dir(self) -> Path:
+ """Directory containing the loaded config, or the env-aware default."""
+ return self.__dict__.get("_config_source_dir", get_config_dir())
+
+ @_config_dir.setter
+ def _config_dir(self, value: Path) -> None:
+ self.__dict__["_config_source_dir"] = Path(value)
+
@property
def memory(self) -> StorageConfig:
"""Backward-compatible accessor — canonical location is tools.storage."""
@@ -1867,11 +1982,12 @@ def load_config(path: Optional[Path] = None) -> JarvisConfig:
cfg.engine.default = recommend_engine(hw)
if path is not None:
- config_path = Path(path)
+ config_path = Path(path).expanduser().resolve()
elif os.environ.get("OPENJARVIS_CONFIG"):
config_path = Path(os.environ["OPENJARVIS_CONFIG"]).expanduser().resolve()
else:
config_path = get_config_path()
+ cfg._config_dir = config_path.parent
if config_path.exists():
with open(config_path, "rb") as fh:
data = tomllib.load(fh)
diff --git a/src/openjarvis/server/agent_manager_routes.py b/src/openjarvis/server/agent_manager_routes.py
index 99c73f39..4e501ba3 100644
--- a/src/openjarvis/server/agent_manager_routes.py
+++ b/src/openjarvis/server/agent_manager_routes.py
@@ -679,9 +679,7 @@ def _get_mcp_tools_locked(
app_state._mcp_tools_cache = (openai_tools, adapters_by_name)
return app_state._mcp_tools_cache
- import json as _json
-
- from openjarvis.core.config import load_config
+ from openjarvis.core.config import load_config, resolve_mcp_servers
openai_tools: List[Dict[str, Any]] = []
adapters_by_name: Dict[str, Any] = {}
@@ -700,16 +698,16 @@ def _get_mcp_tools_locked(
from openjarvis.tools.mcp_adapter import MCPToolProvider
try:
- server_list = _json.loads(app_config.tools.mcp.servers)
- except (_json.JSONDecodeError, TypeError) as exc:
+ server_list = resolve_mcp_servers(
+ app_config.tools.mcp.servers,
+ app_config._config_dir,
+ )
+ except (OSError, UnicodeError, ValueError, TypeError) as exc:
logger.warning("Failed to parse MCP server config: %s", exc)
return openai_tools, adapters_by_name
- if not isinstance(server_list, list):
- return openai_tools, adapters_by_name
-
for server_cfg in server_list:
- cfg = _json.loads(server_cfg) if isinstance(server_cfg, str) else server_cfg
+ cfg = server_cfg
name = cfg.get("name", "<unnamed>")
url = cfg.get("url")
# Bearer token from config — mirrors the builder.py fix for #461.
diff --git a/src/openjarvis/system/builder.py b/src/openjarvis/system/builder.py
index e0fde9c6..c0467c91 100644
--- a/src/openjarvis/system/builder.py
+++ b/src/openjarvis/system/builder.py
@@ -471,27 +471,27 @@ class SystemBuilder:
if config.tools.mcp.enabled and config.tools.mcp.servers:
try:
- import json
-
- server_list = json.loads(config.tools.mcp.servers)
- if isinstance(server_list, list):
- for server_cfg in server_list:
- try:
- external_tools = self._discover_external_mcp(server_cfg)
- self._mcp_tools.extend(external_tools)
- if tool_names:
- external_tools = [
- t
- for t in external_tools
- if t.spec.name in tool_names
- ]
- tools.extend(external_tools)
- except Exception as exc:
- logger.warning(
- "Failed to discover external MCP tools: %s",
- exc,
- )
- except (json.JSONDecodeError, TypeError) as exc:
+ from openjarvis.core.config import resolve_mcp_servers
+
+ server_list = resolve_mcp_servers(
+ config.tools.mcp.servers,
+ config._config_dir,
+ )
+ for server_cfg in server_list:
+ try:
+ external_tools = self._discover_external_mcp(server_cfg)
+ self._mcp_tools.extend(external_tools)
+ if tool_names:
+ external_tools = [
+ t for t in external_tools if t.spec.name in tool_names
+ ]
+ tools.extend(external_tools)
+ except Exception as exc:
+ logger.warning(
+ "Failed to discover external MCP tools: %s",
+ exc,
+ )
+ except (OSError, UnicodeError, ValueError, TypeError) as exc:
logger.warning("Failed to parse MCP server config: %s", exc)
return tools
diff --git a/tests/core/test_resolve_json_or_file.py b/tests/core/test_resolve_json_or_file.py
new file mode 100644
index 00000000..6678d441
--- /dev/null
+++ b/tests/core/test_resolve_json_or_file.py
@@ -0,0 +1,105 @@
+"""Tests for resolve_json_or_file in openjarvis.core.config."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from openjarvis.core.config import load_config, resolve_json_or_file
+
+
+class TestResolveJsonOrFile:
+ """Unit tests for resolve_json_or_file."""
+
+ def test_empty_string(self, tmp_path: Path) -> None:
+ assert resolve_json_or_file("", tmp_path) is None
+
+ def test_whitespace_only(self, tmp_path: Path) -> None:
+ assert resolve_json_or_file(" ", tmp_path) is None
+
+ def test_inline_json_array(self, tmp_path: Path) -> None:
+ assert resolve_json_or_file("[1, 2, 3]", tmp_path) == [1, 2, 3]
+
+ def test_inline_json_object(self, tmp_path: Path) -> None:
+ assert resolve_json_or_file('{"key": "val"}', tmp_path) == {"key": "val"}
+
+ def test_inline_json_with_leading_whitespace(self, tmp_path: Path) -> None:
+ assert resolve_json_or_file(" [1]", tmp_path) == [1]
+
+ def test_file_path_relative(self, tmp_path: Path) -> None:
+ sub = tmp_path / "sub"
+ sub.mkdir()
+ data_file = sub / "data.json"
+ data_file.write_text('[{"a": 1}]', encoding="utf-8")
+
+ result = resolve_json_or_file("sub/data.json", tmp_path)
+ assert result == [{"a": 1}]
+
+ def test_file_path_absolute(self, tmp_path: Path) -> None:
+ # Use a subdirectory as a separate location from config_dir
+ config_dir = tmp_path / "config"
+ config_dir.mkdir()
+ data_dir = tmp_path / "external"
+ data_dir.mkdir()
+ data_file = data_dir / "servers.json"
+ data_file.write_text('{"url": "http://localhost"}', encoding="utf-8")
+
+ result = resolve_json_or_file(str(data_file), config_dir)
+ assert result == {"url": "http://localhost"}
+
+ def test_directory_traversal_blocked(self, tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="outside"):
+ resolve_json_or_file("../../etc/passwd", tmp_path)
+
+ def test_directory_traversal_dot_segments(self, tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="outside"):
+ resolve_json_or_file("sub/../../etc/passwd", tmp_path)
+
+ def test_file_not_found(self, tmp_path: Path) -> None:
+ with pytest.raises(FileNotFoundError):
+ resolve_json_or_file("nonexistent.json", tmp_path)
+
+ def test_directory_is_rejected(self, tmp_path: Path) -> None:
+ directory = tmp_path / "servers.json"
+ directory.mkdir()
+
+ with pytest.raises(ValueError, match="not a regular file"):
+ resolve_json_or_file("servers.json", tmp_path)
+
+ def test_invalid_json_in_file(self, tmp_path: Path) -> None:
+ bad_file = tmp_path / "broken.json"
+ bad_file.write_text("{broken json", encoding="utf-8")
+
+ with pytest.raises(json.JSONDecodeError):
+ resolve_json_or_file("broken.json", tmp_path)
+
+ def test_absolute_path_outside_config_dir_allowed(self, tmp_path: Path) -> None:
+ config_dir = tmp_path / "config"
+ config_dir.mkdir()
+ other_dir = tmp_path / "other"
+ other_dir.mkdir()
+ data_file = other_dir / "data.json"
+ data_file.write_text("[42]", encoding="utf-8")
+
+ # Absolute paths bypass the traversal check
+ result = resolve_json_or_file(str(data_file), config_dir)
+ assert result == [42]
+
+ def test_load_config_records_explicit_source_directory(
+ self, tmp_path: Path
+ ) -> None:
+ config_dir = tmp_path / "nested"
+ config_dir.mkdir()
+ config_path = config_dir / "config.toml"
+ config_path.write_text(
+ '[tools.mcp]\nservers = "mcp-servers.json"\n',
+ encoding="utf-8",
+ )
+
+ load_config.cache_clear()
+ try:
+ config = load_config(config_path)
+ finally:
+ load_config.cache_clear()
+
+ assert config._config_dir == config_dir.resolve()
diff --git a/tests/mcp/test_discovery.py b/tests/mcp/test_discovery.py
index 9dc15097..ef3e5c78 100644
--- a/tests/mcp/test_discovery.py
+++ b/tests/mcp/test_discovery.py
@@ -244,6 +244,39 @@ def test_builder_global_mcp_disable_prevents_discovery() -> None:
assert builder._mcp_tools == []
+def test_builder_resolves_external_file_from_config_directory(tmp_path) -> None:
+ """SystemBuilder consumes file-backed MCP config on the primary path."""
+
+ from openjarvis.core.config import JarvisConfig
+ from openjarvis.system import SystemBuilder
+
+ server_file = tmp_path / "mcp-servers.json"
+ server_file.write_text(
+ '[{"name": "file-server", "url": "http://localhost:8080/mcp"}]',
+ encoding="utf-8",
+ )
+ config = JarvisConfig()
+ config.tools.mcp.servers = server_file.name
+ config._config_dir = tmp_path
+ builder = SystemBuilder(config)
+
+ with (
+ patch("openjarvis.mcp.server.MCPServer") as mcp_server_cls,
+ patch.object(builder, "_discover_external_mcp", return_value=[]) as discover,
+ ):
+ mcp_server_cls.return_value.get_tools.return_value = []
+ builder._resolve_tools(
+ config,
+ engine=MagicMock(),
+ model="test-model",
+ memory_backend=None,
+ )
+
+ discover.assert_called_once_with(
+ {"name": "file-server", "url": "http://localhost:8080/mcp"}
+ )
+
+
def test_reused_builder_transfers_only_current_build_mcp_state() -> None:
"""Each built system exclusively owns its own MCP clients and tools."""
diff --git a/tests/mcp/test_resolve_mcp_servers.py b/tests/mcp/test_resolve_mcp_servers.py
new file mode 100644
index 00000000..f7be3d57
--- /dev/null
+++ b/tests/mcp/test_resolve_mcp_servers.py
@@ -0,0 +1,55 @@
+"""Tests for resolve_mcp_servers in openjarvis.core.config."""
+
+from pathlib import Path
+
+import pytest
+
+from openjarvis.core.config import resolve_mcp_servers
+
+
+class TestResolveMcpServers:
+ """Unit tests for resolve_mcp_servers."""
+
+ def test_inline_json_backwards_compat(self, tmp_path: Path) -> None:
+ raw = '[{"name": "test", "url": "http://localhost"}]'
+ result = resolve_mcp_servers(raw, tmp_path)
+ assert result == [{"name": "test", "url": "http://localhost"}]
+
+ def test_empty_string(self, tmp_path: Path) -> None:
+ assert resolve_mcp_servers("", tmp_path) == []
+
+ def test_single_object_inline(self, tmp_path: Path) -> None:
+ raw = '{"name": "ha", "url": "http://localhost"}'
+ result = resolve_mcp_servers(raw, tmp_path)
+ assert result == [{"name": "ha", "url": "http://localhost"}]
+
+ def test_non_list_result_raises(self, tmp_path: Path) -> None:
+ string_file = tmp_path / "bad.json"
+ string_file.write_text('"just a string"', encoding="utf-8")
+
+ with pytest.raises(ValueError, match="must be a JSON array or object"):
+ resolve_mcp_servers("bad.json", tmp_path)
+
+ def test_file_path_loads_array(self, tmp_path: Path) -> None:
+ servers_file = tmp_path / "servers.json"
+ servers_file.write_text(
+ '[{"name": "s1", "url": "http://a"}, {"name": "s2", "url": "http://b"}]',
+ encoding="utf-8",
+ )
+
+ result = resolve_mcp_servers("servers.json", tmp_path)
+ assert len(result) == 2
+ assert result[0]["name"] == "s1"
+ assert result[1]["name"] == "s2"
+
+ def test_legacy_json_string_entries_are_normalized(self, tmp_path: Path) -> None:
+ raw = '["{\\"name\\": \\"legacy\\", \\"url\\": \\"http://a\\"}"]'
+
+ assert resolve_mcp_servers(raw, tmp_path) == [
+ {"name": "legacy", "url": "http://a"}
+ ]
+
+ @pytest.mark.parametrize("raw", ["[1]", "[null]", '["not-json"]'])
+ def test_non_object_entries_are_rejected(self, raw: str, tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="entry 0"):
+ resolve_mcp_servers(raw, tmp_path)
diff --git a/tests/server/test_mcp_tools_cache.py b/tests/server/test_mcp_tools_cache.py
index ccc6b26a..869cee14 100644
--- a/tests/server/test_mcp_tools_cache.py
+++ b/tests/server/test_mcp_tools_cache.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import threading
+from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
@@ -75,6 +76,36 @@ def test_returns_tools_from_mcp_server(mock_load_config: MagicMock):
assert "get_weather" in adapters
+@patch("openjarvis.core.config.load_config")
+def test_returns_tools_from_external_mcp_file(
+ mock_load_config: MagicMock, tmp_path: Path
+):
+ """Managed-agent discovery uses the same file-backed config semantics."""
+
+ from openjarvis.server.agent_manager_routes import _get_mcp_tools
+
+ server_file = tmp_path / "mcp-servers.json"
+ server_file.write_text(
+ '[{"name": "file-server", "url": "http://localhost:9999"}]',
+ encoding="utf-8",
+ )
+ config = _make_config(servers_json=server_file.name)
+ config._config_dir = tmp_path
+ mock_load_config.return_value = config
+ mock_adapter = _make_adapter("file_tool")
+
+ with (
+ patch("openjarvis.mcp.transport.StreamableHTTPTransport"),
+ patch("openjarvis.mcp.client.MCPClient"),
+ patch("openjarvis.tools.mcp_adapter.MCPToolProvider") as provider,
+ ):
+ provider.return_value.discover.return_value = [mock_adapter]
+ tools, adapters = _get_mcp_tools(_FakeAppState())
+
+ assert tools[0]["function"]["name"] == "file_tool"
+ assert adapters == {"file_tool": mock_adapter}
+
+
@patch("openjarvis.core.config.load_config")
def test_caches_successful_discovery(mock_load_config: MagicMock):
"""Second call returns cached result without re-discovering."""