k3cloud-query-mcp 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """k3cloud-query-mcp — 金蝶云星空 K3Cloud MCP 查询服务(纯查询版)"""
2
+
3
+ __version__ = "1.0.0"
File without changes
@@ -0,0 +1,764 @@
1
+ """
2
+ k3cloud-query-mcp — 金蝶云星空 K3Cloud MCP 查询服务(纯查询版)
3
+
4
+ 从 kingdee-k3cloud-mcp 派生,仅保留查询(只读)工具,移除所有写入/操作工具。
5
+ """
6
+
7
+ import csv
8
+ import json
9
+ import logging
10
+ import os
11
+ import sys
12
+ import time
13
+ from collections.abc import Iterator
14
+ from datetime import date, timedelta
15
+ from pathlib import Path
16
+
17
+ from dotenv import load_dotenv
18
+ from k3cloud_webapi_sdk.const.const_define import InvokeMethod
19
+ from k3cloud_webapi_sdk.main import K3CloudApiSdk
20
+ from k3cloud_webapi_sdk.model.cookie_store import CookieStore
21
+ from mcp.server.auth.provider import AccessToken
22
+ from mcp.server.auth.settings import AuthSettings
23
+ from mcp.server.fastmcp import FastMCP
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ SESSION_LOST_MSG = "会话信息已丢失"
28
+
29
+ # SDK instance: initialized in setup() after environment is validated.
30
+ api_sdk: "RetryableK3CloudApiSdk | None" = None
31
+
32
+
33
+ def _sdk() -> "RetryableK3CloudApiSdk":
34
+ """Return the initialized SDK, asserting it is not None."""
35
+ assert api_sdk is not None, "api_sdk not initialized — call setup() first"
36
+ return api_sdk
37
+
38
+
39
+ class ApiKeyVerifier:
40
+ """验证静态 API Key(Bearer Token)。
41
+
42
+ 仅在 SSE/streamable-http 传输时生效;MCP_API_KEY 未设置时禁用鉴权。
43
+ """
44
+
45
+ def __init__(self, api_key: str):
46
+ self._key = api_key
47
+
48
+ async def verify_token(self, token: str) -> AccessToken | None:
49
+ if token == self._key:
50
+ return AccessToken(token=token, client_id="api-key-client", scopes=[])
51
+ return None
52
+
53
+
54
+ mcp = FastMCP("k3cloud-query")
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # 内部辅助函数
59
+ # ---------------------------------------------------------------------------
60
+
61
+ def _check_expired(data) -> bool:
62
+ if isinstance(data, list):
63
+ return any(_check_expired(item) for item in data)
64
+ if isinstance(data, dict):
65
+ errors = (data.get("Result") or {}).get("ResponseStatus", {}).get("Errors", [])
66
+ return any(SESSION_LOST_MSG in (e.get("Message") or "") for e in errors)
67
+ return False
68
+
69
+
70
+ def _is_session_expired(result: str) -> bool:
71
+ try:
72
+ return _check_expired(json.loads(result))
73
+ except (json.JSONDecodeError, TypeError, ValueError):
74
+ return False
75
+
76
+
77
+ class RetryableK3CloudApiSdk(K3CloudApiSdk):
78
+ """K3CloudApiSdk with automatic session recovery on expiry.
79
+
80
+ When K3Cloud returns "会话信息已丢失", the recovery flow is:
81
+ 1. If the last session reset was more than _RESET_COOLDOWN seconds ago:
82
+ clear cookiesStore so BuildHeader() sends no session headers on retry.
83
+ The retry call lets the server issue a fresh SID (stored by
84
+ FillCookieAndHeader), even though the response body still reports
85
+ "session lost" while the new session activates server-side.
86
+ 2. If we reset recently (within cooldown), skip clearing — the freshly
87
+ issued SID is preserved and retried directly.
88
+
89
+ Rapid consecutive resets would destroy each newly-issued SID before it
90
+ activates, so the 300-second cooldown keeps the latest SID intact until
91
+ the server accepts it.
92
+ """
93
+
94
+ _RESET_COOLDOWN = 300 # seconds
95
+
96
+ def __init__(self, *args, **kwargs):
97
+ super().__init__(*args, **kwargs)
98
+ self._session_reset_at = 0.0
99
+
100
+ def Execute(self, service_name, json_data=None, invoke_type=InvokeMethod.SYNC):
101
+ result = super().Execute(service_name, json_data, invoke_type)
102
+ if isinstance(result, str) and _is_session_expired(result):
103
+ now = time.monotonic()
104
+ if now - self._session_reset_at >= self._RESET_COOLDOWN:
105
+ logger.warning("[k3cloud] session expired, re-establishing SID...")
106
+ self._session_reset_at = now
107
+ if hasattr(self, "cookiesStore"):
108
+ self.cookiesStore = CookieStore()
109
+ else:
110
+ logger.warning(
111
+ "[k3cloud] SDK internals changed: cookiesStore not found, cannot reset SID"
112
+ )
113
+ super().Execute(
114
+ service_name, json_data, invoke_type
115
+ ) # establishes SID, result discarded
116
+ else:
117
+ logger.warning("[k3cloud] session recovering, SID not yet active — skipping retry")
118
+ return result
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # 结果包装 & 翻页
123
+ # ---------------------------------------------------------------------------
124
+
125
+ def _wrap_query_result(raw: str, top_count: int, limit: int, start_row: int) -> str:
126
+ """将 SDK 查询结果包装为带分页元数据的 envelope。
127
+
128
+ 仅对成功的列表响应生效;错误响应(如会话过期)原样透传。
129
+
130
+ 返回格式:
131
+ {
132
+ "rows": [...原始数据...],
133
+ "row_count": N,
134
+ "truncated": true/false,
135
+ "next_start_row": N, # 仅 truncated=true 时存在
136
+ "hint": "..." # 仅 truncated=true 时存在
137
+ }
138
+ """
139
+ if _is_session_expired(raw):
140
+ return raw
141
+
142
+ try:
143
+ data = json.loads(raw)
144
+ except (json.JSONDecodeError, TypeError):
145
+ return raw
146
+
147
+ if not isinstance(data, list):
148
+ return raw
149
+
150
+ row_count = len(data)
151
+ cap = top_count if top_count > 0 else limit
152
+ truncated = row_count > 0 and row_count >= cap
153
+
154
+ result: dict = {
155
+ "rows": data,
156
+ "row_count": row_count,
157
+ "truncated": truncated,
158
+ }
159
+ if truncated:
160
+ result["next_start_row"] = start_row + row_count
161
+ result["hint"] = (
162
+ f"返回行数已达上限({cap} 行),数据可能被截断。"
163
+ f"请用 start_row={start_row + row_count} 继续翻页获取下一页数据。"
164
+ )
165
+
166
+ return json.dumps(result, ensure_ascii=False)
167
+
168
+
169
+ def _paginate_bill(
170
+ params: dict, page_size: int, max_rows: int
171
+ ) -> "tuple[list, bool, int, str | None]":
172
+ """内部翻页原语。返回 (rows, exhausted, next_start_row, error_raw)。"""
173
+ rows: list = []
174
+ initial_start = params.get("StartRow", 0)
175
+ current_start = initial_start
176
+
177
+ while True:
178
+ page_params = {
179
+ **params,
180
+ "StartRow": current_start,
181
+ "TopRowCount": current_start + page_size,
182
+ "Limit": page_size,
183
+ }
184
+ raw = _sdk().BillQuery(page_params)
185
+
186
+ if _is_session_expired(raw):
187
+ return rows, False, current_start, raw
188
+
189
+ try:
190
+ data = json.loads(raw)
191
+ except (json.JSONDecodeError, TypeError):
192
+ return rows, False, current_start, raw
193
+
194
+ if not isinstance(data, list):
195
+ return rows, False, current_start, raw
196
+
197
+ rows.extend(data)
198
+ page_count = len(data)
199
+
200
+ if len(rows) >= max_rows:
201
+ rows = rows[:max_rows]
202
+ return rows, False, initial_start + max_rows, None
203
+
204
+ if page_count < page_size:
205
+ return rows, True, initial_start + len(rows), None
206
+
207
+ current_start += page_size
208
+
209
+
210
+ def _iter_date_chunks(date_from: str, date_to: str, chunk: str) -> "Iterator[tuple[str, str]]":
211
+ """将 [date_from, date_to) 切成 N 个半开区间。chunk ∈ {'month','week','day'}。"""
212
+ if chunk not in {"month", "week", "day"}:
213
+ raise ValueError(f"chunk 必须是 month/week/day,收到: {chunk!r}")
214
+ try:
215
+ current = date.fromisoformat(date_from)
216
+ end = date.fromisoformat(date_to)
217
+ except ValueError as e:
218
+ raise ValueError(f"日期格式错误(需要 YYYY-MM-DD): {e}") from e
219
+ if end <= current:
220
+ raise ValueError("date_to 必须晚于 date_from")
221
+
222
+ while current < end:
223
+ if chunk == "month":
224
+ if current.month == 12:
225
+ next_dt = date(current.year + 1, 1, 1)
226
+ else:
227
+ next_dt = date(current.year, current.month + 1, 1)
228
+ elif chunk == "week":
229
+ next_dt = current + timedelta(weeks=1)
230
+ else:
231
+ next_dt = current + timedelta(days=1)
232
+ chunk_end = min(next_dt, end)
233
+ yield current.isoformat(), chunk_end.isoformat()
234
+ current = chunk_end
235
+
236
+
237
+ def _stream_to_file_handle(
238
+ f,
239
+ params: dict,
240
+ page_size: int,
241
+ max_rows: int,
242
+ fields: list,
243
+ fmt: str,
244
+ header_written: bool,
245
+ ) -> "tuple[int, bool, str | None]":
246
+ """将分页查询结果流式追加写入已打开的文件句柄。
247
+
248
+ Returns:
249
+ (rows_written, header_written, error_raw)
250
+ """
251
+ writer = csv.writer(f) if fmt == "csv" else None
252
+ rows_written = 0
253
+ current_start = params.get("StartRow", 0)
254
+
255
+ while True:
256
+ page_params = {
257
+ **params,
258
+ "StartRow": current_start,
259
+ "TopRowCount": current_start + page_size,
260
+ "Limit": page_size,
261
+ }
262
+ raw = _sdk().BillQuery(page_params)
263
+
264
+ if _is_session_expired(raw):
265
+ return rows_written, header_written, raw
266
+
267
+ try:
268
+ data = json.loads(raw)
269
+ except (json.JSONDecodeError, TypeError):
270
+ return rows_written, header_written, raw
271
+
272
+ if not isinstance(data, list):
273
+ return rows_written, header_written, raw
274
+
275
+ for row in data:
276
+ if fmt == "ndjson":
277
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
278
+ elif writer is not None:
279
+ if not header_written:
280
+ writer.writerow(fields)
281
+ header_written = True
282
+ writer.writerow([row.get(field, "") for field in fields])
283
+ rows_written += 1
284
+ if rows_written >= max_rows:
285
+ return rows_written, header_written, None
286
+
287
+ if len(data) < page_size:
288
+ break
289
+
290
+ current_start += page_size
291
+
292
+ return rows_written, header_written, None
293
+
294
+
295
+ # ===================================================================
296
+ # 查询工具(只读)
297
+ # ===================================================================
298
+
299
+ @mcp.tool()
300
+ def query_bill(
301
+ form_id: str,
302
+ field_keys: str,
303
+ filter_string: str = "",
304
+ order_string: str = "",
305
+ top_count: int = 100,
306
+ start_row: int = 0,
307
+ limit: int = 2000,
308
+ ) -> str:
309
+ """查询金蝶云星空单据数据(返回二维数组)。
310
+
311
+ Args:
312
+ form_id: 表单ID。常用值:
313
+ BD_MATERIAL(物料)、BD_Customer(客户)、BD_Supplier(供应商)、
314
+ SAL_SaleOrder(销售订单)、PUR_PurchaseOrder(采购订单)、
315
+ STK_InStock(入库单)、STK_OutStock(出库单)、GL_VOUCHER(凭证)
316
+ field_keys: 查询字段,逗号分隔。如 "FName,FNumber"
317
+ filter_string: 过滤条件。如 "FNumber like 'MAT%'"
318
+ order_string: 排序字段。如 "FNumber ASC"
319
+ top_count: 本次最多返回行数,默认100。映射到金蝶 TopRowCount(绝对终止行号 = start_row + top_count),
320
+ 同时作为金蝶 Limit(单次页大小)。设为 0 表示不限制行数(仅靠 limit 控制)。
321
+ start_row: 起始行号,默认0。翻页时传入上一次返回的 next_start_row。
322
+ limit: 仅在 top_count=0 时生效,作为金蝶 Limit 页大小上限,默认2000。
323
+ top_count>0 时此参数被忽略(页大小由 top_count 决定)。
324
+ """
325
+ raw = _sdk().ExecuteBillQuery(
326
+ {
327
+ "FormId": form_id,
328
+ "FieldKeys": field_keys,
329
+ "FilterString": filter_string,
330
+ "OrderString": order_string,
331
+ "TopRowCount": (start_row + top_count) if top_count > 0 else 0,
332
+ "StartRow": start_row,
333
+ "Limit": top_count if top_count > 0 else limit,
334
+ }
335
+ )
336
+ return _wrap_query_result(raw, top_count, limit, start_row)
337
+
338
+
339
+ @mcp.tool()
340
+ def query_bill_json(
341
+ form_id: str,
342
+ field_keys: str,
343
+ filter_string: str = "",
344
+ order_string: str = "",
345
+ top_count: int = 100,
346
+ start_row: int = 0,
347
+ limit: int = 2000,
348
+ ) -> str:
349
+ """查询金蝶云星空单据数据(返回JSON格式,字段名作为key)。
350
+
351
+ 与 query_bill 的区别:返回结果是JSON对象数组,每条记录的字段名作为key,更易读。
352
+
353
+ Args:
354
+ form_id: 表单ID。常用值:
355
+ BD_MATERIAL(物料)、BD_Customer(客户)、BD_Supplier(供应商)、
356
+ SAL_SaleOrder(销售订单)、PUR_PurchaseOrder(采购订单)、
357
+ STK_InStock(入库单)、STK_OutStock(出库单)、GL_VOUCHER(凭证)
358
+ field_keys: 查询字段,逗号分隔。如 "FName,FNumber,FCreateOrgId,FUseOrgId"
359
+ filter_string: 过滤条件。如 "FNumber like 'MAT%'"
360
+ order_string: 排序字段。如 "FNumber ASC"
361
+ top_count: 本次最多返回行数,默认100。映射到金蝶 TopRowCount(绝对终止行号 = start_row + top_count),
362
+ 同时作为金蝶 Limit(单次页大小)。设为 0 表示不限制行数(仅靠 limit 控制)。
363
+ start_row: 起始行号,默认0。翻页时传入上一次返回的 next_start_row。
364
+ limit: 仅在 top_count=0 时生效,作为金蝶 Limit 页大小上限,默认2000。
365
+ top_count>0 时此参数被忽略(页大小由 top_count 决定)。
366
+ """
367
+ raw = _sdk().BillQuery(
368
+ {
369
+ "FormId": form_id,
370
+ "FieldKeys": field_keys,
371
+ "FilterString": filter_string,
372
+ "OrderString": order_string,
373
+ "TopRowCount": (start_row + top_count) if top_count > 0 else 0,
374
+ "StartRow": start_row,
375
+ "Limit": top_count if top_count > 0 else limit,
376
+ }
377
+ )
378
+ return _wrap_query_result(raw, top_count, limit, start_row)
379
+
380
+
381
+ @mcp.tool()
382
+ def count_bill(form_id: str, filter_string: str = "") -> str:
383
+ """估算某查询条件下的数据行数(不返回数据内容)。用于大数据量查询前的探测。
384
+
385
+ 返回 JSON 格式:
386
+ {"estimated_rows": N, "is_exact": true/false, "hint": "..."}
387
+ 当 is_exact=false 时,实际行数 ≥ estimated_rows,建议按月/周分片查询。
388
+
389
+ Args:
390
+ form_id: 表单ID。如 SAL_SaleOrder、PUR_PurchaseOrder、BD_MATERIAL 等
391
+ filter_string: 过滤条件。如 "FDate >= '2025-01-01' AND FDate < '2026-01-01'"
392
+ """
393
+ _PROBE_LIMIT = 5000
394
+ raw = _sdk().BillQuery(
395
+ {
396
+ "FormId": form_id,
397
+ "FieldKeys": "FID",
398
+ "FilterString": filter_string,
399
+ "TopRowCount": _PROBE_LIMIT,
400
+ "StartRow": 0,
401
+ "Limit": _PROBE_LIMIT,
402
+ }
403
+ )
404
+
405
+ if _is_session_expired(raw):
406
+ return raw
407
+
408
+ try:
409
+ data = json.loads(raw)
410
+ except (json.JSONDecodeError, TypeError):
411
+ return raw
412
+
413
+ if not isinstance(data, list):
414
+ return raw
415
+
416
+ count = len(data)
417
+ is_exact = count < _PROBE_LIMIT
418
+ result: dict = {"estimated_rows": count, "is_exact": is_exact}
419
+ if not is_exact:
420
+ result["hint"] = (
421
+ f"实际行数 ≥ {_PROBE_LIMIT},建议按自然月分片查询(每月单独调用 query_bill_json)。"
422
+ )
423
+ return json.dumps(result, ensure_ascii=False)
424
+
425
+
426
+ @mcp.tool()
427
+ def query_bill_all(
428
+ form_id: str,
429
+ field_keys: str,
430
+ filter_string: str = "",
431
+ order_string: str = "",
432
+ max_rows: int = 20000,
433
+ page_size: int = 2000,
434
+ ) -> str:
435
+ """自动翻页查询直到拉完或达到 max_rows 安全上限。
436
+
437
+ 适合估算 ≤ 数千行的场景。大数据量(> 5000 行)请用 query_bill_to_file(落盘)
438
+ 或 query_bill_range(日期分片),避免超过 MCP 1 MB 返回限制。
439
+
440
+ 返回格式:
441
+ {"rows": [...], "row_count": N, "exhausted": true/false,
442
+ "next_start_row": N, # 仅 exhausted=false 时
443
+ "hint": "..."} # 仅 exhausted=false 时
444
+
445
+ Args:
446
+ form_id: 表单ID。如 SAL_SaleOrder、PUR_PurchaseOrder、BD_MATERIAL 等
447
+ field_keys: 查询字段,逗号分隔。如 "FBillNo,FDate,FAmount"
448
+ filter_string: 过滤条件。如 "FDate >= '2025-01-01'"
449
+ order_string: 排序字段。如 "FDate ASC"
450
+ max_rows: 安全上限,默认 20000;超过则提前终止并返回 exhausted=false
451
+ page_size: 每页行数,默认 2000,建议不超过 2000
452
+ """
453
+ params = {
454
+ "FormId": form_id,
455
+ "FieldKeys": field_keys,
456
+ "FilterString": filter_string,
457
+ "OrderString": order_string,
458
+ }
459
+ rows, exhausted, next_start, err = _paginate_bill(params, page_size, max_rows)
460
+ if err is not None:
461
+ return err
462
+ result: dict = {"rows": rows, "row_count": len(rows), "exhausted": exhausted}
463
+ if not exhausted:
464
+ result["next_start_row"] = next_start
465
+ result["hint"] = (
466
+ "已达 max_rows 安全上限,如需继续请调用 query_bill_range 或缩小 filter_string 后手动分片"
467
+ )
468
+ return json.dumps(result, ensure_ascii=False)
469
+
470
+
471
+ @mcp.tool()
472
+ def query_bill_to_file(
473
+ form_id: str,
474
+ field_keys: str,
475
+ filter_string: str = "",
476
+ output_path: str = "",
477
+ format: str = "ndjson",
478
+ page_size: int = 2000,
479
+ max_rows: int = 500000,
480
+ ) -> str:
481
+ """自动翻页并流式写入本地文件,适合大数据量导出(万行以上)。
482
+
483
+ 不在内存中累积数据,写入完成后返回文件路径和统计信息。
484
+ 文件可用 Read 工具抽检,或交由 pandas/polars 处理。
485
+
486
+ 返回格式:
487
+ {"path": "...", "row_count": N, "bytes": M, "format": "ndjson"}
488
+ 若中途出错:{"error": "...", "path": "...", "row_count": <已写入>, "bytes": M}
489
+
490
+ Args:
491
+ form_id: 表单ID。如 SAL_SaleOrder、PUR_PurchaseOrder、BD_MATERIAL 等
492
+ field_keys: 查询字段,逗号分隔。如 "FBillNo,FDate,FAmount"
493
+ filter_string: 过滤条件。如 "FDate >= '2025-01-01'"
494
+ output_path: 输出文件绝对路径。如 "/tmp/orders.ndjson"
495
+ format: 输出格式,ndjson(每行一个 JSON 对象)或 csv,默认 ndjson
496
+ page_size: 每页行数,默认 2000
497
+ max_rows: 最大写入行数,默认 500000;超过则截断并正常返回
498
+ """
499
+ if not output_path or not os.path.isabs(output_path):
500
+ return json.dumps({"error": "output_path 必须为非空绝对路径"}, ensure_ascii=False)
501
+ if format not in {"ndjson", "csv"}:
502
+ return json.dumps(
503
+ {"error": f"format 必须是 ndjson 或 csv,收到: {format!r}"}, ensure_ascii=False
504
+ )
505
+ parent = os.path.dirname(output_path)
506
+ if not os.path.isdir(parent):
507
+ return json.dumps({"error": f"目录不存在: {parent}"}, ensure_ascii=False)
508
+
509
+ fields = [f.strip() for f in field_keys.split(",") if f.strip()]
510
+ params = {
511
+ "FormId": form_id,
512
+ "FieldKeys": field_keys,
513
+ "FilterString": filter_string,
514
+ "OrderString": "",
515
+ "StartRow": 0,
516
+ }
517
+
518
+ try:
519
+ with open(output_path, "w", encoding="utf-8", newline="") as f:
520
+ rows_written, _, error_raw = _stream_to_file_handle(
521
+ f, params, page_size, max_rows, fields, format, False
522
+ )
523
+ except OSError as e:
524
+ return json.dumps({"error": f"文件写入失败: {e}"}, ensure_ascii=False)
525
+
526
+ file_bytes = os.path.getsize(output_path)
527
+
528
+ if error_raw is not None:
529
+ return json.dumps(
530
+ {
531
+ "error": "查询中途遇到错误,已写入部分数据",
532
+ "path": output_path,
533
+ "row_count": rows_written,
534
+ "bytes": file_bytes,
535
+ },
536
+ ensure_ascii=False,
537
+ )
538
+
539
+ return json.dumps(
540
+ {
541
+ "path": output_path,
542
+ "row_count": rows_written,
543
+ "bytes": file_bytes,
544
+ "format": format,
545
+ },
546
+ ensure_ascii=False,
547
+ )
548
+
549
+
550
+ @mcp.tool()
551
+ def query_bill_range(
552
+ form_id: str,
553
+ field_keys: str,
554
+ date_field: str,
555
+ date_from: str,
556
+ date_to: str,
557
+ extra_filter: str = "",
558
+ chunk: str = "month",
559
+ output_path: str = "",
560
+ page_size: int = 2000,
561
+ ) -> str:
562
+ """按日期自动切片 + 翻页,适合跨月/跨年查询。
563
+
564
+ 将 [date_from, date_to) 按 chunk 切成 N 段,每段独立翻页拉取。
565
+ output_path 为空时内联返回(受 MCP 1 MB 限制,适合小跨度);
566
+ 非空时流式落盘,适合大跨度(年级)查询。
567
+
568
+ 返回格式(内联):
569
+ {"rows": [...], "row_count": N, "chunks": K, "exhausted": true}
570
+ 返回格式(落盘):
571
+ {"path": "...", "row_count": N, "bytes": M, "chunks": K, "format": "ndjson"}
572
+ 若中途出错:{"error": "...", "path": "...", "row_count": <已写入>, "bytes": M}
573
+
574
+ Args:
575
+ form_id: 表单ID。如 SAL_SaleOrder、PUR_PurchaseOrder 等
576
+ field_keys: 查询字段,逗号分隔
577
+ date_field: 日期字段名。通常是 FDate 或 FCreateDate
578
+ date_from: 起始日期(含),YYYY-MM-DD
579
+ date_to: 结束日期(不含),YYYY-MM-DD
580
+ extra_filter: 额外过滤条件(与日期条件 AND 拼接)
581
+ chunk: 切片粒度,month(默认)/ week / day
582
+ output_path: 落盘路径(绝对路径)。空=内联返回
583
+ page_size: 每页行数,默认 2000
584
+ """
585
+ try:
586
+ chunks = list(_iter_date_chunks(date_from, date_to, chunk))
587
+ except ValueError as e:
588
+ return json.dumps({"error": str(e)}, ensure_ascii=False)
589
+
590
+ inline_mode = not output_path
591
+
592
+ if not inline_mode:
593
+ if not os.path.isabs(output_path):
594
+ return json.dumps({"error": "output_path 必须为绝对路径"}, ensure_ascii=False)
595
+ parent = os.path.dirname(output_path)
596
+ if not os.path.isdir(parent):
597
+ return json.dumps({"error": f"目录不存在: {parent}"}, ensure_ascii=False)
598
+
599
+ fields = [f.strip() for f in field_keys.split(",") if f.strip()]
600
+
601
+ def _build_filter(chunk_from: str, chunk_to: str) -> str:
602
+ date_filter = f"{date_field} >= '{chunk_from}' AND {date_field} < '{chunk_to}'"
603
+ return f"({extra_filter}) AND {date_filter}" if extra_filter else date_filter
604
+
605
+ if inline_mode:
606
+ all_rows: list = []
607
+ for chunk_from, chunk_to in chunks:
608
+ params: dict = {
609
+ "FormId": form_id,
610
+ "FieldKeys": field_keys,
611
+ "FilterString": _build_filter(chunk_from, chunk_to),
612
+ "OrderString": "",
613
+ }
614
+ rows, _exhausted, _next, err = _paginate_bill(params, page_size, 20000)
615
+ if err is not None:
616
+ return err
617
+ all_rows.extend(rows)
618
+ return json.dumps(
619
+ {
620
+ "rows": all_rows,
621
+ "row_count": len(all_rows),
622
+ "chunks": len(chunks),
623
+ "exhausted": True,
624
+ },
625
+ ensure_ascii=False,
626
+ )
627
+
628
+ # Streaming / file mode
629
+ total_count = 0
630
+ error_raw = None
631
+ try:
632
+ with open(output_path, "w", encoding="utf-8", newline="") as f:
633
+ header_written = False
634
+ for chunk_from, chunk_to in chunks:
635
+ params = {
636
+ "FormId": form_id,
637
+ "FieldKeys": field_keys,
638
+ "FilterString": _build_filter(chunk_from, chunk_to),
639
+ "OrderString": "",
640
+ "StartRow": 0,
641
+ }
642
+ rows_written, header_written, error_raw = _stream_to_file_handle(
643
+ f, params, page_size, 500000, fields, "ndjson", header_written
644
+ )
645
+ total_count += rows_written
646
+ if error_raw is not None:
647
+ break
648
+ except OSError as e:
649
+ return json.dumps({"error": f"文件写入失败: {e}"}, ensure_ascii=False)
650
+
651
+ file_bytes = os.path.getsize(output_path)
652
+
653
+ if error_raw is not None:
654
+ return json.dumps(
655
+ {
656
+ "error": "查询中途遇到错误,已写入部分数据",
657
+ "path": output_path,
658
+ "row_count": total_count,
659
+ "bytes": file_bytes,
660
+ },
661
+ ensure_ascii=False,
662
+ )
663
+
664
+ return json.dumps(
665
+ {
666
+ "path": output_path,
667
+ "row_count": total_count,
668
+ "bytes": file_bytes,
669
+ "chunks": len(chunks),
670
+ "format": "ndjson",
671
+ },
672
+ ensure_ascii=False,
673
+ )
674
+
675
+
676
+ @mcp.tool()
677
+ def view_bill(
678
+ form_id: str,
679
+ number: str = "",
680
+ bill_id: str = "",
681
+ ) -> str:
682
+ """查看金蝶云星空单条记录的完整详情。
683
+
684
+ 通过编号或内码查看单条记录的所有字段信息。
685
+
686
+ Args:
687
+ form_id: 表单ID。如 BD_MATERIAL、SAL_SaleOrder 等
688
+ number: 单据编号。如 "MATERIAL001"(number 和 bill_id 二选一)
689
+ bill_id: 单据内码ID(number 和 bill_id 二选一)
690
+ """
691
+ data = {"CreateOrgId": 0, "Number": number, "Id": bill_id, "IsSortBySeq": "false"}
692
+ return _sdk().View(form_id, data)
693
+
694
+
695
+ @mcp.tool()
696
+ def query_metadata(form_id: str) -> str:
697
+ """查询金蝶云星空表单的元数据(字段结构信息)。
698
+
699
+ 用于获取某个表单有哪些字段、字段类型等信息,便于构造查询和保存参数。
700
+
701
+ Args:
702
+ form_id: 表单ID。如 SAL_SaleOrder、PUR_PurchaseOrder、BD_MATERIAL 等
703
+ """
704
+ return _sdk().QueryBusinessInfo({"FormId": form_id})
705
+
706
+
707
+ # ===================================================================
708
+ # 初始化 & 入口
709
+ # ===================================================================
710
+
711
+ def setup() -> None:
712
+ """Initialize environment, validate required vars, and create the SDK instance."""
713
+ global api_sdk
714
+ load_dotenv(dotenv_path=Path.cwd() / ".env")
715
+ _required_env = ["KD_SERVER_URL", "KD_ACCT_ID", "KD_USERNAME", "KD_APP_ID", "KD_APP_SEC"]
716
+ _missing_env = [k for k in _required_env if not os.getenv(k)]
717
+ if _missing_env:
718
+ raise RuntimeError(f"Missing required env vars: {', '.join(_missing_env)}")
719
+
720
+ api_key = os.getenv("MCP_API_KEY", "")
721
+ if api_key:
722
+ issuer_url = os.getenv("MCP_ISSUER_URL", "http://localhost:8000")
723
+ mcp._token_verifier = ApiKeyVerifier(api_key)
724
+ mcp.settings.auth = AuthSettings(issuer_url=issuer_url, resource_server_url=issuer_url) # type: ignore[arg-type]
725
+
726
+ server_url = os.getenv("KD_SERVER_URL", "")
727
+ api_sdk = RetryableK3CloudApiSdk(server_url)
728
+ api_sdk.InitConfig(
729
+ acct_id=os.getenv("KD_ACCT_ID", ""),
730
+ user_name=os.getenv("KD_USERNAME", ""),
731
+ app_id=os.getenv("KD_APP_ID", ""),
732
+ app_secret=os.getenv("KD_APP_SEC", ""),
733
+ server_url=server_url,
734
+ lcid=int(os.getenv("KD_LCID", "2052")),
735
+ org_num=int(os.getenv("KD_ORG_NUM", "0") or "0"),
736
+ )
737
+
738
+
739
+ def main():
740
+ import argparse
741
+
742
+ logging.basicConfig(
743
+ level=logging.INFO,
744
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
745
+ stream=sys.stderr,
746
+ )
747
+
748
+ parser = argparse.ArgumentParser(description="Nxr K3Cloud Query MCP Server(纯查询版)")
749
+ parser.add_argument(
750
+ "--transport",
751
+ choices=["stdio", "sse", "streamable-http"],
752
+ default="stdio",
753
+ help="传输协议(默认 stdio)",
754
+ )
755
+ args = parser.parse_args()
756
+
757
+ setup()
758
+
759
+ logger.info("[k3cloud-query] 纯查询模式,共 8 个查询工具")
760
+ mcp.run(transport=args.transport)
761
+
762
+
763
+ if __name__ == "__main__":
764
+ main()
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: k3cloud-query-mcp
3
+ Version: 1.0.0
4
+ Summary: Nxr K3Cloud Query MCP Server — 金蝶云星空纯查询 MCP 服务,仅提供只读查询工具
5
+ Project-URL: Homepage, https://github.com/nxr/k3cloud-query-mcp
6
+ Project-URL: Repository, https://github.com/nxr/k3cloud-query-mcp
7
+ Author: Nxr Team
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: erp,k3cloud,kingdee,mcp,mcp-server,nxr,query,金蝶
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: kingdee-cdp-webapi-sdk<9.0.0,>=8.2.0
24
+ Requires-Dist: mcp<2,>=1.26.0
25
+ Requires-Dist: python-dotenv<2,>=1.2.1
26
+ Description-Content-Type: text/markdown
27
+
28
+ # k3cloud-query-mcp
29
+
30
+ 金蝶云星空 K3Cloud MCP 查询服务(纯查询版)—— 让 AI 助手通过自然语言查询金蝶 ERP 数据。
31
+
32
+ ## 特性
33
+
34
+ | 特性 | k3cloud-query-mcp |
35
+ |------|----------------------|
36
+ | 查询工具 | ✅ 8 个 |
37
+ | 写入/操作工具 | ❌ 已移除 |
38
+ | 适用场景 | 纯查询 |
39
+
40
+ ## 查询工具列表
41
+
42
+ | 工具 | 说明 |
43
+ |------|------|
44
+ | `query_bill` | 查询单据数据(二维数组) |
45
+ | `query_bill_json` | 查询单据数据(JSON 对象数组) |
46
+ | `count_bill` | 估算查询条件下的数据行数 |
47
+ | `query_bill_all` | 自动翻页查询(≤ 数千行) |
48
+ | `query_bill_to_file` | 大数据量流式导出到文件 |
49
+ | `query_bill_range` | 按日期分片查询(跨月/跨年) |
50
+ | `view_bill` | 查看单条记录完整详情 |
51
+ | `query_metadata` | 查询表单字段元数据 |
52
+
53
+ ## 安装
54
+
55
+ ```bash
56
+ pip install k3cloud-query-mcp
57
+ ```
58
+
59
+ 或使用 uv:
60
+
61
+ ```bash
62
+ uv add k3cloud-query-mcp
63
+ ```
64
+
65
+ ## 配置
66
+
67
+ 在项目根目录创建 `.env` 文件:
68
+
69
+ ```env
70
+ KD_ACCT_ID=your_acct_id
71
+ KD_USERNAME=your_username
72
+ KD_APP_ID=your_app_id
73
+ KD_APP_SEC=your_app_secret
74
+ KD_SERVER_URL=https://your-server/k3cloud/
75
+ KD_LCID=2052
76
+ ```
77
+
78
+ ## 使用
79
+
80
+ ### Claude Desktop 配置
81
+
82
+ ```json
83
+ {
84
+ "mcpServers": {
85
+ "k3cloud-query": {
86
+ "command": "uvx",
87
+ "args": ["k3cloud-query-mcp"],
88
+ "env": {
89
+ "KD_ACCT_ID": "your_acct_id",
90
+ "KD_USERNAME": "your_username",
91
+ "KD_APP_ID": "your_app_id",
92
+ "KD_APP_SEC": "your_app_secret",
93
+ "KD_SERVER_URL": "https://your-server/k3cloud/"
94
+ }
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ ### SSE 模式
101
+
102
+ ```bash
103
+ k3cloud-query-mcp --transport sse
104
+ ```
105
+
106
+ ### 开发
107
+
108
+ ```bash
109
+ # 安装依赖
110
+ uv sync
111
+
112
+ # 运行
113
+ uv run k3cloud-query-mcp
114
+
115
+ # 测试
116
+ make test
117
+
118
+ # 代码检查
119
+ make lint
120
+
121
+ # 格式化
122
+ make format
123
+ ```
@@ -0,0 +1,8 @@
1
+ k3cloud_query_mcp/__init__.py,sha256=cG2PwYZFo8hQzSwX1RIqfbnKHMp435mvJgLfvw0UOPQ,113
2
+ k3cloud_query_mcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ k3cloud_query_mcp/server.py,sha256=cLCVJMQiaEW4CDo38_L8mvvu14jH5J70MLJZK2BwS6U,28065
4
+ k3cloud_query_mcp-1.0.0.dist-info/METADATA,sha256=wXbYvhnvrv-6VZGMW8K-ek4nG5I9Gmu9zxQabs5JU6g,2957
5
+ k3cloud_query_mcp-1.0.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
+ k3cloud_query_mcp-1.0.0.dist-info/entry_points.txt,sha256=Z4A4D-qUBNUlIVA7KbE1QdQH1St_e8-T_YmO-7t3y5w,68
7
+ k3cloud_query_mcp-1.0.0.dist-info/licenses/LICENSE,sha256=9BoAnlWUzbAVcRR-6VO8G6fGBdyQR0ziygxBKBYazJE,10364
8
+ k3cloud_query_mcp-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ k3cloud-query-mcp = k3cloud_query_mcp.server:main
@@ -0,0 +1,183 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner.
54
+
55
+ "Contributor" shall mean Licensor and any individual or Legal Entity
56
+ on behalf of whom a Contribution has been received by Licensor and
57
+ subsequently incorporated within the Work.
58
+
59
+ 2. Grant of Copyright License. Subject to the terms and conditions of
60
+ this License, each Contributor hereby grants to You a perpetual,
61
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
62
+ copyright license to reproduce, prepare Derivative Works of,
63
+ publicly display, publicly perform, sublicense, and distribute the
64
+ Work and such Derivative Works in Source or Object form.
65
+
66
+ 3. Grant of Patent License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ (except as stated in this section) patent license to make, have made,
70
+ use, offer to sell, sell, import, and otherwise transfer the Work,
71
+ where such license applies only to those patent claims licensable
72
+ by such Contributor that are necessarily infringed by their
73
+ Contribution(s) alone or by combination of their Contribution(s)
74
+ with the Work to which such Contribution(s) was submitted. If You
75
+ institute patent litigation against any entity (including a
76
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
77
+ or a Contribution incorporated within the Work constitutes direct
78
+ or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate
80
+ as of the date such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the
83
+ Work or Derivative Works thereof in any medium, with or without
84
+ modifications, and in Source or Object form, provided that You
85
+ meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or
88
+ Derivative Works a copy of this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices
91
+ stating that You changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works
94
+ that You distribute, all copyright, patent, trademark, and
95
+ attribution notices from the Source form of the Work,
96
+ excluding those notices that do not pertain to any part of
97
+ the Derivative Works; and
98
+
99
+ (d) If the Work includes a "NOTICE" text file as part of its
100
+ distribution, then any Derivative Works that You distribute must
101
+ include a readable copy of the attribution notices contained
102
+ within such NOTICE file, excluding those notices that do not
103
+ pertain to any part of the Derivative Works, in at least one
104
+ of the following places: within a NOTICE text file distributed
105
+ as part of the Derivative Works; within the Source form or
106
+ documentation, if provided along with the Derivative Works; or,
107
+ within a display generated by the Derivative Works, if and
108
+ wherever such third-party notices normally appear. The contents
109
+ of the NOTICE file are for informational purposes only and
110
+ do not modify the License. You may add Your own attribution
111
+ notices within Derivative Works that You distribute, alongside
112
+ or as an addendum to the NOTICE text from the Work, provided
113
+ that such additional attribution notices cannot be construed
114
+ as modifying the License.
115
+
116
+ You may add Your own copyright statement to Your modifications and
117
+ may provide additional or different license terms and conditions
118
+ for use, reproduction, or distribution of Your modifications, or
119
+ for any such Derivative Works as a whole, provided Your use,
120
+ reproduction, and distribution of the Work otherwise complies with
121
+ the conditions stated in this License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or redistributing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or consequential damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or any and all
155
+ other commercial damages or losses), even if such Contributor
156
+ has been advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ Copyright 2026 Nxr Team
172
+
173
+ Licensed under the Apache License, Version 2.0 (the "License");
174
+ you may not use this file except in compliance with the License.
175
+ You may obtain a copy of the License at
176
+
177
+ http://www.apache.org/licenses/LICENSE-2.0
178
+
179
+ Unless required by applicable law or agreed to in writing, software
180
+ distributed under the License is distributed on an "AS IS" BASIS,
181
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ See the License for the specific language governing permissions and
183
+ limitations under the License.