feat: improve CRM MCP reliability

This commit is contained in:
nac
2026-07-13 02:56:36 +00:00
parent 3be6dee45e
commit dd129a90a4
9 changed files with 666 additions and 62 deletions
+96 -15
View File
@@ -32,17 +32,58 @@ class FakeNbClient:
],
"meta": {"count": 1},
}
if resource == "contacts":
return {
"data": [
{
"id": 2,
"name": "Alice Contact",
"phone": "+1 555 0100",
"email": "alice.contact@example.com",
"title": "Buyer",
"customer": [{"id": 1, "name": "Acme"}],
"kehulianxiren_client": [{"id": 1, "f_q2q60q7bqbg": "Acme China"}],
"createdAt": "2026-07-01T00:00:00.000Z",
"updatedAt": "2026-07-08T00:00:00.000Z",
}
],
"meta": {"count": 1},
}
if resource == "followups":
return {
"data": [
{
"id": 1,
"f_srysmjkwfq1": "2026-07-08T09:00:00.000Z",
"f_19iplxz0nds": "Called customer about sample status",
"f_19iplxz0nds": "Called customer about sample status and confirmed next procurement meeting.",
"gjjl_client": [{"id": 7, "f_q2q60q7bqbg": "Acme China"}],
"gjjl_client_contacts": [{"id": 8, "f_2zpg91gtmwp": "Alice Contact"}],
"gjjl_followup_person": [{"id": 54, "nickname": "Alice Wang"}],
"createdBy": {"id": 54, "nickname": "Alice Wang"},
"createdAt": "2026-07-08T09:10:00.000Z",
"updatedAt": "2026-07-08T09:20:00.000Z",
}
],
"meta": {"count": 1},
}
if resource == "customers":
return {
"data": [
{
"id": 1,
"name": "Acme",
"f_q2q60q7bqbg": "Acme China",
"f_kh_english_name": "Acme",
"f_territorial_name": "US",
"status": "kh_p_inprogress",
"kh_progress": "kh_p_inprogress",
"source": "客户推荐",
"f_225h6n6v654": "客户推荐",
"owner": [{"id": 54, "nickname": "Alice Wang"}],
"kehu_followup_person": [{"id": 54, "nickname": "Alice Wang"}],
"kehu_contacts": [{"id": 99, "name": "Nested contact that should stay out of compact results"}],
"createdAt": "2026-07-01T00:00:00.000Z",
"updatedAt": "2026-07-08T00:00:00.000Z",
}
],
"meta": {"count": 1},
@@ -58,9 +99,20 @@ class FakeNbClient:
dimensions = kwargs.get("dimensions") or []
alias = dimensions[0].get("alias") if dimensions else None
if alias in {"status", "kh_progress"}:
return {"data": [{"count": 3, "kh_progress": "kh_p_inprogress"}]}
return {
"data": [
{"count": 3, "kh_progress": "kh_p_inprogress"},
{"count": 9, "kh_progress": "kh_p_ordered"},
]
}
if alias in {"source", "f_225h6n6v654"}:
return {"data": [{"count": 2, "f_225h6n6v654": "客户推荐"}]}
return {
"data": [
{"count": 1, "f_225h6n6v654": "https://example.com"},
{"count": 9, "f_225h6n6v654": "客户推荐"},
{"count": 2, "f_225h6n6v654": ""},
]
}
if alias == "owner_id":
return {"data": [{"count": 1, "owner_id": 54}]}
if alias == "kehu_followup_person_id":
@@ -111,7 +163,12 @@ class CrmServiceTests(unittest.TestCase):
result = service.list_customers(query="Acme", status="active", owner="Alice", limit=10, offset=20)
self.assertEqual(result["results"], [{"id": 1, "name": "Acme"}])
self.assertEqual(result["results"][0]["id"], 1)
self.assertEqual(result["results"][0]["name"], "Acme China")
self.assertEqual(result["results"][0]["status_display"], "进行中")
self.assertEqual(result["results"][0]["owner_names"], ["Alice Wang"])
self.assertNotIn("kehu_contacts", result["results"][0])
self.assertNotIn("raw", result["results"][0])
self.assertEqual(result["total"], 1)
self.assertEqual(client.list_calls[0][0], "users")
resource, kwargs = client.list_calls[1]
@@ -143,9 +200,14 @@ class CrmServiceTests(unittest.TestCase):
self.assertEqual(result["customer"]["id"], 7)
self.assertEqual(result["customer"]["name"], "Acme")
self.assertEqual(result["contacts"], [{"id": 1, "name": "Acme"}])
self.assertEqual(result["contacts"][0]["id"], 2)
self.assertEqual(result["contacts"][0]["customer_names"], ["Acme"])
self.assertEqual(result["recent_followups"][0]["id"], 1)
self.assertEqual(result["recent_followups"][0]["summary"]["content"], "Called customer about sample status")
self.assertEqual(
result["recent_followups"][0]["content_preview"],
"Called customer about sample status and confirmed next procurement meeting.",
)
self.assertNotIn("f_19iplxz0nds", result["recent_followups"][0])
self.assertEqual(client.get_calls[0][0], "customers")
self.assertEqual(client.list_calls[0][0], "contacts")
self.assertEqual(client.list_calls[0][1]["filter"], {"$and": [{"customer": {"id": {"$eq": 7}}}]})
@@ -161,7 +223,8 @@ class CrmServiceTests(unittest.TestCase):
self.assertEqual(result["totals"]["customers"], 3)
self.assertEqual(result["totals"]["contacts"], 3)
self.assertEqual(result["totals"]["followups"], 3)
self.assertEqual(result["customer_status"][0]["display"], "进行中")
self.assertEqual(result["customer_status"][0]["display"], "已下单")
self.assertEqual(result["recent_followups"][0]["content_preview"], "Called customer about sample status and confirmed next procurement meeting.")
self.assertEqual(result["customer_owner"][0]["owner_id"], 54)
self.assertGreaterEqual(len(client.query_calls), 3)
self.assertEqual(client.query_calls[0][0], "customers")
@@ -299,11 +362,19 @@ class CrmServiceTests(unittest.TestCase):
client = FakeNbClient()
result = CrmService(load_config(None), client).crm_filter_options(owner_query="alice")
self.assertEqual(result["customer_status"][0]["value"], "kh_p_inprogress")
self.assertEqual(result["customer_status"][0]["label"], "进行中")
self.assertEqual(result["customer_status"][0]["value"], "kh_p_ordered")
self.assertEqual(result["customer_status"][0]["label"], "已下单")
self.assertEqual(result["customer_source"][0]["value"], "客户推荐")
self.assertEqual(result["customer_source"][-1]["value"], "")
self.assertEqual(result["owner_candidates"][0]["id"], 54)
def test_list_customers_can_opt_into_raw_rows(self) -> None:
result = CrmService(load_config(None), FakeNbClient()).list_customers(limit=1, include_raw=True)
row = result["results"][0]
self.assertEqual(row["name"], "Acme China")
self.assertEqual(row["raw"]["kehu_contacts"][0]["id"], 99)
def test_list_tools_clamp_limit_and_offset_for_remote_agents(self) -> None:
client = FakeNbClient()
service = CrmService(load_config(None), client)
@@ -315,15 +386,25 @@ class CrmServiceTests(unittest.TestCase):
self.assertEqual(client.list_calls[0][1]["page_size"], 100)
self.assertEqual(client.list_calls[0][1]["page"], 1)
def test_list_followups_adds_human_readable_summary_without_dropping_raw_fields(self) -> None:
def test_list_followups_returns_compact_preview_by_default(self) -> None:
result = CrmService(load_config(None), FakeNbClient()).list_followups(limit=1)
row = result["results"][0]
self.assertEqual(row["f_19iplxz0nds"], "Called customer about sample status")
self.assertEqual(row["summary"]["content"], "Called customer about sample status")
self.assertEqual(row["summary"]["followedAt"], "2026-07-08T09:00:00.000Z")
self.assertEqual(row["summary"]["customer_names"], ["Acme China"])
self.assertEqual(row["summary"]["owner_names"], ["Alice Wang"])
self.assertEqual(row["id"], 1)
self.assertEqual(row["content_preview"], "Called customer about sample status and confirmed next procurement meeting.")
self.assertEqual(row["followedAt"], "2026-07-08T09:00:00.000Z")
self.assertEqual(row["customer_names"], ["Acme China"])
self.assertEqual(row["owner_names"], ["Alice Wang"])
self.assertNotIn("f_19iplxz0nds", row)
self.assertNotIn("summary", row)
def test_list_followups_can_opt_into_raw_rows(self) -> None:
result = CrmService(load_config(None), FakeNbClient()).list_followups(limit=1, include_raw=True)
row = result["results"][0]
self.assertEqual(row["content_preview"], "Called customer about sample status and confirmed next procurement meeting.")
self.assertEqual(row["raw"]["f_19iplxz0nds"], "Called customer about sample status and confirmed next procurement meeting.")
self.assertEqual(row["raw"]["gjjl_client"][0]["f_q2q60q7bqbg"], "Acme China")
if __name__ == "__main__":
+82
View File
@@ -63,6 +63,7 @@ class McpServiceConfigTests(unittest.TestCase):
path="/mcp",
nb_env="nb-mcp",
config_path="config.json",
nb_bin="/opt/node/bin/nb",
)
content = env_path.read_text(encoding="utf-8")
@@ -72,9 +73,50 @@ class McpServiceConfigTests(unittest.TestCase):
self.assertIn("NOCOBASE_MCP_PATH=/mcp\n", content)
self.assertIn("NOCOBASE_MCP_ENV=nb-mcp\n", content)
self.assertIn("NOCOBASE_MCP_CONFIG=config.json\n", content)
self.assertIn("NOCOBASE_MCP_NB_BIN=/opt/node/bin/nb\n", content)
self.assertEqual(stat.S_IMODE(os.stat(env_path).st_mode), 0o600)
self.assertEqual(stat.S_IMODE(os.stat(env_path.parent).st_mode), 0o700)
def test_find_nb_path_uses_env_or_path_and_errors_when_missing(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
nb_bin = Path(tmp) / "bin" / "nb"
nb_bin.parent.mkdir()
nb_bin.write_text("#!/bin/sh\n", encoding="utf-8")
nb_bin.chmod(0o755)
with patch.dict("os.environ", {"NOCOBASE_MCP_NB_BIN": str(nb_bin)}):
self.assertEqual(manage_mcp_service.find_nb_path(), Path(os.path.abspath(nb_bin)))
cli_script = Path(tmp) / "lib" / "node_modules" / "@nocobase" / "cli" / "bin" / "run.js"
cli_script.parent.mkdir(parents=True)
cli_script.write_text("#!/usr/bin/env node\n", encoding="utf-8")
cli_script.chmod(0o755)
nb_link = Path(tmp) / "node" / "bin" / "nb"
nb_link.parent.mkdir(parents=True)
nb_link.symlink_to(cli_script)
with patch.dict("os.environ", {"NOCOBASE_MCP_NB_BIN": str(nb_link)}):
self.assertEqual(manage_mcp_service.find_nb_path(), nb_link)
missing_nb = Path(tmp) / "missing" / "nb"
with patch.dict("os.environ", {"NOCOBASE_MCP_NB_BIN": str(missing_nb)}):
with self.assertRaisesRegex(RuntimeError, "not an executable"):
manage_mcp_service.find_nb_path()
with patch.dict("os.environ", {"NOCOBASE_MCP_NB_BIN": "nb-custom"}), patch.object(
manage_mcp_service.shutil,
"which",
return_value="/usr/local/bin/nb-custom",
):
self.assertEqual(manage_mcp_service.find_nb_path(), Path("/usr/local/bin/nb-custom"))
with patch.dict("os.environ", {}, clear=True), patch.object(manage_mcp_service.shutil, "which", return_value="/usr/local/bin/nb"):
self.assertEqual(manage_mcp_service.find_nb_path(), Path("/usr/local/bin/nb"))
with patch.dict("os.environ", {}, clear=True), patch.object(manage_mcp_service.shutil, "which", return_value=None):
with self.assertRaisesRegex(RuntimeError, "Could not find nb"):
manage_mcp_service.find_nb_path()
def test_render_remote_config_prints_url_and_authorization_header(self) -> None:
output = manage_mcp_service.render_remote_config(
hosts=["192.168.1.10"],
@@ -100,6 +142,7 @@ class McpServiceConfigTests(unittest.TestCase):
patch.dict("os.environ", {"XDG_CONFIG_HOME": str(config_home)}),
patch.object(manage_mcp_service, "generate_token", return_value="new-token"),
patch.object(manage_mcp_service, "detect_remote_hosts", return_value=["10.0.0.2"]),
patch.object(manage_mcp_service, "find_nb_path", return_value=Path("/opt/node/bin/nb")),
patch.object(manage_mcp_service, "run_systemctl") as run_systemctl,
):
output = manage_mcp_service.new_token(project_root=project_root)
@@ -108,6 +151,7 @@ class McpServiceConfigTests(unittest.TestCase):
env_content = env_path.read_text(encoding="utf-8")
self.assertIn("NOCOBASE_MCP_TOKEN=new-token\n", env_content)
self.assertIn("NOCOBASE_MCP_PORT=10087\n", env_content)
self.assertIn("NOCOBASE_MCP_NB_BIN=/opt/node/bin/nb\n", env_content)
self.assertIn("http://10.0.0.2:10087/mcp", output)
run_systemctl.assert_not_called()
@@ -129,6 +173,7 @@ class McpServiceConfigTests(unittest.TestCase):
patch.dict("os.environ", {"XDG_CONFIG_HOME": str(config_home)}),
patch.object(manage_mcp_service, "detect_remote_hosts", return_value=["10.0.0.2"]),
patch.object(manage_mcp_service, "find_uv_path", return_value=Path("/home/nac/.local/bin/uv")),
patch.object(manage_mcp_service, "find_nb_path", return_value=Path("/opt/node/bin/nb")),
patch.object(manage_mcp_service, "run_systemctl") as run_systemctl,
patch.object(
manage_mcp_service,
@@ -141,8 +186,10 @@ class McpServiceConfigTests(unittest.TestCase):
unit_path = config_home / "systemd" / "user" / manage_mcp_service.SERVICE_NAME
unit_content = unit_path.read_text(encoding="utf-8")
env_content = (project_root / ".runtime" / "nocobase-crm-mcp.env").read_text(encoding="utf-8")
self.assertIn("/home/nac/.local/bin/uv run --no-sync nocobase-crm-mcp", unit_content)
self.assertIn("EnvironmentFile=", unit_content)
self.assertIn("NOCOBASE_MCP_NB_BIN=/opt/node/bin/nb\n", env_content)
self.assertIn("http://10.0.0.2:10087/mcp", output)
self.assertIn("Bearer saved-token", output)
run_systemctl.assert_has_calls(
@@ -165,6 +212,7 @@ class McpServiceConfigTests(unittest.TestCase):
patch.object(manage_mcp_service, "generate_token", return_value="first-token"),
patch.object(manage_mcp_service, "detect_remote_hosts", return_value=["10.0.0.2"]),
patch.object(manage_mcp_service, "find_uv_path", return_value=Path("/home/nac/.local/bin/uv")),
patch.object(manage_mcp_service, "find_nb_path", return_value=Path("/opt/node/bin/nb")),
patch.object(manage_mcp_service, "run_systemctl") as run_systemctl,
patch.object(
manage_mcp_service,
@@ -177,6 +225,7 @@ class McpServiceConfigTests(unittest.TestCase):
env_path = project_root / ".runtime" / "nocobase-crm-mcp.env"
self.assertIn("NOCOBASE_MCP_TOKEN=first-token\n", env_path.read_text(encoding="utf-8"))
self.assertIn("NOCOBASE_MCP_NB_BIN=/opt/node/bin/nb\n", env_path.read_text(encoding="utf-8"))
self.assertIn("Bearer first-token", output)
unit_path = config_home / "systemd" / "user" / manage_mcp_service.SERVICE_NAME
self.assertTrue(unit_path.exists())
@@ -190,6 +239,38 @@ class McpServiceConfigTests(unittest.TestCase):
)
probe_http_service.assert_called_once_with("127.0.0.1", 10087, "/mcp", token="first-token")
def test_start_service_waits_for_http_probe_after_systemd_is_active(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
project_root = Path(tmp) / "project"
project_root.mkdir()
config_home = Path(tmp) / "config"
manage_mcp_service.write_token_env_file(
project_root / ".runtime" / "nocobase-crm-mcp.env",
"saved-token",
)
with (
patch.dict("os.environ", {"XDG_CONFIG_HOME": str(config_home)}),
patch.object(manage_mcp_service, "detect_remote_hosts", return_value=["10.0.0.2"]),
patch.object(manage_mcp_service, "find_uv_path", return_value=Path("/home/nac/.local/bin/uv")),
patch.object(manage_mcp_service, "find_nb_path", return_value=Path("/opt/node/bin/nb")),
patch.object(manage_mcp_service, "run_systemctl"),
patch.object(manage_mcp_service.time, "sleep") as sleep,
patch.object(
manage_mcp_service,
"probe_http_service",
side_effect=[
{"reachable": False, "error": "connection refused"},
{"reachable": True, "status": 406},
],
create=True,
) as probe_http_service,
):
output = manage_mcp_service.start_service(project_root=project_root)
self.assertIn("Service status: active", output)
self.assertEqual(probe_http_service.call_count, 2)
sleep.assert_called_once()
def test_start_service_fails_when_systemd_does_not_become_active(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
project_root = Path(tmp) / "project"
@@ -208,6 +289,7 @@ class McpServiceConfigTests(unittest.TestCase):
with (
patch.dict("os.environ", {"XDG_CONFIG_HOME": str(config_home)}),
patch.object(manage_mcp_service, "find_uv_path", return_value=Path("/home/nac/.local/bin/uv")),
patch.object(manage_mcp_service, "find_nb_path", return_value=Path("/opt/node/bin/nb")),
patch.object(manage_mcp_service, "run_systemctl", side_effect=fake_systemctl),
):
with self.assertRaisesRegex(RuntimeError, "did not become active"):
+13
View File
@@ -86,6 +86,19 @@ class NbClientTests(unittest.TestCase):
self.assertIn("--orders", commands[1])
self.assertIn("--timezone", commands[1])
def test_absolute_nb_bin_prepends_its_directory_to_subprocess_path(self) -> None:
calls: list[dict] = []
def runner(cmd, *, env, **kwargs):
calls.append({"cmd": cmd, "env": env})
return subprocess.CompletedProcess(cmd, 0, stdout='{"data":[]}', stderr="")
with patch.dict(os.environ, {"PATH": "/usr/bin"}, clear=True):
NbClient(env_name="nb-mcp", nb_bin="/opt/node/bin/nb", runner=runner).list_records("customers")
self.assertEqual(calls[0]["cmd"][0], "/opt/node/bin/nb")
self.assertEqual(calls[0]["env"]["PATH"], "/opt/node/bin:/usr/bin")
def test_list_collection_fields_uses_data_modeling_command(self) -> None:
commands: list[list[str]] = []
+59
View File
@@ -2,6 +2,8 @@ import asyncio
import unittest
from unittest.mock import patch
from nocobase_crm_mcp import server as server_module
from nocobase_crm_mcp.nb_client import NbCommandError
from nocobase_crm_mcp.server import BearerTokenAuthMiddleware, FastMCP, create_http_app, create_server
@@ -59,6 +61,16 @@ class FakeCrmService:
return {"results": []}
class ErrorCrmService(FakeCrmService):
def list_customers(self, **kwargs):
raise NbCommandError("nb command failed with exit code 1: denied")
class MissingNbCrmService(FakeCrmService):
def crm_health(self):
raise FileNotFoundError(2, "No such file or directory", "nb")
class ServerTests(unittest.TestCase):
def test_bearer_token_middleware_rejects_missing_or_wrong_token(self) -> None:
app = BearerTokenAuthMiddleware(_ok_app, "secret")
@@ -103,6 +115,53 @@ class ServerTests(unittest.TestCase):
},
)
def test_tool_schemas_expose_raw_opt_in_parameters(self) -> None:
if FastMCP is None:
self.skipTest("MCP SDK is not installed")
server = create_server(crm_service=FakeCrmService(), readonly=True)
tools = {tool.name: tool for tool in asyncio.run(server.list_tools())}
self.assertIn("include_raw", tools["list_customers"].inputSchema["properties"])
self.assertIn("include_raw", tools["list_contacts"].inputSchema["properties"])
self.assertIn("include_raw", tools["list_followups"].inputSchema["properties"])
self.assertIn("include_raw_followups", tools["get_customer"].inputSchema["properties"])
def test_tools_return_structured_error_for_nb_failures(self) -> None:
if FastMCP is None:
self.skipTest("MCP SDK is not installed")
server = create_server(crm_service=ErrorCrmService(), readonly=True)
_content, structured = asyncio.run(server.call_tool("list_customers", {}))
self.assertEqual(structured["error"]["code"], "nb_command_failed")
self.assertIn("denied", structured["error"]["message"])
self.assertFalse(structured["error"]["retryable"])
def test_tools_return_specific_error_when_nb_is_not_found(self) -> None:
if FastMCP is None:
self.skipTest("MCP SDK is not installed")
server = create_server(crm_service=MissingNbCrmService(), readonly=True)
_content, structured = asyncio.run(server.call_tool("crm_health", {}))
self.assertEqual(structured["error"]["code"], "nb_not_found")
self.assertIn("NOCOBASE_MCP_NB_BIN", structured["error"]["hint"])
self.assertFalse(structured["error"]["retryable"])
def test_make_service_uses_nb_bin_from_environment(self) -> None:
with (
patch.dict("os.environ", {"NOCOBASE_MCP_NB_BIN": "/opt/node/bin/nb"}),
patch.object(server_module, "NbClient") as nb_client,
patch.object(server_module, "CrmService", side_effect=lambda config, client: {"config": config, "client": client}),
):
service = server_module._make_service()
self.assertIs(service["client"], nb_client.return_value)
nb_client.assert_called_once_with(env_name="nb-mcp", data_source="main", nb_bin="/opt/node/bin/nb")
def test_config_template_tool_is_opt_in(self) -> None:
if FastMCP is None:
self.skipTest("MCP SDK is not installed")