Initial NocoBase CRM MCP server
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from nocobase_crm_mcp.config import load_config
|
||||
from nocobase_crm_mcp.filters import (
|
||||
build_and_filter,
|
||||
build_date_range_condition,
|
||||
build_relation_id_condition,
|
||||
build_relation_id_or_condition,
|
||||
build_search_filter,
|
||||
)
|
||||
|
||||
|
||||
class ConfigTests(unittest.TestCase):
|
||||
def test_load_config_uses_crm_defaults(self) -> None:
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
config = load_config(None)
|
||||
|
||||
self.assertEqual(config.env_name, "nb-mcp")
|
||||
self.assertEqual(config.data_source, "main")
|
||||
self.assertEqual(config.customer.resource, "customers")
|
||||
self.assertEqual(config.contact.resource, "contacts")
|
||||
self.assertEqual(config.followup.resource, "followups")
|
||||
self.assertIn("name", config.customer.search_fields)
|
||||
self.assertEqual(config.contact.customer_field, "customer")
|
||||
self.assertEqual(config.followup.customer_field, "customer")
|
||||
|
||||
def test_load_config_merges_file_and_environment_overrides(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config_path = Path(tmp) / "crm.json"
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"env": "file-env",
|
||||
"dataSource": "analytics",
|
||||
"collections": {
|
||||
"customers": {
|
||||
"resource": "crmAccounts",
|
||||
"fields": ["id", "displayName"],
|
||||
"searchFields": ["displayName", "shortName"],
|
||||
},
|
||||
"contacts": {"resource": "crmContacts", "customerField": "account"},
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with patch.dict(os.environ, {"NOCOBASE_MCP_ENV": "env-override"}, clear=True):
|
||||
config = load_config(config_path)
|
||||
|
||||
self.assertEqual(config.env_name, "env-override")
|
||||
self.assertEqual(config.data_source, "analytics")
|
||||
self.assertEqual(config.customer.resource, "crmAccounts")
|
||||
self.assertEqual(config.customer.fields, ["id", "displayName"])
|
||||
self.assertEqual(config.customer.search_fields, ["displayName", "shortName"])
|
||||
self.assertEqual(config.contact.resource, "crmContacts")
|
||||
self.assertEqual(config.contact.customer_field, "account")
|
||||
self.assertEqual(config.followup.resource, "followups")
|
||||
|
||||
def test_load_config_supports_user_and_multiple_followup_owner_fields(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config_path = Path(tmp) / "crm.json"
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"users": {
|
||||
"resource": "staff",
|
||||
"fields": ["id", "username", "nickname"],
|
||||
"matchFields": ["username", "nickname"],
|
||||
},
|
||||
"collections": {
|
||||
"followups": {
|
||||
"ownerFields": ["participants", "createdBy"],
|
||||
},
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
config = load_config(config_path)
|
||||
|
||||
self.assertEqual(config.user.resource, "staff")
|
||||
self.assertEqual(config.user.fields, ["id", "username", "nickname"])
|
||||
self.assertEqual(config.user.match_fields, ["username", "nickname"])
|
||||
self.assertEqual(config.followup.owner_fields, ["participants", "createdBy"])
|
||||
|
||||
|
||||
class FilterBuilderTests(unittest.TestCase):
|
||||
def test_build_search_filter_uses_or_includes_conditions(self) -> None:
|
||||
self.assertEqual(
|
||||
build_search_filter("Acme", ["name", "code"]),
|
||||
{
|
||||
"$or": [
|
||||
{"name": {"$includes": "Acme"}},
|
||||
{"code": {"$includes": "Acme"}},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
def test_build_and_filter_wraps_conditions_and_skips_empty_values(self) -> None:
|
||||
result = build_and_filter(
|
||||
[
|
||||
{"status": {"$eq": "active"}},
|
||||
None,
|
||||
{},
|
||||
build_search_filter("Acme", ["name"]),
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
result,
|
||||
{
|
||||
"$and": [
|
||||
{"status": {"$eq": "active"}},
|
||||
{"$or": [{"name": {"$includes": "Acme"}}]},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
def test_build_date_range_condition_uses_nocobase_date_between(self) -> None:
|
||||
self.assertEqual(
|
||||
build_date_range_condition("followedAt", "2026-07-01", "2026-07-08"),
|
||||
{"followedAt": {"$dateBetween": ["2026-07-01", "2026-07-08"]}},
|
||||
)
|
||||
self.assertEqual(
|
||||
build_date_range_condition("followedAt", "2026-07-01", None),
|
||||
{"followedAt": {"$dateNotBefore": "2026-07-01"}},
|
||||
)
|
||||
self.assertEqual(
|
||||
build_date_range_condition("followedAt", None, "2026-07-08"),
|
||||
{"followedAt": {"$dateNotAfter": "2026-07-08"}},
|
||||
)
|
||||
|
||||
def test_build_relation_id_condition_supports_nested_dimension_paths(self) -> None:
|
||||
self.assertEqual(
|
||||
build_relation_id_condition("kehu_followup_person", 54),
|
||||
{"kehu_followup_person": {"id": {"$eq": 54}}},
|
||||
)
|
||||
self.assertEqual(
|
||||
build_relation_id_condition("kehu_followup_person.id", 54),
|
||||
{"kehu_followup_person": {"id": {"$eq": 54}}},
|
||||
)
|
||||
self.assertEqual(
|
||||
build_relation_id_condition(["kehu_followup_person", "id"], 54),
|
||||
{"kehu_followup_person": {"id": {"$eq": 54}}},
|
||||
)
|
||||
|
||||
def test_build_relation_id_or_condition_filters_multiple_owner_fields(self) -> None:
|
||||
self.assertEqual(
|
||||
build_relation_id_or_condition(["gjjl_followup_person", "createdBy"], 54),
|
||||
{
|
||||
"$or": [
|
||||
{"gjjl_followup_person": {"id": {"$eq": 54}}},
|
||||
{"createdBy": {"id": {"$eq": 54}}},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,330 @@
|
||||
import unittest
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from nocobase_crm_mcp.config import load_config
|
||||
from nocobase_crm_mcp.crm import CrmService
|
||||
|
||||
|
||||
class FakeNbClient:
|
||||
def __init__(self) -> None:
|
||||
self.list_calls = []
|
||||
self.get_calls = []
|
||||
self.query_calls = []
|
||||
self.field_calls = []
|
||||
|
||||
def health(self):
|
||||
return {"ok": True, "status": "reachable"}
|
||||
|
||||
def list_records(self, resource, **kwargs):
|
||||
self.list_calls.append((resource, kwargs))
|
||||
if resource == "users":
|
||||
return {
|
||||
"data": [
|
||||
{
|
||||
"id": 54,
|
||||
"username": "alice",
|
||||
"nickname": "Alice Wang",
|
||||
"email": "alice@example.com",
|
||||
"f_yh_english_name": "Alice Wang",
|
||||
}
|
||||
],
|
||||
"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",
|
||||
"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"},
|
||||
}
|
||||
],
|
||||
"meta": {"count": 1},
|
||||
}
|
||||
return {"data": [{"id": 1, "name": "Acme"}], "meta": {"count": 1}}
|
||||
|
||||
def get_record(self, resource, filter_by_tk, **kwargs):
|
||||
self.get_calls.append((resource, filter_by_tk, kwargs))
|
||||
return {"data": {"id": filter_by_tk, "name": "Acme", "f_q2q60q7bqbg": "Acme China"}}
|
||||
|
||||
def query_records(self, resource, **kwargs):
|
||||
self.query_calls.append((resource, kwargs))
|
||||
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"}]}
|
||||
if alias in {"source", "f_225h6n6v654"}:
|
||||
return {"data": [{"count": 2, "f_225h6n6v654": "客户推荐"}]}
|
||||
if alias == "owner_id":
|
||||
return {"data": [{"count": 1, "owner_id": 54}]}
|
||||
if alias == "kehu_followup_person_id":
|
||||
return {"data": [{"count": 1, "kehu_followup_person_id": 54}]}
|
||||
return {"data": [{"count": 3}]}
|
||||
|
||||
def list_collection_fields(self, collection_name, **kwargs):
|
||||
self.field_calls.append((collection_name, kwargs))
|
||||
if collection_name == "contacts":
|
||||
return {
|
||||
"data": [
|
||||
{"name": "id", "title": "ID", "type": "bigInt"},
|
||||
{"name": "f_2zpg91gtmwp", "title": "联系人姓名", "type": "string"},
|
||||
{"name": "khlxr_phone_number", "title": "联系人电话", "type": "string"},
|
||||
{"name": "khlxr_email", "title": "联系人邮箱", "type": "string"},
|
||||
{"name": "kehulianxiren_client", "title": "公司", "type": "belongsToMany"},
|
||||
]
|
||||
}
|
||||
if collection_name == "followups":
|
||||
return {
|
||||
"data": [
|
||||
{"name": "id", "title": "跟进ID", "type": "bigInt"},
|
||||
{"name": "gjjl_client", "title": "客户", "type": "belongsToMany"},
|
||||
{"name": "gjjl_client_contacts", "title": "客户联系人", "type": "belongsToMany"},
|
||||
{"name": "gjjl_followup_person", "title": "参与跟进人员", "type": "belongsToMany"},
|
||||
{"name": "createdBy", "title": "{{t(\"Created by\")}}", "type": "belongsTo"},
|
||||
{"name": "f_srysmjkwfq1", "title": "跟进时间", "type": "date"},
|
||||
{"name": "f_19iplxz0nds", "title": "跟进内容", "type": "text"},
|
||||
]
|
||||
}
|
||||
return {
|
||||
"data": [
|
||||
{"name": "id", "title": "ID", "type": "bigInt"},
|
||||
{"name": "f_q2q60q7bqbg", "title": "中文名称", "type": "string"},
|
||||
{"name": "f_kh_english_name", "title": "英文名称", "type": "string"},
|
||||
{"name": "f_territorial_name", "title": "属地名称", "type": "string"},
|
||||
{"name": "kh_progress", "title": "进度", "type": "string"},
|
||||
{"name": "f_225h6n6v654", "title": "客户来源", "type": "string"},
|
||||
{"name": "kehu_followup_person", "title": "跟进人", "type": "belongsToMany"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
class CrmServiceTests(unittest.TestCase):
|
||||
def test_list_customers_applies_configured_fields_and_filters(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
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["total"], 1)
|
||||
self.assertEqual(client.list_calls[0][0], "users")
|
||||
resource, kwargs = client.list_calls[1]
|
||||
self.assertEqual(resource, "customers")
|
||||
self.assertEqual(kwargs["fields"], load_config(None).customer.fields)
|
||||
self.assertEqual(kwargs["page_size"], 10)
|
||||
self.assertEqual(kwargs["page"], 3)
|
||||
self.assertEqual(
|
||||
kwargs["filter"],
|
||||
{
|
||||
"$and": [
|
||||
{"status": {"$eq": "active"}},
|
||||
{"owner": {"id": {"$eq": 54}}},
|
||||
{
|
||||
"$or": [
|
||||
{"name": {"$includes": "Acme"}},
|
||||
{"code": {"$includes": "Acme"}},
|
||||
]
|
||||
},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
def test_get_customer_loads_related_contacts_and_followups(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
result = service.get_customer(7, include_contacts=True, include_recent_followups=True, followup_limit=5)
|
||||
|
||||
self.assertEqual(result["customer"]["id"], 7)
|
||||
self.assertEqual(result["customer"]["name"], "Acme")
|
||||
self.assertEqual(result["contacts"], [{"id": 1, "name": "Acme"}])
|
||||
self.assertEqual(result["recent_followups"][0]["id"], 1)
|
||||
self.assertEqual(result["recent_followups"][0]["summary"]["content"], "Called customer about sample status")
|
||||
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}}}]})
|
||||
self.assertEqual(client.list_calls[1][0], "followups")
|
||||
self.assertEqual(client.list_calls[1][1]["page_size"], 5)
|
||||
|
||||
def test_crm_overview_uses_count_and_group_queries(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
result = service.crm_overview(owner="Alice")
|
||||
|
||||
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_owner"][0]["owner_id"], 54)
|
||||
self.assertGreaterEqual(len(client.query_calls), 3)
|
||||
self.assertEqual(client.query_calls[0][0], "customers")
|
||||
self.assertEqual(client.query_calls[0][1]["measures"][0]["aggregation"], "count")
|
||||
|
||||
def test_crm_schema_include_fields_reads_each_configured_collection_fields(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
schema = service.crm_schema(include_fields=True)
|
||||
|
||||
self.assertEqual(
|
||||
[call[0] for call in client.field_calls],
|
||||
["customers", "contacts", "followups"],
|
||||
)
|
||||
self.assertEqual(client.field_calls[0][1].get("fields"), None)
|
||||
self.assertEqual(schema["metadata"]["fields"]["customers"][1]["name"], "f_q2q60q7bqbg")
|
||||
self.assertEqual(schema["metadata"]["field_errors"], {})
|
||||
|
||||
def test_crm_schema_include_fields_reports_metadata_acl_hint(self) -> None:
|
||||
class ForbiddenFieldsClient(FakeNbClient):
|
||||
def list_collection_fields(self, collection_name, **kwargs):
|
||||
raise Exception("Request failed with status 403: No permissions")
|
||||
|
||||
service = CrmService(load_config(None), ForbiddenFieldsClient())
|
||||
|
||||
schema = service.crm_schema(include_fields=True)
|
||||
|
||||
self.assertIn("metadata_permission_required", schema["metadata"]["field_errors"]["customers"]["code"])
|
||||
self.assertIn("data-modeling collections fields list", schema["metadata"]["field_errors"]["customers"]["hint"])
|
||||
|
||||
def test_crm_config_template_infers_mapping_from_metadata(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
template = service.crm_config_template()
|
||||
|
||||
self.assertEqual(
|
||||
template["collections"]["customers"]["searchFields"],
|
||||
["f_q2q60q7bqbg", "f_kh_english_name", "f_territorial_name"],
|
||||
)
|
||||
self.assertEqual(template["collections"]["customers"]["statusField"], "kh_progress")
|
||||
self.assertEqual(template["collections"]["customers"]["sourceField"], "f_225h6n6v654")
|
||||
self.assertEqual(template["collections"]["customers"]["ownerField"], "kehu_followup_person")
|
||||
self.assertEqual(template["collections"]["contacts"]["customerField"], "kehulianxiren_client")
|
||||
self.assertEqual(template["collections"]["followups"]["customerField"], "gjjl_client")
|
||||
self.assertEqual(template["collections"]["followups"]["contactField"], "gjjl_client_contacts")
|
||||
self.assertEqual(template["collections"]["followups"]["ownerFields"], ["gjjl_followup_person", "createdBy"])
|
||||
self.assertEqual(template["collections"]["followups"]["dateField"], "f_srysmjkwfq1")
|
||||
|
||||
def test_list_customers_resolves_owner_name_to_relation_id_filter(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
service.list_customers(owner="alice")
|
||||
|
||||
self.assertEqual(client.list_calls[0][0], "users")
|
||||
self.assertEqual(
|
||||
client.list_calls[1][1]["filter"],
|
||||
{"$and": [{"owner": {"id": {"$eq": 54}}}]},
|
||||
)
|
||||
|
||||
def test_list_followups_filters_owner_by_participant_or_creator(self) -> None:
|
||||
client = FakeNbClient()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config_path = Path(tmp) / "crm.json"
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"collections": {
|
||||
"followups": {
|
||||
"ownerFields": ["gjjl_followup_person", "createdBy"],
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
service = CrmService(load_config(config_path), client)
|
||||
|
||||
service.list_followups(owner="alice")
|
||||
|
||||
self.assertEqual(client.list_calls[0][0], "users")
|
||||
self.assertEqual(
|
||||
client.list_calls[1][1]["filter"],
|
||||
{
|
||||
"$and": [
|
||||
{
|
||||
"$or": [
|
||||
{"gjjl_followup_person": {"id": {"$eq": 54}}},
|
||||
{"createdBy": {"id": {"$eq": 54}}},
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
def test_owner_resolution_returns_structured_errors_for_no_or_ambiguous_matches(self) -> None:
|
||||
class NoUserClient(FakeNbClient):
|
||||
def list_records(self, resource, **kwargs):
|
||||
self.list_calls.append((resource, kwargs))
|
||||
if resource == "users":
|
||||
return {"data": [], "meta": {"count": 0}}
|
||||
return super().list_records(resource, **kwargs)
|
||||
|
||||
missing = CrmService(load_config(None), NoUserClient()).list_customers(owner="missing")
|
||||
self.assertEqual(missing["error"]["code"], "owner_not_found")
|
||||
self.assertEqual(missing["error"]["query"], "missing")
|
||||
|
||||
class AmbiguousUserClient(FakeNbClient):
|
||||
def list_records(self, resource, **kwargs):
|
||||
self.list_calls.append((resource, kwargs))
|
||||
if resource == "users":
|
||||
return {
|
||||
"data": [
|
||||
{"id": 1, "username": "alice", "nickname": "Alice"},
|
||||
{"id": 2, "username": "alice2", "nickname": "Alice"},
|
||||
],
|
||||
"meta": {"count": 2},
|
||||
}
|
||||
return super().list_records(resource, **kwargs)
|
||||
|
||||
ambiguous = CrmService(load_config(None), AmbiguousUserClient()).list_customers(owner="alice")
|
||||
self.assertEqual(ambiguous["error"]["code"], "owner_ambiguous")
|
||||
self.assertEqual(len(ambiguous["error"]["candidates"]), 2)
|
||||
|
||||
def test_resolve_owner_returns_candidate_users(self) -> None:
|
||||
result = CrmService(load_config(None), FakeNbClient()).resolve_owner("alice")
|
||||
|
||||
self.assertEqual(result["query"], "alice")
|
||||
self.assertEqual(result["results"][0]["id"], 54)
|
||||
self.assertEqual(result["results"][0]["label"], "Alice Wang")
|
||||
|
||||
def test_crm_filter_options_exposes_filter_values_and_owner_candidates(self) -> None:
|
||||
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_source"][0]["value"], "客户推荐")
|
||||
self.assertEqual(result["owner_candidates"][0]["id"], 54)
|
||||
|
||||
def test_list_tools_clamp_limit_and_offset_for_remote_agents(self) -> None:
|
||||
client = FakeNbClient()
|
||||
service = CrmService(load_config(None), client)
|
||||
|
||||
result = service.list_customers(limit=10000, offset=-50)
|
||||
|
||||
self.assertEqual(result["limit"], 100)
|
||||
self.assertEqual(result["offset"], 0)
|
||||
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:
|
||||
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"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,264 @@
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import call, patch
|
||||
|
||||
import sys
|
||||
|
||||
SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
|
||||
if str(SCRIPTS_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS_DIR))
|
||||
|
||||
import manage_mcp_service
|
||||
|
||||
|
||||
class McpServiceConfigTests(unittest.TestCase):
|
||||
def test_service_management_has_one_shell_entrypoint(self) -> None:
|
||||
entrypoint = SCRIPTS_DIR / "mcp_service.sh"
|
||||
|
||||
self.assertTrue(entrypoint.exists())
|
||||
content = entrypoint.read_text(encoding="utf-8")
|
||||
self.assertIn("manage_mcp_service.py", content)
|
||||
self.assertIn('exec python3 "$PROJECT_ROOT/scripts/manage_mcp_service.py"', content)
|
||||
self.assertFalse((SCRIPTS_DIR / "new_mcp_service_token.sh").exists())
|
||||
self.assertFalse((SCRIPTS_DIR / "start_mcp_service.sh").exists())
|
||||
self.assertFalse((SCRIPTS_DIR / "show_mcp_service_config.sh").exists())
|
||||
self.assertFalse((SCRIPTS_DIR / "stop_mcp_service.sh").exists())
|
||||
self.assertFalse((SCRIPTS_DIR / "uninstall_mcp_service.sh").exists())
|
||||
|
||||
def test_missing_env_message_points_to_start_and_token_rotation(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env_path = Path(tmp) / ".runtime" / "nocobase-crm-mcp.env"
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, r"scripts/mcp_service\.sh start"):
|
||||
manage_mcp_service.read_service_env_file(env_path)
|
||||
|
||||
def test_render_service_unit_uses_http_defaults_without_embedding_token(self) -> None:
|
||||
unit = manage_mcp_service.render_service_unit(
|
||||
project_root=Path("/opt/nocobase-mcp"),
|
||||
env_file=Path("/opt/nocobase-mcp/.runtime/nocobase-crm-mcp.env"),
|
||||
uv_path=Path("/home/nac/.local/bin/uv"),
|
||||
)
|
||||
|
||||
self.assertIn("WorkingDirectory=/opt/nocobase-mcp", unit)
|
||||
self.assertIn("EnvironmentFile=/opt/nocobase-mcp/.runtime/nocobase-crm-mcp.env", unit)
|
||||
self.assertIn("/home/nac/.local/bin/uv run --no-sync nocobase-crm-mcp", unit)
|
||||
self.assertIn("--transport streamable-http", unit)
|
||||
self.assertIn("--host 0.0.0.0", unit)
|
||||
self.assertIn("--port 10087", unit)
|
||||
self.assertNotIn("NOCOBASE_MCP_TOKEN=", unit)
|
||||
|
||||
def test_write_token_env_file_is_private_and_contains_runtime_settings(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env_path = Path(tmp) / ".runtime" / "nocobase-crm-mcp.env"
|
||||
|
||||
manage_mcp_service.write_token_env_file(
|
||||
env_path,
|
||||
"test-token",
|
||||
host="0.0.0.0",
|
||||
port=10087,
|
||||
path="/mcp",
|
||||
nb_env="nb-mcp",
|
||||
config_path="config.json",
|
||||
)
|
||||
|
||||
content = env_path.read_text(encoding="utf-8")
|
||||
self.assertIn("NOCOBASE_MCP_TOKEN=test-token\n", content)
|
||||
self.assertIn("NOCOBASE_MCP_HOST=0.0.0.0\n", content)
|
||||
self.assertIn("NOCOBASE_MCP_PORT=10087\n", content)
|
||||
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.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_render_remote_config_prints_url_and_authorization_header(self) -> None:
|
||||
output = manage_mcp_service.render_remote_config(
|
||||
hosts=["192.168.1.10"],
|
||||
token="test-token",
|
||||
port=10087,
|
||||
path="/mcp",
|
||||
service_status="inactive",
|
||||
)
|
||||
|
||||
self.assertIn("http://192.168.1.10:10087/mcp", output)
|
||||
self.assertIn("Authorization: Bearer test-token", output)
|
||||
self.assertIn('"nocobase-crm"', output)
|
||||
self.assertIn('"type": "streamable-http"', output)
|
||||
self.assertIn("Service status: inactive", output)
|
||||
self.assertNotIn("MCP service is running.", output)
|
||||
|
||||
def test_new_token_writes_token_without_touching_systemd_when_service_is_not_installed(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
project_root = Path(tmp) / "project"
|
||||
project_root.mkdir()
|
||||
config_home = Path(tmp) / "config"
|
||||
with (
|
||||
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, "run_systemctl") as run_systemctl,
|
||||
):
|
||||
output = manage_mcp_service.new_token(project_root=project_root)
|
||||
|
||||
env_path = project_root / ".runtime" / "nocobase-crm-mcp.env"
|
||||
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("http://10.0.0.2:10087/mcp", output)
|
||||
run_systemctl.assert_not_called()
|
||||
|
||||
def test_start_service_uses_saved_token_and_restarts_service(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",
|
||||
host="0.0.0.0",
|
||||
port=10087,
|
||||
path="/mcp",
|
||||
nb_env="nb-mcp",
|
||||
config_path="config.json",
|
||||
)
|
||||
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, "run_systemctl") as run_systemctl,
|
||||
patch.object(
|
||||
manage_mcp_service,
|
||||
"probe_http_service",
|
||||
return_value={"reachable": True, "status": 401},
|
||||
create=True,
|
||||
) as probe_http_service,
|
||||
):
|
||||
output = manage_mcp_service.start_service(project_root=project_root)
|
||||
|
||||
unit_path = config_home / "systemd" / "user" / manage_mcp_service.SERVICE_NAME
|
||||
unit_content = unit_path.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("http://10.0.0.2:10087/mcp", output)
|
||||
self.assertIn("Bearer saved-token", output)
|
||||
run_systemctl.assert_has_calls(
|
||||
[
|
||||
call(["daemon-reload"]),
|
||||
call(["enable", manage_mcp_service.SERVICE_NAME]),
|
||||
call(["restart", manage_mcp_service.SERVICE_NAME]),
|
||||
call(["is-active", "--quiet", manage_mcp_service.SERVICE_NAME]),
|
||||
]
|
||||
)
|
||||
probe_http_service.assert_called_once_with("127.0.0.1", 10087, "/mcp", token="saved-token")
|
||||
|
||||
def test_start_service_generates_token_on_first_run(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
project_root = Path(tmp) / "project"
|
||||
project_root.mkdir()
|
||||
config_home = Path(tmp) / "config"
|
||||
with (
|
||||
patch.dict("os.environ", {"XDG_CONFIG_HOME": str(config_home)}),
|
||||
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, "run_systemctl") as run_systemctl,
|
||||
patch.object(
|
||||
manage_mcp_service,
|
||||
"probe_http_service",
|
||||
return_value={"reachable": True, "status": 401},
|
||||
create=True,
|
||||
) as probe_http_service,
|
||||
):
|
||||
output = manage_mcp_service.start_service(project_root=project_root)
|
||||
|
||||
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("Bearer first-token", output)
|
||||
unit_path = config_home / "systemd" / "user" / manage_mcp_service.SERVICE_NAME
|
||||
self.assertTrue(unit_path.exists())
|
||||
run_systemctl.assert_has_calls(
|
||||
[
|
||||
call(["daemon-reload"]),
|
||||
call(["enable", manage_mcp_service.SERVICE_NAME]),
|
||||
call(["restart", manage_mcp_service.SERVICE_NAME]),
|
||||
call(["is-active", "--quiet", manage_mcp_service.SERVICE_NAME]),
|
||||
]
|
||||
)
|
||||
probe_http_service.assert_called_once_with("127.0.0.1", 10087, "/mcp", token="first-token")
|
||||
|
||||
def test_start_service_fails_when_systemd_does_not_become_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",
|
||||
)
|
||||
|
||||
def fake_systemctl(args, *, check=True):
|
||||
if args[:2] == ["is-active", "--quiet"]:
|
||||
raise subprocess.CalledProcessError(3, ["systemctl", "--user", *args])
|
||||
return subprocess.CompletedProcess(["systemctl", "--user", *args], 0)
|
||||
|
||||
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, "run_systemctl", side_effect=fake_systemctl),
|
||||
):
|
||||
with self.assertRaisesRegex(RuntimeError, "did not become active"):
|
||||
manage_mcp_service.start_service(project_root=project_root)
|
||||
|
||||
def test_show_config_reports_saved_config_not_running_claim(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
project_root = Path(tmp) / "project"
|
||||
project_root.mkdir()
|
||||
manage_mcp_service.write_token_env_file(
|
||||
project_root / ".runtime" / "nocobase-crm-mcp.env",
|
||||
"saved-token",
|
||||
)
|
||||
with (
|
||||
patch.object(manage_mcp_service, "detect_remote_hosts", return_value=["10.0.0.2"]),
|
||||
patch.object(manage_mcp_service, "service_state", return_value="inactive", create=True),
|
||||
):
|
||||
output = manage_mcp_service.show_config(project_root)
|
||||
|
||||
self.assertIn("Saved MCP client config.", output)
|
||||
self.assertIn("Service status: inactive", output)
|
||||
self.assertNotIn("MCP service is running.", output)
|
||||
|
||||
def test_service_status_output_includes_paths_url_and_probe_state(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
project_root = Path(tmp) / "project"
|
||||
project_root.mkdir()
|
||||
manage_mcp_service.write_token_env_file(
|
||||
project_root / ".runtime" / "nocobase-crm-mcp.env",
|
||||
"saved-token",
|
||||
port=10087,
|
||||
path="/mcp",
|
||||
)
|
||||
with (
|
||||
patch.object(manage_mcp_service, "detect_remote_hosts", return_value=["10.0.0.2"]),
|
||||
patch.object(manage_mcp_service, "service_state", return_value="active", create=True),
|
||||
patch.object(
|
||||
manage_mcp_service,
|
||||
"probe_http_service",
|
||||
return_value={"reachable": True, "status": 401},
|
||||
create=True,
|
||||
),
|
||||
):
|
||||
output = manage_mcp_service.service_status(project_root=project_root)
|
||||
|
||||
self.assertIn("Service status: active", output)
|
||||
self.assertIn("Unit file:", output)
|
||||
self.assertIn("Env file:", output)
|
||||
self.assertIn("http://10.0.0.2:10087/mcp", output)
|
||||
self.assertIn("HTTP probe: reachable", output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,171 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from nocobase_crm_mcp.nb_client import NbClient, NbCommandError
|
||||
|
||||
|
||||
class NbClientTests(unittest.TestCase):
|
||||
def test_list_records_builds_safe_nb_command_and_environment(self) -> None:
|
||||
calls: list[dict] = []
|
||||
|
||||
def runner(cmd, *, cwd, env, timeout, capture_output, text, check):
|
||||
calls.append(
|
||||
{
|
||||
"cmd": cmd,
|
||||
"cwd": cwd,
|
||||
"env": env,
|
||||
"timeout": timeout,
|
||||
"capture_output": capture_output,
|
||||
"text": text,
|
||||
"check": check,
|
||||
}
|
||||
)
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout='{"data":[{"id":1}],"meta":{"count":1}}', stderr="")
|
||||
|
||||
client = NbClient(env_name="nb-mcp", data_source="main", runner=runner)
|
||||
|
||||
result = client.list_records(
|
||||
"customers",
|
||||
filter={"$and": [{"status": {"$eq": "active"}}]},
|
||||
fields=["id", "name"],
|
||||
sort=["-updatedAt"],
|
||||
page=2,
|
||||
page_size=20,
|
||||
)
|
||||
|
||||
self.assertEqual(result["data"], [{"id": 1}])
|
||||
command = calls[0]["cmd"]
|
||||
self.assertEqual(command[:4], ["nb", "api", "resource", "list"])
|
||||
self.assertIn("--resource", command)
|
||||
self.assertIn("customers", command)
|
||||
self.assertIn("--env", command)
|
||||
self.assertIn("nb-mcp", command)
|
||||
self.assertIn("--yes", command)
|
||||
self.assertIn("--json-output", command)
|
||||
self.assertIn("--data-source", command)
|
||||
self.assertIn("main", command)
|
||||
self.assertIn("--filter", command)
|
||||
self.assertIn(json.dumps({"$and": [{"status": {"$eq": "active"}}]}, separators=(",", ":")), command)
|
||||
self.assertIn("--fields", command)
|
||||
self.assertIn("id", command)
|
||||
self.assertIn("--sort", command)
|
||||
self.assertIn("-updatedAt", command)
|
||||
self.assertEqual(calls[0]["env"]["NB_CLI_LOG_DISABLED"], "1")
|
||||
self.assertEqual(calls[0]["env"]["NB_SKIP_STARTUP_UPDATE"], "1")
|
||||
self.assertTrue(calls[0]["capture_output"])
|
||||
self.assertTrue(calls[0]["text"])
|
||||
self.assertFalse(calls[0]["check"])
|
||||
|
||||
def test_get_record_and_query_records_use_expected_commands(self) -> None:
|
||||
commands: list[list[str]] = []
|
||||
|
||||
def runner(cmd, **kwargs):
|
||||
commands.append(cmd)
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout='{"data":[]}', stderr="")
|
||||
|
||||
client = NbClient(env_name="nb-mcp", runner=runner)
|
||||
client.get_record("customers", 7, fields=["id"])
|
||||
client.query_records(
|
||||
"customers",
|
||||
measures=[{"field": ["id"], "aggregation": "count", "alias": "count"}],
|
||||
dimensions=[{"field": ["status"], "alias": "status"}],
|
||||
orders=[{"field": ["status"], "alias": "status", "order": "asc"}],
|
||||
limit=10,
|
||||
timezone="+08:00",
|
||||
)
|
||||
|
||||
self.assertEqual(commands[0][:4], ["nb", "api", "resource", "get"])
|
||||
self.assertIn("--filter-by-tk", commands[0])
|
||||
self.assertIn("7", commands[0])
|
||||
self.assertEqual(commands[1][:4], ["nb", "api", "resource", "query"])
|
||||
self.assertIn("--measures", commands[1])
|
||||
self.assertIn("--dimensions", commands[1])
|
||||
self.assertIn("--orders", commands[1])
|
||||
self.assertIn("--timezone", commands[1])
|
||||
|
||||
def test_list_collection_fields_uses_data_modeling_command(self) -> None:
|
||||
commands: list[list[str]] = []
|
||||
|
||||
def runner(cmd, **kwargs):
|
||||
commands.append(cmd)
|
||||
return subprocess.CompletedProcess(
|
||||
cmd,
|
||||
0,
|
||||
stdout='{"data":[{"name":"f_customer_name","title":"客户名称","interface":"input"}]}',
|
||||
stderr="",
|
||||
)
|
||||
|
||||
result = NbClient(env_name="nb-mcp", runner=runner).list_collection_fields("t_nt3pjadelqi")
|
||||
|
||||
self.assertEqual(result["data"][0]["name"], "f_customer_name")
|
||||
self.assertEqual(
|
||||
commands[0][:6],
|
||||
["nb", "api", "data-modeling", "collections", "fields", "list"],
|
||||
)
|
||||
self.assertIn("--collection-name", commands[0])
|
||||
self.assertIn("t_nt3pjadelqi", commands[0])
|
||||
self.assertIn("--env", commands[0])
|
||||
self.assertIn("nb-mcp", commands[0])
|
||||
self.assertIn("--yes", commands[0])
|
||||
self.assertIn("--json-output", commands[0])
|
||||
|
||||
def test_get_collection_uses_data_modeling_command(self) -> None:
|
||||
commands: list[list[str]] = []
|
||||
|
||||
def runner(cmd, **kwargs):
|
||||
commands.append(cmd)
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout='{"data":{"name":"t_nt3pjadelqi"}}', stderr="")
|
||||
|
||||
NbClient(env_name="nb-mcp", runner=runner).get_collection("t_nt3pjadelqi", appends=["fields"])
|
||||
|
||||
self.assertEqual(commands[0][:5], ["nb", "api", "data-modeling", "collections", "get"])
|
||||
self.assertIn("--filter-by-tk", commands[0])
|
||||
self.assertIn("t_nt3pjadelqi", commands[0])
|
||||
self.assertIn("--appends", commands[0])
|
||||
self.assertIn("fields", commands[0])
|
||||
|
||||
def test_command_errors_redact_api_token(self) -> None:
|
||||
def runner(cmd, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
cmd,
|
||||
1,
|
||||
stdout="",
|
||||
stderr="Authorization failed for Bearer super-secret-token and --token super-secret-token",
|
||||
)
|
||||
|
||||
client = NbClient(env_name="nb-mcp", api_token="super-secret-token", runner=runner)
|
||||
|
||||
with self.assertRaises(NbCommandError) as caught:
|
||||
client.list_records("customers")
|
||||
|
||||
message = str(caught.exception)
|
||||
self.assertNotIn("super-secret-token", message)
|
||||
self.assertIn("<redacted>", message)
|
||||
|
||||
def test_invalid_json_output_raises_command_error(self) -> None:
|
||||
def runner(cmd, **kwargs):
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout="HTTP 200", stderr="")
|
||||
|
||||
client = NbClient(env_name="nb-mcp", runner=runner)
|
||||
|
||||
with self.assertRaises(NbCommandError):
|
||||
client.list_records("customers")
|
||||
|
||||
def test_environment_overrides_can_change_nb_home_without_shell(self) -> None:
|
||||
captured_env = {}
|
||||
|
||||
def runner(cmd, *, env, **kwargs):
|
||||
captured_env.update(env)
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout='{"data":[]}', stderr="")
|
||||
|
||||
with patch.dict(os.environ, {"NB_CLI_ROOT": "/tmp/custom-nb-root"}, clear=True):
|
||||
NbClient(env_name="nb-mcp", runner=runner).list_records("customers")
|
||||
|
||||
self.assertEqual(captured_env["NB_CLI_ROOT"], "/tmp/custom-nb-root")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,126 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from nocobase_crm_mcp.server import BearerTokenAuthMiddleware, FastMCP, create_http_app, create_server
|
||||
|
||||
|
||||
async def _ok_app(scope, receive, send):
|
||||
await send({"type": "http.response.start", "status": 200, "headers": []})
|
||||
await send({"type": "http.response.body", "body": b"ok"})
|
||||
|
||||
|
||||
def run_asgi_request(app, *, authorization=None, method="POST", path="/mcp"):
|
||||
events = []
|
||||
headers = []
|
||||
if authorization is not None:
|
||||
headers.append((b"authorization", authorization.encode("latin1")))
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": b"", "more_body": False}
|
||||
|
||||
async def send(message):
|
||||
events.append(message)
|
||||
|
||||
scope = {"type": "http", "method": method, "path": path, "headers": headers}
|
||||
asyncio.run(app(scope, receive, send))
|
||||
return events
|
||||
|
||||
|
||||
class FakeCrmService:
|
||||
def crm_health(self):
|
||||
return {"ok": True}
|
||||
|
||||
def crm_schema(self, include_fields=False):
|
||||
return {"include_fields": include_fields}
|
||||
|
||||
def crm_overview(self, **kwargs):
|
||||
return {"totals": {"customers": 1}}
|
||||
|
||||
def crm_config_template(self):
|
||||
return {"collections": {}}
|
||||
|
||||
def crm_filter_options(self, **kwargs):
|
||||
return {"customer_status": []}
|
||||
|
||||
def resolve_owner(self, **kwargs):
|
||||
return {"results": []}
|
||||
|
||||
def list_customers(self, **kwargs):
|
||||
return {"results": []}
|
||||
|
||||
def get_customer(self, **kwargs):
|
||||
return {"customer": None}
|
||||
|
||||
def list_contacts(self, **kwargs):
|
||||
return {"results": []}
|
||||
|
||||
def list_followups(self, **kwargs):
|
||||
return {"results": []}
|
||||
|
||||
|
||||
class ServerTests(unittest.TestCase):
|
||||
def test_bearer_token_middleware_rejects_missing_or_wrong_token(self) -> None:
|
||||
app = BearerTokenAuthMiddleware(_ok_app, "secret")
|
||||
|
||||
self.assertEqual(run_asgi_request(app)[0]["status"], 401)
|
||||
self.assertEqual(run_asgi_request(app, authorization="Bearer wrong")[0]["status"], 401)
|
||||
|
||||
def test_bearer_token_middleware_allows_matching_token(self) -> None:
|
||||
app = BearerTokenAuthMiddleware(_ok_app, "secret")
|
||||
|
||||
events = run_asgi_request(app, authorization="Bearer secret")
|
||||
|
||||
self.assertEqual(events[0]["status"], 200)
|
||||
self.assertEqual(events[1]["body"], b"ok")
|
||||
|
||||
def test_bearer_token_middleware_allows_options_preflight_without_token(self) -> None:
|
||||
app = BearerTokenAuthMiddleware(_ok_app, "secret")
|
||||
|
||||
events = run_asgi_request(app, method="OPTIONS")
|
||||
|
||||
self.assertEqual(events[0]["status"], 204)
|
||||
|
||||
def test_readonly_server_exposes_crm_tools_only(self) -> None:
|
||||
if FastMCP is None:
|
||||
self.skipTest("MCP SDK is not installed")
|
||||
|
||||
server = create_server(crm_service=FakeCrmService(), readonly=True)
|
||||
tools = asyncio.run(server.list_tools())
|
||||
|
||||
self.assertEqual(
|
||||
{tool.name for tool in tools},
|
||||
{
|
||||
"crm_health",
|
||||
"crm_schema",
|
||||
"crm_overview",
|
||||
"crm_filter_options",
|
||||
"resolve_owner",
|
||||
"list_customers",
|
||||
"get_customer",
|
||||
"list_contacts",
|
||||
"list_followups",
|
||||
},
|
||||
)
|
||||
|
||||
def test_config_template_tool_is_opt_in(self) -> None:
|
||||
if FastMCP is None:
|
||||
self.skipTest("MCP SDK is not installed")
|
||||
|
||||
with patch.dict("os.environ", {"NOCOBASE_MCP_ENABLE_CONFIG_TOOLS": "1"}):
|
||||
server = create_server(crm_service=FakeCrmService(), readonly=True)
|
||||
tools = asyncio.run(server.list_tools())
|
||||
|
||||
self.assertIn("crm_config_template", {tool.name for tool in tools})
|
||||
|
||||
def test_create_http_app_requires_bearer_token(self) -> None:
|
||||
if FastMCP is None:
|
||||
self.skipTest("MCP SDK is not installed")
|
||||
|
||||
server = create_server(crm_service=FakeCrmService(), readonly=True)
|
||||
with self.assertRaises(ValueError):
|
||||
create_http_app(server, "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user