output_presenter.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. import json
  2. import logging
  3. from urllib.parse import urlparse
  4. from constants import DEVICE_INVALID_MESSAGE
  5. logger = logging.getLogger(__name__)
  6. # Builds AI-safe MCP results for the explicitly supported tool set.
  7. class OutputPresenter:
  8. TABLE_TOOLS = frozenset((
  9. 'query_order_exact',
  10. 'query_track',
  11. 'query_customs_declaration_files',
  12. 'query_outbound_list',
  13. ))
  14. DETAIL_TOOLS = frozenset(('query_outbound_detail',))
  15. ORDER_DETAIL_TOOLS = frozenset(('query_order_detail',))
  16. OPTION_TOOLS = frozenset((
  17. 'list_order_filter_options',
  18. 'list_outbound_filter_options',
  19. 'list_pending_outbound_export_filter_options',
  20. ))
  21. EXPORT_TOOLS = frozenset((
  22. 'export_pending_outbound_orders',
  23. 'export_out_of_province_port_data',
  24. ))
  25. TASK_TOOLS = frozenset(('query_export_task',))
  26. SAFE_TOOLS = (
  27. TABLE_TOOLS | DETAIL_TOOLS | ORDER_DETAIL_TOOLS
  28. | OPTION_TOOLS | EXPORT_TOOLS | TASK_TOOLS
  29. )
  30. ORDER_DETAIL_SECTIONS = {
  31. 'overview': '订单概览',
  32. 'packages': '箱单信息',
  33. 'package_items': '箱单商品',
  34. 'dw_auth': 'DW授权信息',
  35. 'attachments': '附件信息',
  36. 'inbound': '入库信息',
  37. 'checks': '查验信息',
  38. 'tracks': '订单轨迹',
  39. 'operation_logs': '操作日志',
  40. 'cost_logs': '应收与结算日志',
  41. 'delivery': '派送信息',
  42. 'all': '全部',
  43. }
  44. ORDER_DETAIL_FIELDS = {
  45. 'overview': {
  46. 'order_info': {
  47. 'order_number': '订单号', 'reference_number': '客户参考号',
  48. 'customer_name': '客户名称', 'departure_country': '起运国',
  49. 'destination_country': '目的国', 'package_method': '包装类型',
  50. 'product_name': '物流产品', 'forecast_pwv': '预报件重体',
  51. 'inbound_pwv': '入库件重体',
  52. 'receivable_charge_weight': '应收计费重/体积',
  53. 'settlement_charge_weight': '结算计费重/体积',
  54. 'declaration_type': '报关类型', 'pre_recording': '是否需要预录单',
  55. 'idcard_name': '企业/个人姓名',
  56. 'idcard_number': '社会信用代码/身份证号',
  57. 'outbound_number': '排舱单号', 'container_mode': '直送柜/拼柜',
  58. 'track_map_available': '是否可查看轨迹地图', 'insurance': '购买保险',
  59. 'delivery_way': '派送方式', 'return_shipping_surcharge': '退运附加',
  60. 'work_order_count': '工单数量', 'bill_remark': '账单备注',
  61. 'remark': '订单备注',
  62. },
  63. 'freight_info': {
  64. 'estimated_inbound_time': '预计入库时间', 'cargo_type': '货物类型',
  65. 'pickup_way': '交货方式', 'warehouse': '交货仓库',
  66. 'pickup_address': '提货地址', 'pickup_contact': '提货联系人',
  67. 'pickup_phone': '提货联系电话', 'delivery_type': '派送类型',
  68. 'delivery_address': '派送地址', 'delivery_remark': '派送备注',
  69. 'oversea_warehouse': '海外仓',
  70. },
  71. 'package_summary': {
  72. 'box_count': '箱数', 'total_weight': '重量', 'weight_unit': '重量单位',
  73. 'total_volume': '体积', 'sku_count': 'SKU数量',
  74. 'clearance_total_price': '清关总价', 'clearance_currency': '清关币种',
  75. 'purchase_total_price': '采购总价', 'purchase_currency': '采购币种',
  76. },
  77. 'trader_info': {
  78. 'exporter': '出口商', 'importer': '进口商',
  79. 'coo_required': '是否做产地证',
  80. },
  81. },
  82. 'packages': {
  83. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  84. 'sku_summary': 'SKU', 'product_name_summary': '商品名',
  85. 'box_quantity': '箱数', 'box_length_cm': '单箱长(CM)',
  86. 'box_width_cm': '单箱宽(CM)', 'box_height_cm': '单箱高(CM)',
  87. 'gross_weight_kg': '单箱毛重量(KG)', 'net_weight_kg': '单箱净重量(KG)',
  88. 'is_over_length': '长度是否超限', 'is_over_width': '宽度是否超限',
  89. 'is_over_height': '高度是否超限', 'is_over_weight': '重量是否超限',
  90. },
  91. 'package_items': {
  92. 'shipment_id': 'SHIPMENT ID', 'reference_id': 'REFERENCE ID',
  93. 'box_specification': '箱规', 'box_specification_unit': '箱规单位',
  94. 'package_gross_weight_kg': '箱单单箱毛重(KG)',
  95. 'package_net_weight_kg': '箱单单箱净重(KG)',
  96. 'inspection_result': '查验结果', 'exception_reason': '异常原因',
  97. 'inspection_photo_count': '查验图片数量', 'sku': 'SKU',
  98. 'units_per_box': '单箱个数', 'declaration_type': '报关类型',
  99. 'box_number': '箱号', 'item_gross_weight_kg': '商品单箱毛重量(KG)',
  100. 'item_net_weight_kg': '商品单箱净重量(KG)', 'chinese_name': '中文品名',
  101. 'english_name': '英文名称', 'brand_type': '品牌类型', 'brand': '品牌',
  102. 'model': '型号', 'material_cn': '材质(CN)', 'material_en': '材质(EN)',
  103. 'purpose_cn': '用途', 'goods_attributes': '商品属性',
  104. 'declaration_hs_code': '报关编码', 'clearance_hs_code': '清关编码',
  105. 'material_ratio': '材质占比', 'clearance_unit_price': '清关单价',
  106. 'clearance_currency': '清关币种', 'purchase_unit_price': '采购单价',
  107. 'purchase_currency': '采购币种', 'product_image_count': '商品图片数量',
  108. 'remark': '备注',
  109. },
  110. 'dw_auth': {
  111. 'fba_id': 'FBAID', 'dw_start': 'DW开始时间', 'dw_end': 'DW结束时间',
  112. 'dw_display': 'DW', 'authorization_status': '客户授权状态',
  113. },
  114. 'attachments': {
  115. 'category': '附件分类', 'file_name': '文件名称',
  116. 'file_extension': '文件类型', 'is_image': '是否图片',
  117. 'preview_url': '预览链接', 'download_url': '下载链接',
  118. 'cost_name': '收费项目',
  119. },
  120. 'inbound_summary': {
  121. 'inbound_status': '入库状态', 'inbound_time': '入库时间',
  122. 'inbound_operator': '操作人', 'warehouse': '仓库',
  123. 'abnormal_reason': '异常原因', 'inbound_photo_count': '入库图片数量',
  124. 'forecast_pwv_summary': '预报件重体', 'inbound_pwv_summary': '入库件重体',
  125. },
  126. 'inbound': {
  127. 'has_label': '是否贴标', 'shipment_id': 'SHIPMENT ID',
  128. 'inbound_quantity': '入库件数',
  129. 'measurement_photo_count': '测量图片数量',
  130. 'box_specification': '入库箱规', 'weight_mode': None, 'weight': None,
  131. 'weight_unit': '重量单位', 'is_over_length': '长度是否超限',
  132. 'is_over_width': '宽度是否超限', 'is_over_height': '高度是否超限',
  133. 'is_over_weight': '重量是否超限', 'operated_at': '操作时间',
  134. },
  135. 'checks': {
  136. 'shipment_id': '货件编号', 'sku': 'SKU', 'box_number': '箱号',
  137. 'box_quantity': '箱数', 'box_specification': '箱规',
  138. 'inspection_result': '查验结果',
  139. 'inspection_photo_count': '查验图片数量', 'remark': '备注',
  140. 'inspector': '查验人', 'inspected_at': '查验时间',
  141. },
  142. 'tracks': {
  143. 'track_type': '轨迹类型', 'status': '轨迹节点', 'location': '轨迹地点',
  144. 'occurred_at': '时间', 'tracking_number': '跟踪号',
  145. 'shipment_id': 'SHIPMENT ID', 'content': '轨迹内容',
  146. },
  147. 'operation_logs': {
  148. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  149. },
  150. 'cost_logs': {
  151. 'operated_at': '操作时间', 'content': '操作内容', 'operator': '操作人',
  152. },
  153. 'delivery_summary': {
  154. 'master_tracking_number': '主跟踪号', 'sub_order_count': '子单数量',
  155. },
  156. 'delivery': {'sub_tracking_number': '子跟踪号'},
  157. }
  158. ORDER_DETAIL_STATUS_FIELDS = {
  159. 'stage': '阶段', 'label': '节点', 'state': '状态',
  160. 'occurred_at': '时间', 'time_kind': '时间类型',
  161. }
  162. ORDER_DETAIL_STATES = {
  163. 'completed': '已完成', 'in_progress': '进行中',
  164. 'pending': '待完成', 'hidden': '不展示',
  165. }
  166. ORDER_DETAIL_TIME_KINDS = {
  167. 'actual': '实际', 'estimated': '预计', 'empty': '暂无',
  168. }
  169. TABLE_COLUMNS = {
  170. 'query_order_exact': {
  171. 'order_number': ('订单号',),
  172. 'reference_number': ('客户参考号',),
  173. 'status_txt_name': ('状态',),
  174. 'check_status_txt_name': ('是否已查验',),
  175. 'customer_name': ('客户名称',),
  176. 'customer_account_type_name': ('客户属性',),
  177. 'inbound_date': ('入库时间',),
  178. 'wo_num': ('未完成工单',),
  179. 'product_name': ('物流产品',),
  180. 'inbound_pieces': ('件数',),
  181. 'inbound_volume': ('体积(CBM)',),
  182. 'inbound_weight': ('重量(KG)',),
  183. 'pro_cn_name': ('品名',),
  184. 'export_declaration_type': ('报关方式',),
  185. 'merge_declare_number': ('合并报关单号',),
  186. 'delivery_address': ('派送地址',),
  187. 'container_code': ('柜号',),
  188. 'out_status_txt': ('排舱单状态',),
  189. 'hinge_of_destination': ('目的港',),
  190. 'etd': ('ETD',),
  191. 'atd': ('ATD',),
  192. 'eta': ('ETA',),
  193. 'ata': ('ATA',),
  194. 'release_time': ('清关放行时间',),
  195. 'oversea_inbound_date': ('海外入库时间',),
  196. 'appt_time': ('APPT时间',),
  197. 'est_loading_time': ('预计装柜时间',),
  198. 'pickup_time': ('海外提柜时间',),
  199. 'delivery_way_title': ('派送方式',),
  200. 'tracking_number': ('快递单号', '承运商跟踪号码'),
  201. 'shipment_id': ('Shipment ID',),
  202. 'goods_attribute': ('商品属性',),
  203. 'sku': ('SKU',),
  204. 'sales_user': ('商务经理',),
  205. 'service_user': ('客户经理',),
  206. 'department_name': ('事业部',),
  207. 'remark': ('订单备注',),
  208. 'importer_name': ('进口商',),
  209. 'warehouse_name': ('交货仓库',),
  210. 'paid_status_name': ('付款状态',),
  211. },
  212. 'query_track': {
  213. 'status': ('轨迹节点', '轨迹状态,如:开始集港、离港放行、清关、配送等'),
  214. 'location': ('轨迹地点', '发生地点'),
  215. 'time': ('时间', '轨迹发生时间(已转换为用户时区)'),
  216. 'content': ('轨迹内容', '详细描述'),
  217. 'tracking_number': ('跟踪号', '快递单号'),
  218. 'shipment_id': ('Shipment ID', '包裹ID'),
  219. },
  220. 'query_customs_declaration_files': {
  221. 'outbound_number': ('排舱单号',),
  222. 'order_number': ('订单号',),
  223. 'file_name': ('文件名',),
  224. 'file_type': ('文件类型',),
  225. 'file_url': ('文件链接',),
  226. },
  227. 'query_outbound_list': {
  228. 'outbound_number': ('排舱单号',),
  229. 'direct_send': ('直送柜',),
  230. 'remark': ('备注',),
  231. 'cargo_type': ('超长超重',),
  232. 'warehouse_name': ('集货仓库',),
  233. 'status': ('状态',),
  234. 'so_number': ('SO号',),
  235. 'container_code': ('柜号',),
  236. 'seal_number': ('封条号',),
  237. 'container_type': ('柜型',),
  238. 'shipping_method': ('运输方式',),
  239. 'total_volume': ('体积(CBM)',),
  240. 'total_weight': ('重量(KG)',),
  241. 'ship_schedule': ('船期',),
  242. 'closing_time': ('截关时间',),
  243. 'est_loading_time': ('预计装柜时间',),
  244. 'operator': ('操作人',),
  245. 'operation_modes': ('拖报清方式',),
  246. 'operation_time': ('操作时间',),
  247. 'ship_company': ('船司',),
  248. 'vessel_name': ('船名航次',),
  249. 'cutoff_time_si': ('截SI时间',),
  250. 'clearance_port': ('清关口岸',),
  251. 'loading_port': ('起运港',),
  252. 'destination_port': ('目的港',),
  253. 'transit_port': ('中转港',),
  254. 'etd': ('ETD',),
  255. 'eta': ('ETA',),
  256. 'has_fda': ('是否含FDA认证商品',),
  257. 'has_cpsc': ('是否含CPSC商品',),
  258. 'has_food': ('是否含食品',),
  259. },
  260. 'query_outbound_detail': {
  261. 'order_number': ('订单号',),
  262. 'cargo_type': ('超长超重',),
  263. 'customs_files': ('报关资料',),
  264. 'reference_number': ('客户参考号',),
  265. 'customer_name': ('客户名称',),
  266. 'declaration_type': ('报关方式',),
  267. 'merge_declare_number': ('合并报关单号',),
  268. 'order_remark': ('订单备注',),
  269. 'bl_number': ('提单号',),
  270. 'container_code': ('柜号',),
  271. 'customer_service': ('客户经理',),
  272. 'est_inbound_date': ('预计入库时间',),
  273. 'inbound_date': ('实际入库时间',),
  274. 'status': ('状态',),
  275. 'pieces': ('预报件数 / 入库件数',),
  276. 'weight': ('预报实重(KG) / 入库实重(KG)',),
  277. 'volume': ('预报体积(m³) / 入库体积(m³)',),
  278. 'pickup_place': ('交货地',),
  279. 'product_name': ('物流产品',),
  280. 'goods_name': ('品名',),
  281. 'closing_time': ('截关时间',),
  282. 'clearance_remark': ('报关备注',),
  283. 'import_clearance_remark': ('清关备注',),
  284. 'delivery_address': ('派送地址',),
  285. 'delivery_type': ('派送类型',),
  286. 'delivery_way': ('派送方式',),
  287. 'channel': ('派送渠道',),
  288. 'country_name': ('目的国',),
  289. 'importer_name': ('进口商',),
  290. 'vat_type': ('清关税号',),
  291. 'packing_type': ('货物类型',),
  292. 'is_abnormal': ('是否问题件',),
  293. 'package_method': ('包装类型',),
  294. 'order_reply': ('到货回复',),
  295. 'is_must_load': ('订单是否必装',),
  296. 'has_fda': ('是否含FDA认证商品',),
  297. 'has_cpsc': ('是否含CPSC商品',),
  298. 'has_food': ('是否含食品',),
  299. },
  300. }
  301. OUTBOUND_DETAIL_SUMMARY = {
  302. 'bl_number': '提单号',
  303. 'container_code': '柜号',
  304. 'container_type': '柜型',
  305. 'total_volume': '总体积',
  306. 'total_weight': '总重量',
  307. 'total_pieces': '总件数',
  308. 'sku': 'SKU',
  309. 'buy_declaration_count': '买单报关数量',
  310. 'general_declaration_count': '一般贸易报关数量',
  311. 'must_load': '必装单量/体积',
  312. 'backup_load': '备装单量/体积',
  313. }
  314. FIELD_LABELS = {
  315. 'query_order_exact': {
  316. 'order_number': '订单号',
  317. 'order_numbers': '订单号',
  318. 'reference_number': '客户参考号',
  319. 'reference_numbers': '客户参考号',
  320. 'tracking_number': '快递单号',
  321. 'tracking_numbers': '快递单号',
  322. 'outbound_number': '排舱单号',
  323. 'outbound_numbers': '排舱单号',
  324. 'container_code': '柜号',
  325. 'container_codes': '柜号',
  326. 'so_number': 'SO号',
  327. 'so_numbers': 'SO号',
  328. 'shipment_id': 'Shipment ID',
  329. 'receiver_country': '收货国家',
  330. 'product_ids': '物流产品',
  331. 'customer_ids': '客户',
  332. 'sales_id': '销售人员',
  333. 'warehouse_ids': '仓库',
  334. 'department_id': '事业部',
  335. 'inbound_date_start': '入库开始日期',
  336. 'inbound_date_end': '入库结束日期',
  337. 'outbound_date_start': '出库开始日期',
  338. 'outbound_date_end': '出库结束日期',
  339. 'page': '页码',
  340. 'limit': '每页数量',
  341. },
  342. 'query_track': {
  343. 'order_id': '订单ID',
  344. 'order_number': '订单号',
  345. 'tracking_number': '快递单号',
  346. 'page': '页码',
  347. 'limit': '每页数量',
  348. },
  349. 'query_customs_declaration_files': {
  350. 'outbound_numbers': '排舱单号',
  351. 'order_numbers': '订单号',
  352. 'page': '页码',
  353. 'limit': '每页数量',
  354. },
  355. 'query_outbound_list': {
  356. 'outbound_numbers': '排舱单号',
  357. 'order_numbers': '订单号',
  358. 'container_codes': '柜号',
  359. 'so_numbers': 'SO号',
  360. 'bl_numbers': '提单号',
  361. 'outbound_status': '排舱状态',
  362. 'shipping_method': '运输方式',
  363. 'warehouse_id': '集货仓库',
  364. 'is_direct_send': '是否直送柜',
  365. 'page': '页码',
  366. 'limit': '每页数量',
  367. },
  368. 'query_outbound_detail': {
  369. 'outbound_number': '排舱单号',
  370. 'page': '页码',
  371. 'limit': '每页数量',
  372. },
  373. 'query_order_detail': {
  374. 'order_number': '订单号', 'section': '详情模块',
  375. 'page': '页码', 'limit': '每页数量',
  376. },
  377. 'list_order_filter_options': {
  378. 'filter_type': '筛选项类型',
  379. 'keyword': '关键词',
  380. 'page': '页码',
  381. 'limit': '每页数量',
  382. },
  383. 'list_outbound_filter_options': {
  384. 'filter_type': '筛选类别',
  385. 'keyword': '显示名称',
  386. 'page': '页码',
  387. 'limit': '每页数量',
  388. },
  389. 'list_pending_outbound_export_filter_options': {
  390. 'filter_type': '筛选项类型',
  391. 'product_type_id': '产品分类',
  392. 'keyword': '关键词',
  393. 'page': '页码',
  394. 'limit': '每页数量',
  395. },
  396. 'export_pending_outbound_orders': {
  397. 'number': '单号',
  398. 'product_type_id': '产品分类',
  399. 'product_id': '物流产品',
  400. 'order_warehouse_id': '集货仓库',
  401. 'receiver_country': '目的国',
  402. 'is_remove': '是否装柜剔除',
  403. 'address': '派送地址',
  404. 'inbound_date': '入库时间',
  405. 'status': '订单状态',
  406. 'merge_declare_number': '合并报关单号',
  407. 'importer_id': '进口商',
  408. 'packing_type': '货物类型',
  409. 'is_battery': '带电属性',
  410. 'is_magnetic': '带磁属性',
  411. 'is_wood': '带木属性',
  412. 'is_other': '其他商品属性',
  413. 'is_fda': 'FDA产品属性',
  414. 'is_toy': '玩具属性',
  415. 'is_ultra_limit': '超长超重属性',
  416. 'is_sensitive': '敏感货属性',
  417. 'is_food': '食品属性',
  418. 'no_property': '无属性',
  419. },
  420. 'export_out_of_province_port_data': {
  421. 'outbound_numbers': '排舱单号',
  422. 'container_codes': '柜号',
  423. 'bl_numbers': '提单号',
  424. 'so_numbers': 'SO号',
  425. 'file_type': '资料类型',
  426. },
  427. 'query_export_task': {
  428. 'task_ref': '导出任务引用',
  429. },
  430. }
  431. ERROR_MESSAGES = {
  432. 'MCP_1101': '设备配置已失效,请重新生成配置',
  433. 'MCP_1102': '设备会话已过期,请重新连接',
  434. 'MCP_1103': '员工账号不可用,请联系管理员',
  435. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  436. 'MCP_1201': '工具当前不可用',
  437. 'MCP_1202': '工具当前不可用',
  438. 'MCP_1301': '没有权限使用此工具',
  439. 'MCP_1501': '目标数据不可用',
  440. 'MCP_1502': '结果过多,请缩小查询范围',
  441. 'MCP_1601': '没有可导出的数据',
  442. 'MCP_9001': '工具调用失败,请稍后重试',
  443. }
  444. NON_RETRYABLE_CODES = frozenset((
  445. 'MCP_1101',
  446. 'MCP_1102',
  447. 'MCP_1103',
  448. 'MCP_1104',
  449. 'MCP_1201',
  450. 'MCP_1202',
  451. 'MCP_1301',
  452. 'MCP_1401',
  453. 'MCP_1501',
  454. 'MCP_1502',
  455. 'MCP_1601',
  456. ))
  457. def handles(self, tool_name):
  458. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  459. # Convert a backend envelope into text and structured display data.
  460. def present(self, tool_name, tool_result):
  461. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  462. return self._format_error()
  463. code = str(tool_result.get('code') or '').strip()
  464. meta = self._build_meta(tool_result.get('meta'))
  465. if code not in ('MCP_0000', '0'):
  466. return self._business_error(
  467. tool_name,
  468. code or 'MCP_9001',
  469. tool_result.get('msg'),
  470. meta,
  471. )
  472. data = tool_result.get('data')
  473. if not isinstance(data, dict):
  474. return self._format_error(meta)
  475. if tool_name in self.DETAIL_TOOLS:
  476. return self._present_outbound_detail(
  477. tool_name,
  478. data,
  479. tool_result.get('meta'),
  480. meta,
  481. )
  482. if tool_name in self.ORDER_DETAIL_TOOLS:
  483. return self._present_order_detail(data, tool_result.get('meta'), meta)
  484. if tool_name in self.TABLE_TOOLS:
  485. return self._present_table(
  486. tool_name,
  487. data,
  488. tool_result.get('meta'),
  489. meta,
  490. )
  491. if tool_name in self.OPTION_TOOLS:
  492. return self._present_options(data, tool_result.get('meta'), meta)
  493. if tool_name in self.EXPORT_TOOLS:
  494. return self._present_export_submission(data, meta)
  495. return self._present_export_task(data, meta)
  496. def _present_order_detail(self, data, raw_meta, meta):
  497. if set(data) != {'section', 'order_number', 'payload'}:
  498. return self._format_error(meta)
  499. section = data.get('section')
  500. order_number = data.get('order_number')
  501. payload = data.get('payload')
  502. if (
  503. section not in self.ORDER_DETAIL_SECTIONS
  504. or not isinstance(order_number, str) or not order_number.strip()
  505. or not isinstance(payload, dict)
  506. ):
  507. return self._format_error(meta)
  508. content = {
  509. '订单号': order_number.strip(),
  510. '详情模块': self.ORDER_DETAIL_SECTIONS[section],
  511. }
  512. if section == 'all':
  513. all_content = self._present_order_detail_all(payload)
  514. if all_content is None:
  515. return self._format_error(meta)
  516. content.update(all_content)
  517. elif section == 'overview':
  518. expected = {
  519. 'status_nodes', 'order_info', 'freight_info',
  520. 'package_summary', 'trader_info',
  521. }
  522. if set(payload) != expected or not isinstance(payload['status_nodes'], list):
  523. return self._format_error(meta)
  524. nodes = []
  525. for row in payload['status_nodes']:
  526. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  527. if translated is None:
  528. return self._format_error(meta)
  529. state = row.get('state')
  530. time_kind = row.get('time_kind')
  531. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  532. return self._format_error(meta)
  533. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  534. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  535. nodes.append(translated)
  536. content['状态节点'] = nodes
  537. for raw_key, chinese_key in (
  538. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  539. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  540. ):
  541. translated = self._translate_exact(
  542. payload.get(raw_key),
  543. self.ORDER_DETAIL_FIELDS['overview'][raw_key],
  544. )
  545. if translated is None:
  546. return self._format_error(meta)
  547. content[chinese_key] = translated
  548. elif section == 'inbound':
  549. if set(payload) != {'summary', 'records'}:
  550. return self._format_error(meta)
  551. summary = self._translate_exact(
  552. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  553. )
  554. records = self._translate_order_detail_rows(section, payload.get('records'))
  555. if summary is None or records is None:
  556. return self._format_error(meta)
  557. content['入库概况'] = summary
  558. content['明细'] = records
  559. pagination = self._order_detail_pagination(raw_meta)
  560. if pagination is None:
  561. return self._format_error(meta)
  562. content['分页'] = pagination
  563. elif section == 'delivery':
  564. if set(payload) != {'summary', 'records'}:
  565. return self._format_error(meta)
  566. summary = self._translate_exact(
  567. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  568. )
  569. records = self._translate_order_detail_rows(section, payload.get('records'))
  570. if summary is None or records is None:
  571. return self._format_error(meta)
  572. content['派送汇总'] = summary
  573. content['明细'] = records
  574. pagination = self._order_detail_pagination(raw_meta)
  575. if pagination is None:
  576. return self._format_error(meta)
  577. content['分页'] = pagination
  578. else:
  579. if set(payload) != {'records'}:
  580. return self._format_error(meta)
  581. records = self._translate_order_detail_rows(section, payload.get('records'))
  582. pagination = self._order_detail_pagination(raw_meta)
  583. if records is None or pagination is None:
  584. return self._format_error(meta)
  585. content['明细'] = records
  586. content['分页'] = pagination
  587. text = json.dumps(content, ensure_ascii=False, indent=2)
  588. return self._success_result(content, text, meta)
  589. def _present_order_detail_all(self, payload):
  590. expected_sections = set(self.ORDER_DETAIL_SECTIONS) - {'all'}
  591. if set(payload) != expected_sections:
  592. return None
  593. overview = payload.get('overview')
  594. if not isinstance(overview, dict) or set(overview) != {
  595. 'status_nodes', 'order_info', 'freight_info', 'package_summary', 'trader_info',
  596. } or not isinstance(overview['status_nodes'], list):
  597. return None
  598. overview_content = {'状态节点': []}
  599. for row in overview['status_nodes']:
  600. translated = self._translate_exact(row, self.ORDER_DETAIL_STATUS_FIELDS)
  601. if translated is None:
  602. return None
  603. state = row.get('state')
  604. time_kind = row.get('time_kind')
  605. if state not in self.ORDER_DETAIL_STATES or time_kind not in self.ORDER_DETAIL_TIME_KINDS:
  606. return None
  607. translated['状态'] = self.ORDER_DETAIL_STATES[state]
  608. translated['时间类型'] = self.ORDER_DETAIL_TIME_KINDS[time_kind]
  609. overview_content['状态节点'].append(translated)
  610. for raw_key, chinese_key in (
  611. ('order_info', '订单信息'), ('freight_info', '货运信息'),
  612. ('package_summary', '箱单汇总'), ('trader_info', '进出口商'),
  613. ):
  614. translated = self._translate_exact(
  615. overview.get(raw_key), self.ORDER_DETAIL_FIELDS['overview'][raw_key]
  616. )
  617. if translated is None:
  618. return None
  619. overview_content[chinese_key] = translated
  620. result = {'订单概览': overview_content}
  621. for section, label in self.ORDER_DETAIL_SECTIONS.items():
  622. if section in ('overview', 'all'):
  623. continue
  624. translated = self._present_order_detail_all_section(section, payload.get(section))
  625. if translated is None:
  626. return None
  627. result[label] = translated
  628. return result
  629. def _present_order_detail_all_section(self, section, payload):
  630. if not isinstance(payload, dict) or 'pagination' not in payload:
  631. return None
  632. pagination = self._order_detail_pagination(payload.get('pagination'))
  633. if pagination is None:
  634. return None
  635. if section == 'inbound':
  636. if set(payload) != {'summary', 'records', 'pagination'}:
  637. return None
  638. summary = self._translate_exact(
  639. payload.get('summary'), self.ORDER_DETAIL_FIELDS['inbound_summary']
  640. )
  641. records = self._translate_order_detail_rows(section, payload.get('records'))
  642. if summary is None or records is None:
  643. return None
  644. return {'入库概况': summary, '明细': records, '分页': pagination}
  645. if section == 'delivery':
  646. if set(payload) != {'summary', 'records', 'pagination'}:
  647. return None
  648. summary = self._translate_exact(
  649. payload.get('summary'), self.ORDER_DETAIL_FIELDS['delivery_summary']
  650. )
  651. records = self._translate_order_detail_rows(section, payload.get('records'))
  652. if summary is None or records is None:
  653. return None
  654. return {'派送汇总': summary, '明细': records, '分页': pagination}
  655. if set(payload) != {'records', 'pagination'}:
  656. return None
  657. records = self._translate_order_detail_rows(section, payload.get('records'))
  658. if records is None:
  659. return None
  660. return {'明细': records, '分页': pagination}
  661. def _translate_order_detail_rows(self, section, records):
  662. if not isinstance(records, list):
  663. return None
  664. mapping = self.ORDER_DETAIL_FIELDS.get(section)
  665. if not isinstance(mapping, dict):
  666. return None
  667. translated_rows = []
  668. for row in records:
  669. translated = self._translate_exact(row, mapping)
  670. if translated is None:
  671. return None
  672. if section == 'inbound':
  673. mode = row.get('weight_mode')
  674. if mode not in ('single_box', 'total'):
  675. return None
  676. translated[
  677. '单箱入库重量' if mode == 'single_box' else '总重量KG'
  678. ] = row.get('weight', '')
  679. translated_rows.append(translated)
  680. return translated_rows
  681. @staticmethod
  682. def _translate_exact(value, mapping):
  683. if not isinstance(value, dict) or set(value) != set(mapping):
  684. return None
  685. result = {}
  686. for key, label in mapping.items():
  687. if label is None:
  688. continue
  689. item = value.get(key, '')
  690. if isinstance(item, (dict, list)):
  691. return None
  692. result[label] = '' if item is None else item
  693. return result
  694. @staticmethod
  695. def _order_detail_pagination(raw_meta):
  696. if not isinstance(raw_meta, dict):
  697. return None
  698. if not all(key in raw_meta for key in ('page', 'limit', 'has_more')):
  699. return None
  700. page = raw_meta.get('page')
  701. limit = raw_meta.get('limit')
  702. has_more = raw_meta.get('has_more')
  703. if isinstance(page, bool) or not isinstance(page, int) or page < 1:
  704. return None
  705. if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
  706. return None
  707. if not isinstance(has_more, bool):
  708. return None
  709. return {'页码': page, '每页数量': limit, '是否还有更多': has_more}
  710. # Map local tool exceptions without exposing internal error details.
  711. def present_exception(self, tool_name, exception):
  712. if not self.handles(tool_name):
  713. return self._format_error()
  714. message = str(exception or '').strip()
  715. if isinstance(exception, ValueError):
  716. label = self._find_field_label(tool_name, message)
  717. return self._error_result(
  718. 'MCP_1401',
  719. self._parameter_message(label),
  720. False,
  721. )
  722. if message == DEVICE_INVALID_MESSAGE:
  723. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  724. if message.lower().startswith('tool disabled'):
  725. return self._error_result('MCP_1202', '工具当前不可用', False)
  726. return self._error_result(
  727. 'MCP_9001',
  728. '工具调用失败,请稍后重试',
  729. True,
  730. )
  731. def _present_table(self, tool_name, data, raw_meta, meta):
  732. columns = data.get('columns')
  733. records = data.get('records')
  734. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  735. return self._format_error(meta)
  736. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  737. if not isinstance(allowed_columns, dict):
  738. return self._format_error(meta)
  739. headers = []
  740. keys = []
  741. for column in columns:
  742. if not isinstance(column, dict):
  743. return self._format_error(meta)
  744. key = column.get('key')
  745. label = column.get('name')
  746. if not isinstance(key, str) or not key.strip():
  747. return self._format_error(meta)
  748. if not isinstance(label, str) or not label.strip():
  749. return self._format_error(meta)
  750. key = key.strip()
  751. definition = allowed_columns.get(key)
  752. if not isinstance(definition, tuple) or not definition:
  753. return self._format_error(meta)
  754. keys.append(key)
  755. header = {'label': definition[0]}
  756. if len(definition) > 1:
  757. header['description'] = definition[1]
  758. headers.append(header)
  759. rows = []
  760. for record in records:
  761. if not isinstance(record, dict):
  762. return self._format_error(meta)
  763. rows.append([
  764. '' if record.get(key) is None else record.get(key, '')
  765. for key in keys
  766. ])
  767. content = {
  768. 'summary': self._safe_text(data.get('summary')),
  769. 'headers': headers,
  770. 'rows': rows,
  771. }
  772. tips = self._safe_tips(data.get('tips'))
  773. if tips:
  774. content['tips'] = tips
  775. pagination = self._build_pagination(raw_meta)
  776. if pagination:
  777. content['pagination'] = pagination
  778. return self._success_result(content, self._render_table(content), meta)
  779. def _present_outbound_detail(self, tool_name, data, raw_meta, meta):
  780. summary = data.get('summary')
  781. columns = data.get('columns')
  782. records = data.get('records')
  783. if not isinstance(summary, dict):
  784. return self._format_error(meta)
  785. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  786. return self._format_error(meta)
  787. if any(key not in summary for key in self.OUTBOUND_DETAIL_SUMMARY):
  788. return self._format_error(meta)
  789. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  790. headers = []
  791. keys = []
  792. for column in columns:
  793. if not isinstance(column, dict):
  794. return self._format_error(meta)
  795. key = column.get('key')
  796. definition = allowed_columns.get(key) if isinstance(key, str) else None
  797. if not isinstance(definition, tuple) or not definition:
  798. return self._format_error(meta)
  799. keys.append(key)
  800. headers.append({'label': definition[0]})
  801. rows = []
  802. for record in records:
  803. if not isinstance(record, dict):
  804. return self._format_error(meta)
  805. row = []
  806. for key in keys:
  807. value = '' if record.get(key) is None else record.get(key, '')
  808. if key == 'customs_files':
  809. if not isinstance(value, list):
  810. return self._format_error(meta)
  811. files = []
  812. for item in value:
  813. if not isinstance(item, dict):
  814. return self._format_error(meta)
  815. files.append({
  816. '文件名称': item.get('file_name', ''),
  817. '文件类型': item.get('file_type', ''),
  818. '文件链接': item.get('file_url', ''),
  819. })
  820. value = files
  821. row.append(value)
  822. rows.append(row)
  823. summary_keys = list(self.OUTBOUND_DETAIL_SUMMARY.keys())
  824. content = {
  825. 'summary': {
  826. 'headers': [
  827. {'label': self.OUTBOUND_DETAIL_SUMMARY[key]}
  828. for key in summary_keys
  829. ],
  830. 'row': [summary.get(key, '') for key in summary_keys],
  831. },
  832. 'details': {
  833. 'headers': headers,
  834. 'rows': rows,
  835. },
  836. }
  837. tips = self._safe_tips(data.get('tips'))
  838. if tips:
  839. content['details']['tips'] = tips
  840. pagination = self._build_pagination(raw_meta)
  841. if pagination:
  842. content['details']['pagination'] = pagination
  843. return self._success_result(
  844. content,
  845. self._render_outbound_detail(content),
  846. meta,
  847. )
  848. @classmethod
  849. def _render_outbound_detail(cls, content):
  850. lines = ['排舱汇总:']
  851. summary = content['summary']
  852. for header, value in zip(summary['headers'], summary['row']):
  853. lines.append('- {0}: {1}'.format(header['label'], value))
  854. lines.append('订单明细:')
  855. details = content['details']
  856. lines.append('表头共 {0} 列:'.format(len(details['headers'])))
  857. for index, header in enumerate(details['headers'], start=1):
  858. lines.append('{0}. {1}'.format(index, header['label']))
  859. for index, row in enumerate(details['rows'], start=1):
  860. lines.append('记录 {0}:'.format(index))
  861. for header, value in zip(details['headers'], row):
  862. if isinstance(value, (dict, list)):
  863. value = json.dumps(value, ensure_ascii=False)
  864. lines.append('- {0}: {1}'.format(header['label'], value))
  865. tips = details.get('tips') or []
  866. if tips:
  867. lines.append('提示:{0}'.format(';'.join(tips)))
  868. return '\n'.join(lines)
  869. def _present_options(self, data, raw_meta, meta):
  870. records = data.get('records')
  871. if not isinstance(records, list):
  872. return self._format_error(meta)
  873. rows = []
  874. for record in records:
  875. if not isinstance(record, dict):
  876. return self._format_error(meta)
  877. rows.append([
  878. record.get('value', ''),
  879. self._safe_text(record.get('label')),
  880. self._safe_text(record.get('code')),
  881. ])
  882. content = {
  883. 'headers': [
  884. {'label': '可传值'},
  885. {'label': '显示名称'},
  886. {'label': '业务编码'},
  887. ],
  888. 'rows': rows,
  889. }
  890. pagination = self._build_pagination(raw_meta)
  891. if pagination:
  892. content['pagination'] = pagination
  893. return self._success_result(content, self._render_table(content), meta)
  894. def _present_export_submission(self, data, meta):
  895. expected = {'task_ref', 'status', 'retry_after_seconds'}
  896. if set(data) != expected:
  897. return self._format_error(meta)
  898. task_ref = data.get('task_ref')
  899. retry_after = data.get('retry_after_seconds')
  900. if (
  901. not isinstance(task_ref, str) or not task_ref.strip()
  902. or data.get('status') != 'queued'
  903. or isinstance(retry_after, bool)
  904. or not isinstance(retry_after, int)
  905. or retry_after <= 0
  906. ):
  907. return self._format_error(meta)
  908. task = {
  909. 'task_ref': task_ref.strip(),
  910. 'status': 'queued',
  911. 'retry_after_seconds': retry_after,
  912. }
  913. content = {
  914. 'message': '导出任务已提交',
  915. 'task': task,
  916. }
  917. text = (
  918. '导出任务已提交\n'
  919. '- 任务引用: {0}\n'
  920. '- 建议 {1} 秒后单独查询任务状态'
  921. ).format(task['task_ref'], retry_after)
  922. return self._success_result(content, text, meta)
  923. def _present_export_task(self, data, meta):
  924. task_ref = data.get('task_ref')
  925. status = data.get('status')
  926. if (
  927. not isinstance(task_ref, str)
  928. or not task_ref.strip()
  929. or status not in ('queued', 'running', 'completed', 'failed')
  930. ):
  931. return self._format_error(meta)
  932. task = {'task_ref': task_ref.strip(), 'status': status}
  933. if status in ('queued', 'running'):
  934. if set(data) != {'task_ref', 'status', 'retry_after_seconds'}:
  935. return self._format_error(meta)
  936. retry_after = data.get('retry_after_seconds')
  937. if (
  938. isinstance(retry_after, bool)
  939. or not isinstance(retry_after, int)
  940. or retry_after <= 0
  941. ):
  942. return self._format_error(meta)
  943. task['retry_after_seconds'] = retry_after
  944. label = '等待中' if status == 'queued' else '生成中'
  945. content = {'message': '导出任务{0}'.format(label), 'task': task}
  946. text = (
  947. '导出任务{0}\n- 任务引用: {1}\n- 建议 {2} 秒后再次查询'
  948. ).format(label, task['task_ref'], retry_after)
  949. return self._success_result(content, text, meta)
  950. if status == 'failed':
  951. if set(data) != {'task_ref', 'status'}:
  952. return self._format_error(meta)
  953. content = {'message': '导出任务失败,请重新提交', 'task': task}
  954. text = '导出任务失败,请重新提交'
  955. return self._success_result(content, text, meta)
  956. if set(data) != {'task_ref', 'status', 'files'}:
  957. return self._format_error(meta)
  958. files = data.get('files')
  959. if not isinstance(files, list) or not files:
  960. return self._format_error(meta)
  961. safe_files = []
  962. for item in files:
  963. if not isinstance(item, dict) or set(item) != {'label', 'url'}:
  964. return self._format_error(meta)
  965. label = item.get('label')
  966. url = item.get('url')
  967. if (
  968. not isinstance(label, str) or not label.strip()
  969. or not self._valid_http_url(url)
  970. ):
  971. return self._format_error(meta)
  972. safe_files.append({'label': label.strip(), 'url': url.strip()})
  973. content = {
  974. 'message': '文件已生成',
  975. 'task': task,
  976. 'files': safe_files,
  977. }
  978. lines = ['文件已生成']
  979. for item in safe_files:
  980. lines.append('- {0}: {1}'.format(item['label'], item['url']))
  981. return self._success_result(content, '\n'.join(lines), meta)
  982. def _valid_http_url(self, value):
  983. if not isinstance(value, str) or not value.strip():
  984. return False
  985. if value != value.strip() or '\\' in value or any(
  986. character.isspace() or ord(character) < 32 or ord(character) == 127
  987. for character in value
  988. ):
  989. return False
  990. try:
  991. parsed = urlparse(value)
  992. port = parsed.port
  993. return (
  994. parsed.scheme in ('http', 'https')
  995. and bool(parsed.hostname)
  996. and parsed.username is None
  997. and parsed.password is None
  998. and (port is None or 0 < port <= 65535)
  999. )
  1000. except ValueError:
  1001. return False
  1002. def _business_error(self, tool_name, code, raw_message, meta):
  1003. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  1004. logger.warning(
  1005. 'Unknown MCP business error code',
  1006. extra={
  1007. 'request_id': meta.get('request_id', ''),
  1008. 'tool_code': tool_name,
  1009. 'backend_code': code,
  1010. 'response_code': 'MCP_9001',
  1011. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  1012. },
  1013. )
  1014. code = 'MCP_9001'
  1015. if code == 'MCP_1401':
  1016. label = self._find_field_label(tool_name, raw_message)
  1017. message = self._parameter_message(label)
  1018. else:
  1019. message = self.ERROR_MESSAGES[code]
  1020. retryable = code not in self.NON_RETRYABLE_CODES
  1021. return self._error_result(code, message, retryable, meta)
  1022. def _find_field_label(self, tool_name, raw_message):
  1023. message = str(raw_message or '')
  1024. fields = self.FIELD_LABELS.get(tool_name, {})
  1025. for field in sorted(fields, key=len, reverse=True):
  1026. if field in message:
  1027. return fields[field]
  1028. return ''
  1029. @staticmethod
  1030. def _parameter_message(label):
  1031. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  1032. @staticmethod
  1033. def _build_meta(raw_meta):
  1034. if not isinstance(raw_meta, dict):
  1035. return {}
  1036. request_id = raw_meta.get('request_id')
  1037. if not isinstance(request_id, str) or not request_id.strip():
  1038. return {}
  1039. return {'request_id': request_id.strip()}
  1040. @staticmethod
  1041. def _build_pagination(raw_meta):
  1042. if not isinstance(raw_meta, dict):
  1043. return {}
  1044. return {
  1045. key: raw_meta[key]
  1046. for key in ('page', 'limit', 'has_more', 'total')
  1047. if key in raw_meta
  1048. }
  1049. @staticmethod
  1050. def _safe_text(value):
  1051. if value is None:
  1052. return ''
  1053. return str(value).strip()
  1054. @classmethod
  1055. def _safe_tips(cls, value):
  1056. if not isinstance(value, list):
  1057. return []
  1058. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  1059. @classmethod
  1060. def _render_table(cls, content):
  1061. headers = content.get('headers') or []
  1062. rows = content.get('rows') or []
  1063. lines = []
  1064. summary = cls._safe_text(content.get('summary'))
  1065. if summary:
  1066. lines.append(summary)
  1067. lines.append('表头共 {0} 列:'.format(len(headers)))
  1068. for index, header in enumerate(headers, start=1):
  1069. lines.append('{0}. {1}'.format(index, header['label']))
  1070. for index, row in enumerate(rows, start=1):
  1071. lines.append('记录 {0}:'.format(index))
  1072. for header, value in zip(headers, row):
  1073. if isinstance(value, (dict, list)):
  1074. value = json.dumps(value, ensure_ascii=False)
  1075. lines.append('- {0}: {1}'.format(header['label'], value))
  1076. tips = content.get('tips') or []
  1077. if tips:
  1078. lines.append('提示:{0}'.format(';'.join(tips)))
  1079. return '\n'.join(lines)
  1080. @staticmethod
  1081. def _success_result(content, text, meta):
  1082. return {
  1083. 'structured_content': content,
  1084. 'text': text,
  1085. 'is_error': False,
  1086. 'meta': meta,
  1087. }
  1088. @staticmethod
  1089. def _error_result(code, message, retryable, meta=None):
  1090. return {
  1091. 'structured_content': {
  1092. 'code': code,
  1093. 'message': message,
  1094. 'retryable': retryable,
  1095. },
  1096. 'text': '{0}: {1}'.format(code, message),
  1097. 'is_error': True,
  1098. 'meta': meta or {},
  1099. }
  1100. @classmethod
  1101. def _format_error(cls, meta=None):
  1102. return cls._error_result(
  1103. 'MCP_9001',
  1104. '工具返回格式异常',
  1105. True,
  1106. meta,
  1107. )