test_used_car_api.py
8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""二手车三个接口的出入参,逐字对照《大数据 MCP 接口规范》v1.4。
**这是本文件存在的唯一理由**:断言实际发出去的请求体键名**恰好等于**规范
第 2/3/4 节列出的那几个,多一个键就失败。规范 v1.3 移除了接口一、二的
`brand` 品牌筛选,这类「文档改了但代码没跟上」的漂移只有靠这种精确断言才拦得住。
"""
from __future__ import annotations
import json
import httpx
import pytest
import respx
from mcp.server.fastmcp.exceptions import ToolError
from mcp_hive.core.mcp.host import build_instance
from mcp_hive.core.registry import get_manifest
from mcp_hive.services.used_car import api_client
BASE = "http://upstream.test/facade"
@pytest.fixture
async def service(app_settings, fake_credentials):
instance = build_instance(get_manifest("used_car"), app_settings)
assert instance.ok, instance.error
async with api_client.lifespan():
yield instance
def sent_body(route) -> dict:
"""取出这条路由收到的第一个请求的 JSON 请求体。"""
return json.loads(route.calls[0].request.content)
@pytest.fixture
def upstream():
"""把三个接口都打桩成空结果,返回 {路径: route}。"""
with respx.mock(base_url=BASE, assert_all_called=False) as mock:
empty = httpx.Response(200, json={"data": [], "schema": []})
yield {
"shelf": mock.post("/mcp/shelf/list").mock(return_value=empty),
"monthly": mock.post("/mcp/monthly/list").mock(return_value=empty),
"daily": mock.post("/mcp/daily/list").mock(return_value=empty),
}
# ------------------------------------------------ 接口一:POST /mcp/shelf/list
async def test_shelf_sends_exactly_the_documented_keys(service, upstream):
await service.mcp.call_tool("query_shelf_data", {"store_name": "A店", "store_id": 44211227})
assert sent_body(upstream["shelf"]) == {"storeName": "A店", "storeId": 44211227}
async def test_shelf_accepts_no_arguments_at_all(service, upstream):
"""规范 2.2:所有参数均为可选,不传则返回全部门店。"""
await service.mcp.call_tool("query_shelf_data", {})
assert sent_body(upstream["shelf"]) == {}
async def test_shelf_omits_unset_optionals_instead_of_sending_null(service, upstream):
await service.mcp.call_tool("query_shelf_data", {"store_name": "A店"})
assert sent_body(upstream["shelf"]) == {"storeName": "A店"}
async def test_shelf_has_no_brand_filter(service):
"""规范 v1.3 移除了 brand 品牌筛选(宽表无品牌列,筛不动)。"""
tools = {t.name: t for t in await service.mcp.list_tools()}
assert "brand" not in tools["query_shelf_data"].inputSchema["properties"]
# ---------------------------------------------- 接口二:POST /mcp/monthly/list
async def test_monthly_sends_exactly_the_documented_keys(service, upstream):
await service.mcp.call_tool(
"query_monthly_data", {"month": "2026-08", "store_name": "比亚迪深圳南山店"}
)
assert sent_body(upstream["monthly"]) == {
"month": "2026-08",
"storeName": "比亚迪深圳南山店",
}
async def test_monthly_month_is_required_per_spec(service):
"""规范 3.2 把 month 标为必填,工具的 schema 必须如实反映。"""
tools = {t.name: t for t in await service.mcp.list_tools()}
assert tools["query_monthly_data"].inputSchema["required"] == ["month"]
async def test_monthly_has_no_brand_filter(service):
tools = {t.name: t for t in await service.mcp.list_tools()}
assert "brand" not in tools["query_monthly_data"].inputSchema["properties"]
# ------------------------------------------------ 接口三:POST /mcp/daily/list
async def test_daily_sends_exactly_the_documented_keys(service, upstream):
await service.mcp.call_tool(
"query_daily_report",
{
"store_name": "比亚迪深圳南山店",
"employee": "张三",
"start_date": "2026-08-01",
"end_date": "2026-08-31",
},
)
assert sent_body(upstream["daily"]) == {
"storeName": "比亚迪深圳南山店",
"employee": "张三",
"startDate": "2026-08-01",
"endDate": "2026-08-31",
}
async def test_daily_required_params_match_the_spec(service):
"""规范 4.2:storeName / startDate / endDate 必填,employee 可选。"""
tools = {t.name: t for t in await service.mcp.list_tools()}
required = set(tools["query_daily_report"].inputSchema["required"])
assert required == {"store_name", "start_date", "end_date"}
@pytest.mark.parametrize(
"missing", ["store_name", "start_date", "end_date"]
)
async def test_daily_rejects_missing_required_param(service, upstream, missing):
args = {
"store_name": "A店",
"start_date": "2026-08-01",
"end_date": "2026-08-31",
}
args.pop(missing)
with pytest.raises(ToolError):
await service.mcp.call_tool("query_daily_report", args)
assert upstream["daily"].call_count == 0
# ------------------------------------------------------------------ 通用约定
@pytest.mark.parametrize(
("tool", "args", "route"),
[
("query_shelf_data", {"store_name": "A店"}, "shelf"),
("query_monthly_data", {"month": "2026-08"}, "monthly"),
(
"query_daily_report",
{"store_name": "A店", "start_date": "2026-08-01", "end_date": "2026-08-02"},
"daily",
),
],
)
async def test_every_request_carries_the_three_signature_headers(service, upstream, tool, args, route):
"""规范 1.2:appKey / sign / timestamp 三个头缺一不可。"""
await service.mcp.call_tool(tool, args)
headers = upstream[route].calls[0].request.headers
assert headers["appKey"] == "test-app-key"
assert len(headers["sign"]) == 40
assert headers["timestamp"].isdigit()
@pytest.mark.parametrize(
("tool", "path"),
[
("query_shelf_data", "/mcp/shelf/list"),
("query_monthly_data", "/mcp/monthly/list"),
("query_daily_report", "/mcp/daily/list"),
],
)
def test_paths_match_the_spec(tool, path):
from mcp_hive.services.used_car import api_client as ac
assert path in (ac.PATH_SHELF, ac.PATH_MONTHLY, ac.PATH_DAILY)
async def test_only_three_tools_are_exposed(service):
"""规范只有三个接口。多出来的工具说明有人加了规范外的东西。"""
names = {t.name for t in await service.mcp.list_tools()}
assert names == {"query_shelf_data", "query_monthly_data", "query_daily_report"}
async def test_tool_descriptions_stay_within_the_length_budget(service):
"""工具描述每轮对话都占 Agent 上下文。约定见 CLAUDE.md:中文 200-400 字符。"""
for tool in await service.mcp.list_tools():
assert 100 <= len(tool.description) <= 450, f"{tool.name}: {len(tool.description)}"
async def test_every_parameter_has_a_description_in_the_schema(service):
"""参数说明必须进 inputSchema,只写在 docstring 里的话,
只渲染 schema 的客户端什么都看不到。"""
for tool in await service.mcp.list_tools():
for name, prop in tool.inputSchema["properties"].items():
assert prop.get("description"), f"{tool.name}.{name} 缺少参数说明"
# ------------------------------------------------------- 调试台的工具元信息
async def test_every_tool_has_an_upstream_and_an_example(service):
"""控制台调试台靠 manifest.tool_docs 显示「这个工具打哪个接口」并预填参数。
新增工具时容易忘了补,这里守着。"""
docs = get_manifest("used_car").tool_docs
for tool in await service.mcp.list_tools():
doc = docs.get(tool.name)
assert doc is not None, f"{tool.name} 没有在 manifest.tool_docs 里登记"
assert doc.upstream.startswith("POST /mcp/"), doc.upstream
assert doc.example, f"{tool.name} 的示例参数是空的"
@pytest.mark.parametrize(
("tool", "route"),
[
("query_shelf_data", "shelf"),
("query_monthly_data", "monthly"),
("query_daily_report", "daily"),
],
)
async def test_example_arguments_actually_call_the_tool(service, upstream, tool, route):
"""示例参数必须是能真的调通的 —— 参数名拼错、少传必填项都会在这里炸。
这挡不住「门店在测试环境里不存在」,但能挡住「示例和工具签名对不上」,
后者才是改参数时最容易漏的。
"""
example = get_manifest("used_car").tool_docs[tool].example
await service.mcp.call_tool(tool, dict(example))
assert upstream[route].call_count == 1