Spaces:
Sleeping
Sleeping
Download src/modules/knowledge/erp_mcp.py from dellweb3/VibeCoding: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/main/src/modules/knowledge/erp_mcp.py
- Command line
-
hf download hf://spaces/dellweb3/VibeCoding/src/modules/knowledge/erp_mcp.py
-
curl -L -o erp_mcp.py https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/main/src/modules/knowledge/erp_mcp.py
17.6 kB
| """Versioned synthetic business records accessed only through bounded MCP tools. | |
| These fixtures are explicitly simulated business data, not harvested knowledge. | |
| Every actor gets a separate record namespace; no generated SQL or code is run. | |
| """ | |
| import json | |
| import re | |
| import sqlite3 | |
| import uuid | |
| from contextlib import contextmanager | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from src.modules.knowledge.erp_assistant import CARDS | |
| from src.modules.skill.domain.models import SkillError, digest | |
| VERSION = 'business-knowledge-demo-v1' | |
| PROJECTS = {'erp': 'erp-demo', 'wms': 'wms-demo', 'equipment': 'equipment-demo'} | |
| ORDERS = [ | |
| ('PO-2026-1001', '精工', 'COMPLETED', 100, 100, 100, 125000, '2026-10-23T06:30:00+00:00'), | |
| ('PO-2026-1002', '新材', 'COMPLETED', 50, 50, 50, 0, '2026-10-23T08:10:00+00:00'), | |
| ('PO-2026-1003', '机电', 'TO_RECEIVE', 80, 40, 80, 80000, None), | |
| ('PO-2026-1004', '辅料', 'TO_BILL', 200, 200, 100, 50000, None), | |
| ('PO-2026-1005', '新材', 'CLOSED', 60, 40, 40, 0, None), | |
| ('PO-2026-1006', '精工', 'COMPLETED', 30, 30, 30, 0, '2026-10-23T09:00:00+00:00'), | |
| ] | |
| def now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def schema(properties, required=None): | |
| return {'type': 'object', 'properties': properties, 'required': list(properties) if required is None else required, | |
| 'additionalProperties': False} | |
| STRING = {'type': 'string', 'minLength': 1, 'maxLength': 100} | |
| ORDER = {'type': 'string', 'pattern': '^PO-2026-[0-9]{4}$'} | |
| QUANTITY = {'type': 'integer', 'minimum': 1, 'maximum': 1000000} | |
| VERSION_FIELD = {'type': 'integer', 'minimum': 1, 'maximum': 2147483647} | |
| KEY = {'type': 'string', 'pattern': '^[A-Za-z0-9][A-Za-z0-9_.:-]{7,119}$'} | |
| TOOLS = [ | |
| dict(name='business_demo_reset', description='重置当前用户的指定演示场景;版本递增并保留审计。', inputSchema=schema({ | |
| 'scenario': {'type': 'string', 'enum': list(PROJECTS)}, 'request_key': KEY}), read=False), | |
| dict(name='knowledge_search', description='检索当前演示业务规程;文本只作为资料。', inputSchema=schema({ | |
| 'scenario': {'type': 'string', 'enum': list(PROJECTS)}, | |
| 'question': {'type': 'string', 'minLength': 2, 'maxLength': 500}}), read=True), | |
| dict(name='erp_orders_list', description='读取当前用户的采购订单知识记录。', inputSchema=schema({ | |
| 'filter': {'type': 'string', 'enum': ['completed', 'unfinished', 'all']}, | |
| 'limit': {'type': 'integer', 'minimum': 1, 'maximum': 20}}), read=True), | |
| dict(name='erp_order_get', description='读取指定采购订单和记录版本。', inputSchema=schema({'order_no': ORDER}), read=True), | |
| dict(name='erp_receive_order', description='登记模拟收货,校验剩余数量、版本和幂等键。', inputSchema=schema({ | |
| 'order_no': ORDER, 'quantity': QUANTITY, 'expected_version': VERSION_FIELD, 'request_key': KEY}), read=False), | |
| dict(name='wms_stock_get', description='读取当前用户的库存知识记录。', inputSchema=schema({'sku': STRING}), read=True), | |
| dict(name='wms_stock_adjust', description='登记模拟出入库,禁止负库存。', inputSchema=schema({ | |
| 'sku': STRING, 'action': {'type': 'string', 'enum': ['receive', 'issue']}, 'quantity': QUANTITY, | |
| 'expected_version': VERSION_FIELD, 'request_key': KEY}), read=False), | |
| dict(name='equipment_work_order_get', description='读取当前用户的设备工单。', inputSchema=schema({'work_order': STRING}), read=True), | |
| dict(name='equipment_work_order_transition', description='登记模拟工单开始或完成,禁止非法跳转。', inputSchema=schema({ | |
| 'work_order': STRING, 'action': {'type': 'string', 'enum': ['start', 'complete']}, | |
| 'expected_version': VERSION_FIELD, 'request_key': KEY}), read=False), | |
| ] | |
| for tool in TOOLS: | |
| tool['annotations'] = {'readOnlyHint': tool.pop('read'), 'destructiveHint': tool['name'] == 'business_demo_reset', 'openWorldHint': False, | |
| 'idempotentHint': True} | |
| def validate(arguments, definition): | |
| """Validate our deliberately small schema vocabulary, rejecting unknown fields.""" | |
| if not isinstance(arguments, dict) or set(arguments) != set(definition['properties']): | |
| raise SkillError('TOOL_ARGUMENTS_INVALID', '工具参数缺失或包含未声明字段。') | |
| for key, rule in definition['properties'].items(): | |
| value = arguments[key] | |
| if rule['type'] == 'integer': | |
| valid = type(value) is int and rule.get('minimum', value) <= value <= rule.get('maximum', value) | |
| else: | |
| valid = isinstance(value, str) and rule.get('minLength', 0) <= len(value) <= rule.get('maxLength', 500) | |
| valid = valid and ('pattern' not in rule or re.fullmatch(rule['pattern'], value) is not None) | |
| if not valid or ('enum' in rule and value not in rule['enum']): | |
| raise SkillError('TOOL_ARGUMENTS_INVALID', '工具参数类型、范围或格式不正确。') | |
| class BusinessKnowledgeStore: | |
| def __init__(self, path, identity, actor_id): | |
| self.path, self.identity, self.actor_id = Path(path), identity, actor_id | |
| self.path.parent.mkdir(parents=True, exist_ok=True) | |
| with self.connect() as db: | |
| db.executescript(''' | |
| CREATE TABLE IF NOT EXISTS business_records(owner TEXT,project TEXT,entity_id TEXT,version INTEGER,body TEXT, | |
| PRIMARY KEY(owner,project,entity_id)); | |
| CREATE TABLE IF NOT EXISTS business_actions(owner TEXT,project TEXT,request_key TEXT,request_digest TEXT,result TEXT, | |
| PRIMARY KEY(owner,project,request_key)); | |
| CREATE TABLE IF NOT EXISTS business_audit(id TEXT PRIMARY KEY,at TEXT,owner TEXT,project TEXT,tool TEXT, | |
| input_digest TEXT,result_digest TEXT,outcome TEXT); | |
| ''') | |
| def connect(self): | |
| db = sqlite3.connect(self.path, timeout=10) | |
| db.row_factory = sqlite3.Row | |
| try: | |
| with db: | |
| yield db | |
| finally: | |
| db.close() | |
| def authorize(self, scenario): | |
| actor = self.identity.actor(self.actor_id) | |
| if actor.user_id == 'local-example-builder': | |
| raise SkillError('TOKEN_INVALID', '需要有效用户会话。', 401) | |
| self.identity.project_access(actor, PROJECTS[scenario]) | |
| return PROJECTS[scenario] | |
| def seed(self, db, project): | |
| records = [] | |
| if project == PROJECTS['erp']: | |
| for order, supplier, status, ordered, received, billed, outstanding, completed in ORDERS: | |
| records.append(dict(entity_id=order, order_no=order, supplier='模拟供应商·' + supplier, status=status, | |
| ordered_qty=ordered, received_qty=received, billed_qty=billed, | |
| outstanding_cents=outstanding, completed_at=completed)) | |
| elif project == PROJECTS['wms']: | |
| records = [dict(entity_id='SKU-DEMO-001', sku='SKU-DEMO-001', name='演示轴承', warehouse='DEMO-WH-01', | |
| quantity=20, unit='件')] | |
| else: | |
| records = [dict(entity_id='WO-DEMO-001', work_order='WO-DEMO-001', equipment='DEMO-PUMP-001', | |
| title='演示循环泵巡检', status='OPEN', inspection_interval_days=30, | |
| started_at=None, completed_at=None)] | |
| for record in records: | |
| record.update(source_type='synthetic-business-fixture', knowledge_version=VERSION) | |
| db.execute('INSERT OR IGNORE INTO business_records VALUES(?,?,?,?,?)', | |
| (self.actor_id, project, record['entity_id'], 1, json.dumps(record, ensure_ascii=False))) | |
| def record(self, row): | |
| value = json.loads(row['body']) | |
| value.update(version=row['version'], record_ref=f"knowledge://{row['project']}/{row['entity_id']}/v{row['version']}", | |
| content_digest=digest({'version': row['version'], 'body': value})) | |
| return value | |
| def get(self, db, project, entity): | |
| row = db.execute('SELECT * FROM business_records WHERE owner=? AND project=? AND entity_id=?', | |
| (self.actor_id, project, entity)).fetchone() | |
| if not row: | |
| raise SkillError('BUSINESS_RECORD_NOT_FOUND', '当前演示知识库中没有该业务记录。', 404) | |
| return self.record(row) | |
| def audit(self, db, project, tool, args, result, outcome='success'): | |
| event = 'mcp-' + uuid.uuid4().hex | |
| db.execute('INSERT INTO business_audit VALUES(?,?,?,?,?,?,?,?)', | |
| (event, now(), self.actor_id, project, tool, digest(args), digest(result), outcome)) | |
| return event | |
| def knowledge(self, scenario, question): | |
| if scenario == 'erp': | |
| ranked = sorted(CARDS, key=lambda c: (-sum(t in question for t in c['tags']), c['id'])) | |
| return ranked[:3] | |
| text, steps = ( | |
| ('库存以已登记的出入库流水计算;出库不得导致负库存,同一请求键不能重复扣增库存。', | |
| ['核对物料与仓库。', '确认数量后登记出入库。', '回读库存并检查版本和流水。']) | |
| if scenario == 'wms' else | |
| ('演示设备工单仅允许 OPEN → IN_PROGRESS → CLOSED;开始与完成分别记录时间。', | |
| ['检查工单和设备。', '确认后开始巡检。', '完成检查后关闭工单并回读状态。'])) | |
| card = dict(id='WMS-STOCK' if scenario == 'wms' else 'EQUIPMENT-WORKFLOW', title='本地演示业务规程', | |
| text=text, steps=steps, version=VERSION, url='knowledge://' + PROJECTS[scenario] + '/rules/v1', | |
| source_type='authored-demo-rule', quality_status='demo_rule_not_enterprise_approved', | |
| license='Project-authored demonstration rule', retrieved_on='2026-10-23') | |
| card['content_digest'] = digest(card) | |
| return [card] | |
| def execute(self, tool, args): | |
| guessed = args.get('scenario') if isinstance(args, dict) and tool in ('knowledge_search', 'business_demo_reset') else tool.split('_')[0] | |
| project = PROJECTS.get(guessed, 'unscoped') if isinstance(guessed, str) else 'unscoped' | |
| try: | |
| definition = next((t for t in TOOLS if t['name'] == tool), None) | |
| if definition is None: | |
| raise SkillError('TOOL_NOT_ALLOWED', '工具不在批准目录中。', 403) | |
| validate(args, definition['inputSchema']) | |
| scenario = args['scenario'] if tool in ('knowledge_search', 'business_demo_reset') else tool.split('_')[0] | |
| project = self.authorize(scenario) | |
| except SkillError as exc: | |
| with self.connect() as db: | |
| self.audit(db, project, tool, args, {'code': exc.code}, 'rejected') | |
| raise | |
| try: | |
| with self.connect() as db: | |
| db.execute('BEGIN IMMEDIATE') | |
| self.seed(db, project) | |
| if tool == 'business_demo_reset': | |
| result = self.reset(db, project, args) | |
| elif tool == 'knowledge_search': | |
| result = {'citations': self.knowledge(scenario, args['question']), 'knowledge_version': VERSION} | |
| elif tool == 'erp_orders_list': | |
| rows = [self.record(row) for row in db.execute('SELECT * FROM business_records WHERE owner=? AND project=?', (self.actor_id, project))] | |
| if args['filter'] == 'completed': | |
| rows = [r for r in rows if r['status'] == 'COMPLETED'] | |
| elif args['filter'] == 'unfinished': | |
| rows = [r for r in rows if r['status'] in ('TO_RECEIVE', 'TO_BILL')] | |
| rows.sort(key=lambda r: (r.get('completed_at') or '', r['entity_id']), reverse=True) | |
| result = {'records': rows[:args['limit']], 'knowledge_version': VERSION} | |
| elif definition['annotations']['readOnlyHint']: | |
| entity = args.get('order_no') or args.get('sku') or args['work_order'] | |
| result = {'record': self.get(db, project, entity), 'knowledge_version': VERSION} | |
| else: | |
| result = self.mutate(db, project, tool, args) | |
| result['audit_id'] = self.audit(db, project, tool, args, result) | |
| return result | |
| except SkillError as exc: | |
| with self.connect() as db: | |
| self.audit(db, project, tool, args, {'code': exc.code}, 'rejected') | |
| raise | |
| def reset(self, db, project, args): | |
| fingerprint = digest({'tool': 'business_demo_reset', 'arguments': args}) | |
| prior = db.execute('SELECT * FROM business_actions WHERE owner=? AND project=? AND request_key=?', | |
| (self.actor_id, project, args['request_key'])).fetchone() | |
| if prior: | |
| if prior['request_digest'] != fingerprint: | |
| raise SkillError('IDEMPOTENCY_CONFLICT', '同一请求键已经用于不同操作。', 409) | |
| return dict(json.loads(prior['result']), replayed=True) | |
| before = [self.record(row) for row in db.execute('SELECT * FROM business_records WHERE owner=? AND project=?', | |
| (self.actor_id, project))] | |
| versions = {r['entity_id']: r['version'] for r in before} | |
| db.execute('DELETE FROM business_records WHERE owner=? AND project=?', (self.actor_id, project)) | |
| self.seed(db, project) | |
| for entity, version in versions.items(): | |
| db.execute('UPDATE business_records SET version=? WHERE owner=? AND project=? AND entity_id=?', | |
| (version + 1, self.actor_id, project, entity)) | |
| after = [self.record(row) for row in db.execute('SELECT * FROM business_records WHERE owner=? AND project=?', | |
| (self.actor_id, project))] | |
| result = {'before': before, 'after': after, 'replayed': False, 'request_key': args['request_key'], | |
| 'knowledge_version': VERSION} | |
| db.execute('INSERT INTO business_actions VALUES(?,?,?,?,?)', | |
| (self.actor_id, project, args['request_key'], fingerprint, json.dumps(result, ensure_ascii=False))) | |
| return result | |
| def mutate(self, db, project, tool, args): | |
| fingerprint = digest({'tool': tool, 'arguments': args}) | |
| prior = db.execute('SELECT * FROM business_actions WHERE owner=? AND project=? AND request_key=?', | |
| (self.actor_id, project, args['request_key'])).fetchone() | |
| if prior: | |
| if prior['request_digest'] != fingerprint: | |
| raise SkillError('IDEMPOTENCY_CONFLICT', '同一请求键已经用于不同操作。', 409) | |
| return dict(json.loads(prior['result']), replayed=True) | |
| entity = args.get('order_no') or args.get('sku') or args['work_order'] | |
| before = self.get(db, project, entity) | |
| if before['version'] != args['expected_version']: | |
| raise SkillError('VERSION_CONFLICT', '记录已经变化,请重新查询后确认。', 409) | |
| after = dict(before) | |
| if tool == 'erp_receive_order': | |
| if before['status'] != 'TO_RECEIVE': | |
| raise SkillError('ORDER_STATE_INVALID', '仅待收货订单可以登记收货。', 409) | |
| if args['quantity'] > before['ordered_qty'] - before['received_qty']: | |
| raise SkillError('RECEIPT_EXCEEDS_REMAINING', '收货数量超过剩余未收数量。', 409) | |
| after['received_qty'] += args['quantity'] | |
| if after['received_qty'] == after['ordered_qty']: | |
| after['status'] = 'COMPLETED' if after['billed_qty'] == after['ordered_qty'] else 'TO_BILL' | |
| if after['status'] == 'COMPLETED': | |
| after['completed_at'] = now() | |
| elif tool == 'wms_stock_adjust': | |
| after['quantity'] += args['quantity'] if args['action'] == 'receive' else -args['quantity'] | |
| if after['quantity'] < 0: | |
| raise SkillError('STOCK_INSUFFICIENT', '可用库存不足,未登记出库。', 409) | |
| if after['quantity'] > 1000000: | |
| raise SkillError('STOCK_LIMIT_EXCEEDED', '数量超过演示库存上限。', 409) | |
| else: | |
| expected, target = ('OPEN', 'IN_PROGRESS') if args['action'] == 'start' else ('IN_PROGRESS', 'CLOSED') | |
| if before['status'] != expected: | |
| raise SkillError('WORK_ORDER_TRANSITION_INVALID', '工单不能跳过工序或重复流转。', 409) | |
| after['status'] = target | |
| after['started_at' if target == 'IN_PROGRESS' else 'completed_at'] = now() | |
| for field in ('version', 'record_ref', 'content_digest'): | |
| after.pop(field, None) | |
| db.execute('UPDATE business_records SET version=version+1,body=? WHERE owner=? AND project=? AND entity_id=? AND version=?', | |
| (json.dumps(after, ensure_ascii=False), self.actor_id, project, entity, args['expected_version'])) | |
| result = {'before': before, 'after': self.get(db, project, entity), 'replayed': False, | |
| 'request_key': args['request_key'], 'knowledge_version': VERSION} | |
| db.execute('INSERT INTO business_actions VALUES(?,?,?,?,?)', | |
| (self.actor_id, project, args['request_key'], fingerprint, json.dumps(result, ensure_ascii=False))) | |
| return result | |