Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ EMBEDDING_MODEL=text-embedding-qwen3-embedding-4b
EMBEDDING_API_KEY=
EMBEDDING_BASE_URL=

# Set false, 0, no, or off to skip MCP client discovery (case-insensitive).
BARELOOP_ENABLE_MCP=true

# Optional MCP endpoints. Local is attempted before remote.
MCP_LOCAL_URL=http://127.0.0.1:8000/mcp
MCP_REMOTE_URL=
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ endpoint carrying `MCP_REMOTE_TOKEN` must use HTTPS; loopback HTTP remains avail
| `TOKENIZER_MODEL` | Yes | Transformers tokenizer used to estimate context size |
| `FALLBACK_MODEL` | No | Reserved fallback model identifier |
| `MLX_MODEL` | No | Reserved local MLX model identifier |
| `BARELOOP_ENABLE_MCP` | No | MCP client discovery; defaults to `true`. Use `false`, `0`, `no`, or `off` to skip it (case-insensitive) |
| `MCP_LOCAL_URL` | No | Local MCP URL; defaults to `http://127.0.0.1:8000/mcp` |
| `MCP_REMOTE_URL` | No | Remote MCP fallback URL |
| `MCP_REMOTE_TOKEN` | No | Bearer token for the remote MCP endpoint |
Expand Down Expand Up @@ -307,4 +308,3 @@ the source and tests as the current contract.
## License

BareLoop is released under the [MIT License](LICENSE).

2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ BareLoop 先尝试本地地址,再尝试配置的 `MCP_REMOTE_URL`;发现的
| `TOKENIZER_MODEL` | 是 | Transformers Tokenizer,用于估算上下文大小 |
| `FALLBACK_MODEL` | 否 | 预留的 Fallback Model 标识,目前未接入路由 |
| `MLX_MODEL` | 否 | 预留的本地 MLX Model 标识,目前未接入路由 |
| `BARELOOP_ENABLE_MCP` | 否 | MCP Client 工具发现,默认 `true`;设为 `false`、`0`、`no` 或 `off` 可跳过(不区分大小写) |
| `MCP_LOCAL_URL` | 否 | 本地 MCP 地址,默认 `http://127.0.0.1:8000/mcp` |
| `MCP_REMOTE_URL` | 否 | 远程 MCP 备用地址 |
| `MCP_REMOTE_TOKEN` | 否 | 远程 MCP Bearer Token |
Expand Down Expand Up @@ -286,4 +287,3 @@ Public API 稳定性仍在开发中。现阶段请以源码和测试作为行为
## License

BareLoop 使用 [MIT License](LICENSE)。

14 changes: 13 additions & 1 deletion src/bareloop/mcp_integration/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,19 @@ def _validate_authenticated_endpoint(url: str) -> None:
raise ValueError("Authenticated remote MCP endpoints require HTTPS")


def _mcp_enabled() -> bool:
return os.getenv("BARELOOP_ENABLE_MCP", "true").strip().lower() not in {
"false",
"0",
"no",
"off",
}


async def mcp_init() -> list[ToolDefinition]:
if not _mcp_enabled():
return []

local_url = os.getenv(
"MCP_LOCAL_URL",
"http://127.0.0.1:8000/mcp",
Expand Down Expand Up @@ -354,7 +366,7 @@ async def mcp_init() -> list[ToolDefinition]:
def start_background_mcp_init() -> None:
"""Start MCP discovery in a background thread concurrently with CLI start."""
global _mcp_init_future
if _mcp_init_future is not None:
if not _mcp_enabled() or _mcp_init_future is not None:
return
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="mcp-init")
_mcp_init_future = executor.submit(lambda: asyncio.run(mcp_init()))
Expand Down
82 changes: 82 additions & 0 deletions tests/test_mcp_integration.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,88 @@
import asyncio
from concurrent.futures import Future
from importlib import import_module
from unittest.mock import AsyncMock, Mock

import pytest


@pytest.mark.parametrize("setting", ["false", "0", "no", "off", " FALSE ", "No", " Off "])
def test_disabled_mcp_does_not_start_background_discovery(monkeypatch, setting) -> None:
from bareloop.mcp_integration import client as mcp_client

monkeypatch.setenv("BARELOOP_ENABLE_MCP", setting)
monkeypatch.setattr(mcp_client, "_mcp_init_future", None)
executor = Mock(side_effect=AssertionError("disabled MCP must not create a thread"))
monkeypatch.setattr(mcp_client.concurrent.futures, "ThreadPoolExecutor", executor)

mcp_client.start_background_mcp_init()

executor.assert_not_called()
assert mcp_client._mcp_init_future is None
assert mcp_client.wait_for_mcp_init() == []


@pytest.mark.parametrize("setting", ["false", "0", "no", "off", " FALSE ", "No", " Off "])
def test_disabled_mcp_skips_direct_discovery(monkeypatch, setting, capsys) -> None:
from bareloop.mcp_integration import client as mcp_client

monkeypatch.setenv("BARELOOP_ENABLE_MCP", setting)
monkeypatch.setenv("MCP_LOCAL_URL", "http://127.0.0.1:8000/mcp")
monkeypatch.setenv("MCP_REMOTE_URL", "https://example.invalid/mcp")
manager = Mock(side_effect=AssertionError("disabled MCP must not discover endpoints"))
register = Mock()
monkeypatch.setattr(mcp_client, "MCPClientManager", manager)
monkeypatch.setattr(mcp_client, "register_dynamic_tools", register)

assert asyncio.run(mcp_client.mcp_init()) == []

manager.assert_not_called()
register.assert_not_called()
assert capsys.readouterr().err == ""


@pytest.mark.parametrize("setting", [None, "true", "1", "yes", " TRUE ", "unrecognized", ""])
def test_enabled_mcp_schedules_discovery_once(monkeypatch, setting) -> None:
from bareloop.mcp_integration import client as mcp_client

monkeypatch.delenv("BARELOOP_ENABLE_MCP", raising=False)
if setting is not None:
monkeypatch.setenv("BARELOOP_ENABLE_MCP", setting)
monkeypatch.setattr(mcp_client, "_mcp_init_future", None)
future = Future()
future.set_result([])
executor = Mock()
executor.submit.return_value = future
monkeypatch.setattr(
mcp_client.concurrent.futures, "ThreadPoolExecutor", Mock(return_value=executor)
)

mcp_client.start_background_mcp_init()
mcp_client.start_background_mcp_init()

executor.submit.assert_called_once()
assert mcp_client.wait_for_mcp_init() == []


@pytest.mark.parametrize("setting", [None, "true", "1", "yes", " TRUE ", "unrecognized", ""])
def test_enabled_mcp_still_initializes_endpoints(monkeypatch, setting) -> None:
from bareloop.mcp_integration import client as mcp_client

monkeypatch.delenv("BARELOOP_ENABLE_MCP", raising=False)
if setting is not None:
monkeypatch.setenv("BARELOOP_ENABLE_MCP", setting)
monkeypatch.delenv("MCP_REMOTE_URL", raising=False)
initialize = AsyncMock()
register = Mock()
monkeypatch.setattr(mcp_client.MCPClientManager, "initialize", initialize)
monkeypatch.setattr(mcp_client, "register_dynamic_tools", register)

assert asyncio.run(mcp_client.mcp_init()) == []

initialize.assert_awaited_once()
register.assert_called_once_with([])


def test_mcp_server_uses_standard_path(monkeypatch: pytest.MonkeyPatch) -> None:
server_module = import_module("bareloop.mcp_integration.server")

Expand All @@ -20,6 +99,8 @@ def test_mcp_startup_degrades_when_endpoint_is_unreachable(
) -> None:
from bareloop.mcp_integration import client as mcp_client

monkeypatch.setenv("BARELOOP_ENABLE_MCP", "true")

async def fail_initialize(self, configs):
raise ConnectionError("offline")

Expand Down Expand Up @@ -47,6 +128,7 @@ def test_remote_mcp_token_requires_encrypted_transport(
) -> None:
from bareloop.mcp_integration import client as mcp_client

monkeypatch.setenv("BARELOOP_ENABLE_MCP", "true")
monkeypatch.setenv("MCP_REMOTE_URL", "http://example.com/mcp")
monkeypatch.setenv("MCP_REMOTE_TOKEN", "do-not-log-this-token")

Expand Down
Loading