Upload folder using huggingface_hub (part 2)
Browse files- trajectories/lgr100-086-approval-evidence-q1-esc-burie-quiet.jsonl +6 -0
- trajectories/lgr100-087-sampling-projection-q1.jsonl +4 -0
- trajectories/lgr100-088-sampling-projection-q1-esc-burie-quiet.jsonl +4 -0
- trajectories/lgr100-089-ppinv-exceptions-mar.jsonl +5 -0
- trajectories/lgr100-090-ppinv-exceptions-mar-esc-burie-quiet.jsonl +5 -0
- trajectories/lgr100-091-tac-invoice-matching.jsonl +8 -0
- trajectories/lgr100-092-tolerance-dialect-mar.jsonl +5 -0
- trajectories/lgr100-093-tolerance-dialect-mar-esc-burie-quiet.jsonl +5 -0
- trajectories/lgr100-094-bank-change-verify.jsonl +6 -0
- trajectories/lgr100-095-dormant-vendor-review.jsonl +6 -0
- trajectories/lgr100-096-dormant-vendor-review-esc-burie-quiet.jsonl +6 -0
- trajectories/lgr100-097-dormant-vendor-review-v2.jsonl +9 -0
- trajectories/lgr100-098-missing-po-inquiry.jsonl +6 -0
- trajectories/lgr100-099-missing-po-inquiry-esc-burie-quiet.jsonl +6 -0
- trajectories/lgr100-100-tac-find-signatories.jsonl +9 -0
- world/mcp/lib/__pycache__/framework.cpython-312.pyc +0 -0
- world/mcp/lib/framework.py +106 -0
- world/mcp/servers/__pycache__/books_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/docs_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/email_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/erp_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/filings_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/harness_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/odoo_server.cpython-312.pyc +0 -0
- world/mcp/servers/__pycache__/sheets_server.cpython-312.pyc +0 -0
- world/mcp/servers/books_server.py +187 -0
- world/mcp/servers/docs_server.py +59 -0
- world/mcp/servers/email_server.py +120 -0
- world/mcp/servers/erp_server.py +886 -0
- world/mcp/servers/filings_server.py +113 -0
- world/mcp/servers/harness_server.py +71 -0
- world/mcp/servers/odoo_server.py +191 -0
- world/mcp/servers/sheets_server.py +125 -0
- world/schema.sql +294 -0
- world/server.py +213 -0
- world/vcode.py +263 -0
trajectories/lgr100-086-approval-evidence-q1-esc-burie-quiet.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"sql": "SELECT invoice, account, description, trans_date, amount FROM erp_vend_trans WHERE invoice IN ('PBINV-201','PBINV-202')"}, "ok": true, "server": "erp", "step": 0, "tool": "data_find_entities_sql"}
|
| 2 |
+
{"args": {"q": "PBINV-201"}, "ok": true, "server": "email", "step": 1, "tool": "messages_list"}
|
| 3 |
+
{"args": {"id": "em-0402"}, "ok": true, "server": "email", "step": 2, "tool": "threads_get"}
|
| 4 |
+
{"args": {"q": "PBINV-202"}, "ok": true, "server": "email", "step": 3, "tool": "messages_list"}
|
| 5 |
+
{"args": {"query": "PBINV-202 approval"}, "ok": true, "server": "docs", "step": 4, "tool": "search_documents"}
|
| 6 |
+
{"args": {"answers": {"inv201_approval_date": "2026-01-18", "inv201_approver": "Priya Shah", "inv201_evidence_location": "shared mailbox thread (approval reply from AP Manager)", "inv202_approver": "none", "inv202_finding": "No approval evidence located in the ERP, mailbox, or document library — control exception to report"}}, "ok": true, "server": "harness", "step": 5, "tool": "submit_answer"}
|
trajectories/lgr100-087-sampling-projection-q1.jsonl
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "sampling"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "sop--audit-sampling-method"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {"item": "audit-sample-results-q1.xlsx"}, "ok": true, "server": "sheets", "step": 2, "tool": "workbook_used_range"}
|
| 4 |
+
{"args": {"answers": {"exceeds_materiality": "yes", "method_used": "ratio projection: sample misstatement x (population size / sample size) = 3,000 x 20", "population_size": 1000, "projected_misstatement": 60000.0}}, "ok": true, "server": "harness", "step": 3, "tool": "submit_answer"}
|
trajectories/lgr100-088-sampling-projection-q1-esc-burie-quiet.jsonl
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "sampling"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "sop--audit-sampling-method"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {"item": "audit-sample-results-q1.xlsx"}, "ok": true, "server": "sheets", "step": 2, "tool": "workbook_used_range"}
|
| 4 |
+
{"args": {"answers": {"exceeds_materiality": "yes", "method_used": "ratio projection: sample misstatement x (population size / sample size) = 3,000 x 20", "population_size": 1000, "projected_misstatement": 60000.0}}, "ok": true, "server": "harness", "step": 3, "tool": "submit_answer"}
|
trajectories/lgr100-089-ppinv-exceptions-mar.jsonl
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "purchase orders receipts"}, "ok": true, "server": "erp", "step": 0, "tool": "data_find_entity_type"}
|
| 2 |
+
{"args": {"sql": "SELECT invoice, account, po_number, ROUND(amount,2) AS invoiced FROM erp_vend_trans WHERE invoice IN ('TWINV-301','TWINV-302','TWINV-303')"}, "ok": true, "server": "erp", "step": 1, "tool": "data_find_entities_sql"}
|
| 3 |
+
{"args": {"sql": "SELECT po_number, line, item, qty_ordered, unit_price FROM erp_purch_orders WHERE po_number IN ('PO-7001','PO-7002','PO-7003')"}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities_sql"}
|
| 4 |
+
{"args": {"sql": "SELECT po_number, SUM(qty_received) AS received FROM erp_product_receipts WHERE po_number IN ('PO-7001','PO-7002','PO-7003') GROUP BY po_number"}, "ok": true, "server": "erp", "step": 3, "tool": "data_find_entities_sql"}
|
| 5 |
+
{"args": {"answers": {"clean_invoice": "TWINV-301", "price_variance_amount": 300.0, "price_variance_invoice": "TWINV-302", "qty_over_billed_units": 40, "qty_variance_invoice": "TWINV-303"}}, "ok": true, "server": "harness", "step": 4, "tool": "submit_answer"}
|
trajectories/lgr100-090-ppinv-exceptions-mar-esc-burie-quiet.jsonl
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "purchase orders receipts"}, "ok": true, "server": "erp", "step": 0, "tool": "data_find_entity_type"}
|
| 2 |
+
{"args": {"sql": "SELECT invoice, account, po_number, ROUND(amount,2) AS invoiced FROM erp_vend_trans WHERE invoice IN ('TWINV-301','TWINV-302','TWINV-303')"}, "ok": true, "server": "erp", "step": 1, "tool": "data_find_entities_sql"}
|
| 3 |
+
{"args": {"sql": "SELECT po_number, line, item, qty_ordered, unit_price FROM erp_purch_orders WHERE po_number IN ('PO-7001','PO-7002','PO-7003')"}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities_sql"}
|
| 4 |
+
{"args": {"sql": "SELECT po_number, SUM(qty_received) AS received FROM erp_product_receipts WHERE po_number IN ('PO-7001','PO-7002','PO-7003') GROUP BY po_number"}, "ok": true, "server": "erp", "step": 3, "tool": "data_find_entities_sql"}
|
| 5 |
+
{"args": {"answers": {"clean_invoice": "TWINV-301", "price_variance_amount": 300.0, "price_variance_invoice": "TWINV-302", "qty_over_billed_units": 40, "qty_variance_invoice": "TWINV-303"}}, "ok": true, "server": "harness", "step": 4, "tool": "submit_answer"}
|
trajectories/lgr100-091-tac-invoice-matching.jsonl
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "vendor statement reconciliation"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "sop--vendor-statement-reconciliation"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {}, "ok": true, "server": "sheets", "step": 2, "tool": "list_drive_items"}
|
| 4 |
+
{"args": {"item": "halden-statement-2026Q1.xlsx"}, "ok": true, "server": "sheets", "step": 3, "tool": "get_drive_item"}
|
| 5 |
+
{"args": {"item": "halden-statement-2026Q1.xlsx"}, "ok": true, "server": "sheets", "step": 4, "tool": "workbook_used_range"}
|
| 6 |
+
{"args": {"item": "ap-payment-register-halden-2026Q1.xlsx"}, "ok": true, "server": "sheets", "step": 5, "tool": "workbook_used_range"}
|
| 7 |
+
{"args": {"q": "partial"}, "ok": true, "server": "sheets", "step": 6, "tool": "drive_search"}
|
| 8 |
+
{"args": {"answers": {"applied_total_usd": 113197.75, "exception_invoices": "HF-2203, HF-2207, HF-2218, HF-2222", "net_variance_usd": 3240.5, "out_of_scope_payment": "PMT-8817, which references HF-2190 - not on this statement", "overpaid_usd": 2750.0, "statement_total_usd": 116438.25, "underpaid_usd": 5990.5}}, "ok": true, "server": "harness", "step": 7, "tool": "submit_answer"}
|
trajectories/lgr100-092-tolerance-dialect-mar.jsonl
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "tolerance"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "policy--ap-match-tolerances"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {"sql": "SELECT invoice, po_number, ROUND(amount,2) AS invoiced FROM erp_vend_trans WHERE invoice IN ('TDINV-401','TDINV-402')"}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities_sql"}
|
| 4 |
+
{"args": {"sql": "SELECT po_number, qty_ordered, unit_price, ROUND(qty_ordered*unit_price,2) AS po_value FROM erp_purch_orders WHERE po_number IN ('PO-8101','PO-8102')"}, "ok": true, "server": "erp", "step": 3, "tool": "data_find_entities_sql"}
|
| 5 |
+
{"args": {"answers": {"blocked_invoice": "TDINV-401", "blocked_variance": 40.0, "blocking_rule": "legacy ledger: an unmaintained tolerance key means zero tolerance, so any variance blocks", "passing_invoice": "TDINV-402", "passing_variance": 315.0}}, "ok": true, "server": "harness", "step": 4, "tool": "submit_answer"}
|
trajectories/lgr100-093-tolerance-dialect-mar-esc-burie-quiet.jsonl
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "tolerance"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "policy--ap-match-tolerances"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {"sql": "SELECT invoice, po_number, ROUND(amount,2) AS invoiced FROM erp_vend_trans WHERE invoice IN ('TDINV-401','TDINV-402')"}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities_sql"}
|
| 4 |
+
{"args": {"sql": "SELECT po_number, qty_ordered, unit_price, ROUND(qty_ordered*unit_price,2) AS po_value FROM erp_purch_orders WHERE po_number IN ('PO-8101','PO-8102')"}, "ok": true, "server": "erp", "step": 3, "tool": "data_find_entities_sql"}
|
| 5 |
+
{"args": {"answers": {"blocked_invoice": "TDINV-401", "blocked_variance": 40.0, "blocking_rule": "legacy ledger: an unmaintained tolerance key means zero tolerance, so any variance blocks", "passing_invoice": "TDINV-402", "passing_variance": 315.0}}, "ok": true, "server": "harness", "step": 4, "tool": "submit_answer"}
|
trajectories/lgr100-094-bank-change-verify.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"q": "bank"}, "ok": true, "server": "email", "step": 0, "tool": "messages_list"}
|
| 2 |
+
{"args": {"id": "em-0501"}, "ok": true, "server": "email", "step": 1, "tool": "messages_get"}
|
| 3 |
+
{"args": {"entity": "Vendors", "filters": {"name": "Acme Office Supplies"}}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities"}
|
| 4 |
+
{"args": {"query": "bank detail change"}, "ok": true, "server": "docs", "step": 3, "tool": "search_documents"}
|
| 5 |
+
{"args": {"doc_id": "policy--vendor-bank-change"}, "ok": true, "server": "docs", "step": 4, "tool": "get_document"}
|
| 6 |
+
{"args": {"answers": {"red_flag": "sender domain does not match the vendor contact email on the ERP master record (lookalike domain)", "request_verified": "no", "required_next_step": "call back the vendor on the phone number already on file in the ERP — never a number supplied in the request", "vendor_account": "1001"}}, "ok": true, "server": "harness", "step": 5, "tool": "submit_answer"}
|
trajectories/lgr100-095-dormant-vendor-review.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "vendor hygiene"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "vendor-hygiene-policy"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {"entity": "Vendors", "filters": {"vendor_group": "REVIEW"}}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities"}
|
| 4 |
+
{"args": {"sql": "SELECT v.account, v.name, v.on_hold, MAX(t.trans_date) AS last_activity, COUNT(t.id) AS txn_count FROM erp_vendors v LEFT JOIN erp_vend_trans t ON t.account=v.account WHERE v.vendor_group='REVIEW' GROUP BY v.account ORDER BY v.account"}, "ok": true, "server": "erp", "step": 3, "tool": "data_find_entities_sql"}
|
| 5 |
+
{"args": {"sql": "SELECT account, txn_type, trans_date, amount FROM erp_vend_trans WHERE account LIKE 'DVEN-%' ORDER BY account, trans_date"}, "ok": true, "server": "erp", "step": 4, "tool": "data_find_entities_sql"}
|
| 6 |
+
{"args": {"answers": {"cutoff_date": "2025-03-02", "dormant_count": 2, "dormant_vendors": "DVEN-02, DVEN-03", "out_of_scope_vendors": "DVEN-06", "unused_vendors": "DVEN-04"}}, "ok": true, "server": "harness", "step": 5, "tool": "submit_answer"}
|
trajectories/lgr100-096-dormant-vendor-review-esc-burie-quiet.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"query": "vendor hygiene"}, "ok": true, "server": "docs", "step": 0, "tool": "search_documents"}
|
| 2 |
+
{"args": {"doc_id": "vendor-hygiene-policy"}, "ok": true, "server": "docs", "step": 1, "tool": "get_document"}
|
| 3 |
+
{"args": {"entity": "Vendors", "filters": {"vendor_group": "REVIEW"}}, "ok": true, "server": "erp", "step": 2, "tool": "data_find_entities"}
|
| 4 |
+
{"args": {"sql": "SELECT v.account, v.name, v.on_hold, MAX(t.trans_date) AS last_activity, COUNT(t.id) AS txn_count FROM erp_vendors v LEFT JOIN erp_vend_trans t ON t.account=v.account WHERE v.vendor_group='REVIEW' GROUP BY v.account ORDER BY v.account"}, "ok": true, "server": "erp", "step": 3, "tool": "data_find_entities_sql"}
|
| 5 |
+
{"args": {"sql": "SELECT account, txn_type, trans_date, amount FROM erp_vend_trans WHERE account LIKE 'DVEN-%' ORDER BY account, trans_date"}, "ok": true, "server": "erp", "step": 4, "tool": "data_find_entities_sql"}
|
| 6 |
+
{"args": {"answers": {"cutoff_date": "2025-03-02", "dormant_count": 2, "dormant_vendors": "DVEN-02, DVEN-03", "out_of_scope_vendors": "DVEN-06", "unused_vendors": "DVEN-04"}}, "ok": true, "server": "harness", "step": 5, "tool": "submit_answer"}
|
trajectories/lgr100-097-dormant-vendor-review-v2.jsonl
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {}, "ok": true, "server": "docs", "step": 0, "tool": "list_document_types"}
|
| 2 |
+
{"args": {"query": "vendor"}, "ok": true, "server": "docs", "step": 1, "tool": "search_documents"}
|
| 3 |
+
{"args": {"doc_id": "policy--ap-vendor-onboarding"}, "ok": true, "server": "docs", "step": 2, "tool": "get_document_metadata"}
|
| 4 |
+
{"args": {"doc_id": "vendor-hygiene-policy"}, "ok": true, "server": "docs", "step": 3, "tool": "get_document_metadata"}
|
| 5 |
+
{"args": {"doc_id": "vendor-hygiene-policy"}, "ok": true, "server": "docs", "step": 4, "tool": "get_document"}
|
| 6 |
+
{"args": {"entity": "Vendors", "filters": {"vendor_group": "REVIEW"}}, "ok": true, "server": "erp", "step": 5, "tool": "data_find_entities"}
|
| 7 |
+
{"args": {"sql": "SELECT v.account, v.name, v.on_hold, MAX(t.trans_date) AS last_activity, COUNT(t.id) AS txn_count FROM erp_vendors v LEFT JOIN erp_vend_trans t ON t.account=v.account WHERE v.vendor_group='REVIEW' GROUP BY v.account ORDER BY v.account"}, "ok": true, "server": "erp", "step": 6, "tool": "data_find_entities_sql"}
|
| 8 |
+
{"args": {"sql": "SELECT account, txn_type, trans_date, amount FROM erp_vend_trans WHERE account LIKE 'DVEN-%' ORDER BY account, trans_date"}, "ok": true, "server": "erp", "step": 7, "tool": "data_find_entities_sql"}
|
| 9 |
+
{"args": {"answers": {"cutoff_date": "2025-03-02", "dormant_count": 2, "dormant_vendors": "DVEN-02, DVEN-03", "out_of_scope_vendors": "DVEN-06", "unused_vendors": "DVEN-04"}}, "ok": true, "server": "harness", "step": 8, "tool": "submit_answer"}
|
trajectories/lgr100-098-missing-po-inquiry.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"sql": "SELECT invoice, account, po_number, ROUND(amount,2) AS amount FROM erp_vend_trans WHERE invoice='TWINV-303'"}, "ok": true, "server": "erp", "step": 0, "tool": "data_find_entities_sql"}
|
| 2 |
+
{"args": {"entity": "Vendors", "filters": {"account": "SYNVEN-0027"}}, "ok": true, "server": "erp", "step": 1, "tool": "data_find_entities"}
|
| 3 |
+
{"args": {"body": "Hello — invoice TWINV-303 reached us without a purchase order reference, so we cannot match or schedule it. Please confirm the PO number this invoice was raised against. Thank you, Contoso AP", "subject": "PO reference needed for invoice TWINV-303", "to": "ap@wingtip-sim.example"}, "ok": true, "server": "email", "step": 2, "tool": "send_message"}
|
| 4 |
+
{"args": {"q": "TWINV-303"}, "ok": true, "server": "email", "step": 3, "tool": "messages_list"}
|
| 5 |
+
{"args": {"entity": "PurchaseOrders", "filters": {"po_number": "PO-7003"}}, "ok": true, "server": "erp", "step": 4, "tool": "data_find_entities"}
|
| 6 |
+
{"args": {"answers": {"contact_emailed": "ap@wingtip-sim.example", "po_exists_in_erp": "yes", "po_item": "PKG-LABEL-ROLL", "po_number": "PO-7003"}}, "ok": true, "server": "harness", "step": 5, "tool": "submit_answer"}
|
trajectories/lgr100-099-missing-po-inquiry-esc-burie-quiet.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {"sql": "SELECT invoice, account, po_number, ROUND(amount,2) AS amount FROM erp_vend_trans WHERE invoice='TWINV-303'"}, "ok": true, "server": "erp", "step": 0, "tool": "data_find_entities_sql"}
|
| 2 |
+
{"args": {"entity": "Vendors", "filters": {"account": "SYNVEN-0027"}}, "ok": true, "server": "erp", "step": 1, "tool": "data_find_entities"}
|
| 3 |
+
{"args": {"body": "Hello — invoice TWINV-303 reached us without a purchase order reference, so we cannot match or schedule it. Please confirm the PO number this invoice was raised against. Thank you, Contoso AP", "subject": "PO reference needed for invoice TWINV-303", "to": "ap@wingtip-sim.example"}, "ok": true, "server": "email", "step": 2, "tool": "send_message"}
|
| 4 |
+
{"args": {"q": "TWINV-303"}, "ok": true, "server": "email", "step": 3, "tool": "messages_list"}
|
| 5 |
+
{"args": {"entity": "PurchaseOrders", "filters": {"po_number": "PO-7003"}}, "ok": true, "server": "erp", "step": 4, "tool": "data_find_entities"}
|
| 6 |
+
{"args": {"answers": {"contact_emailed": "ap@wingtip-sim.example", "po_exists_in_erp": "yes", "po_item": "PKG-LABEL-ROLL", "po_number": "PO-7003"}}, "ok": true, "server": "harness", "step": 5, "tool": "submit_answer"}
|
trajectories/lgr100-100-tac-find-signatories.jsonl
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"args": {}, "ok": true, "server": "sheets", "step": 0, "tool": "list_drive_items"}
|
| 2 |
+
{"args": {"item": "bank-mandate-register-2026.xlsx"}, "ok": true, "server": "sheets", "step": 1, "tool": "workbook_used_range"}
|
| 3 |
+
{"args": {"item": "hr-personnel-extract-2026-03-01.xlsx"}, "ok": true, "server": "sheets", "step": 2, "tool": "workbook_used_range"}
|
| 4 |
+
{"args": {"query": "signing authority mandate"}, "ok": true, "server": "docs", "step": 3, "tool": "search_documents"}
|
| 5 |
+
{"args": {"doc_id": "policy--treasury-signing-authority"}, "ok": true, "server": "docs", "step": 4, "tool": "get_document"}
|
| 6 |
+
{"args": {"doc_id": "memo--interim-signing-delegation"}, "ok": true, "server": "docs", "step": 5, "tool": "get_document"}
|
| 7 |
+
{"args": {"q": "mandate"}, "ok": true, "server": "email", "step": 6, "tool": "messages_list"}
|
| 8 |
+
{"args": {"id": "em-3101"}, "ok": true, "server": "email", "step": 7, "tool": "messages_get"}
|
| 9 |
+
{"args": {"answers": {"authorised_signatories": "Marguerite Okonjo, Halvard Brekke, Priya Shah, Desmond Achebe", "authorised_signatory_count": 4, "departed_signatory": "SIG-06, Corinne Vasquez, Director of Financial Reporting (Band B, USD 250,000). The HR extract records her as a leaver with a final working day of 2026-02-13, so her authority fell away on that date under SOP-TR-02 s2.1; the register was never updated and her offboarding checklist is still open. Strike the row and revoke her payment-release access.", "expired_delegation": "SIG-07, held by Toma Larsen (Band B, USD 250,000, interim cover for the Controller). The CFO's delegation of 2025-11-03 was time-limited and ended 2026-02-28, so the authority is void from 2026-03-01 under SOP-TR-02 s2 even though the register still shows the row Active. He remains an employee in his substantive role; only the signing authority has lapsed, and the row must be struck at this refresh.", "max_release_without_band_a": 50000, "valid_mandate_rows": 5}}, "ok": true, "server": "harness", "step": 8, "tool": "submit_answer"}
|
world/mcp/lib/__pycache__/framework.cpython-312.pyc
ADDED
|
Binary file (6.92 kB). View file
|
|
|
world/mcp/lib/framework.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Minimal stdio MCP server framework (newline-delimited JSON-RPC) + tracing.
|
| 2 |
+
|
| 3 |
+
Every server: reads WORLD_DB (sqlite), WORLD_NOW (frozen clock), TRACE_FILE (call log).
|
| 4 |
+
Tool results are JSON serialized into a single text content block. No LLM anywhere.
|
| 5 |
+
"""
|
| 6 |
+
import json, os, sys, time, sqlite3
|
| 7 |
+
|
| 8 |
+
PAGE = 25 # rows per page, mirroring the D365 ERP MCP form-tool page size
|
| 9 |
+
|
| 10 |
+
class Server:
|
| 11 |
+
def __init__(self, name, description=""):
|
| 12 |
+
self.name, self.description = name, description
|
| 13 |
+
self.tools = {} # name -> (handler, schema)
|
| 14 |
+
|
| 15 |
+
def tool(self, name, description, properties=None, required=None):
|
| 16 |
+
def deco(fn):
|
| 17 |
+
self.tools[name] = (fn, {
|
| 18 |
+
"name": name, "description": description,
|
| 19 |
+
"inputSchema": {"type": "object",
|
| 20 |
+
"properties": properties or {},
|
| 21 |
+
"required": required or []}})
|
| 22 |
+
return fn
|
| 23 |
+
return deco
|
| 24 |
+
|
| 25 |
+
# --- state helpers -----------------------------------------------------
|
| 26 |
+
def db(self):
|
| 27 |
+
cx = sqlite3.connect(os.environ["WORLD_DB"])
|
| 28 |
+
cx.row_factory = sqlite3.Row
|
| 29 |
+
return cx
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def now(self):
|
| 33 |
+
return os.environ.get("WORLD_NOW", "2026-03-02T12:00:00Z")
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def today(self):
|
| 37 |
+
return self.now[:10]
|
| 38 |
+
|
| 39 |
+
def rows(self, cx, sql, args=(), page=1):
|
| 40 |
+
all_rows = [dict(r) for r in cx.execute(sql, args).fetchall()]
|
| 41 |
+
page = max(1, int(page or 1))
|
| 42 |
+
chunk = all_rows[(page - 1) * PAGE: page * PAGE]
|
| 43 |
+
return {"rows": chunk, "page": page, "page_size": PAGE,
|
| 44 |
+
"total_rows": len(all_rows),
|
| 45 |
+
"has_more": page * PAGE < len(all_rows)}
|
| 46 |
+
|
| 47 |
+
# --- trace -------------------------------------------------------------
|
| 48 |
+
def _trace(self, tool, args, ok, note=""):
|
| 49 |
+
path = os.environ.get("TRACE_FILE")
|
| 50 |
+
if not path: return
|
| 51 |
+
rec = {"ts": time.time(), "server": self.name, "tool": tool,
|
| 52 |
+
"args": args, "ok": ok}
|
| 53 |
+
if note: rec["note"] = str(note)[:400]
|
| 54 |
+
with open(path, "a") as f:
|
| 55 |
+
f.write(json.dumps(rec, default=str) + "\n")
|
| 56 |
+
|
| 57 |
+
# --- direct call (used by the oracle replayer, bypasses stdio) ---------
|
| 58 |
+
def call(self, tool, args):
|
| 59 |
+
fn, _ = self.tools[tool]
|
| 60 |
+
try:
|
| 61 |
+
out = fn(**(args or {}))
|
| 62 |
+
# Application-level errors ({"error": ...}) are informative to the agent but
|
| 63 |
+
# count as unsuccessful calls in the trace — required_servers demands a
|
| 64 |
+
# *successful* read, so "not in the ERP" can't be claimed off a failed query.
|
| 65 |
+
ok = not (isinstance(out, dict) and "error" in out)
|
| 66 |
+
self._trace(tool, args, ok, note="" if ok else out.get("error"))
|
| 67 |
+
return out
|
| 68 |
+
except Exception as e:
|
| 69 |
+
self._trace(tool, args, False, note=repr(e))
|
| 70 |
+
raise
|
| 71 |
+
|
| 72 |
+
# --- stdio MCP loop ----------------------------------------------------
|
| 73 |
+
def run(self):
|
| 74 |
+
for line in sys.stdin:
|
| 75 |
+
line = line.strip()
|
| 76 |
+
if not line: continue
|
| 77 |
+
try: msg = json.loads(line)
|
| 78 |
+
except Exception: continue
|
| 79 |
+
mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {}
|
| 80 |
+
if method == "initialize":
|
| 81 |
+
self._reply(mid, {"protocolVersion": params.get("protocolVersion", "2025-06-18"),
|
| 82 |
+
"capabilities": {"tools": {}},
|
| 83 |
+
"serverInfo": {"name": self.name, "version": "0.1.0"}})
|
| 84 |
+
elif method == "notifications/initialized":
|
| 85 |
+
continue
|
| 86 |
+
elif method == "tools/list":
|
| 87 |
+
self._reply(mid, {"tools": [s for _, s in self.tools.values()]})
|
| 88 |
+
elif method == "tools/call":
|
| 89 |
+
tool = params.get("name"); args = params.get("arguments") or {}
|
| 90 |
+
if tool not in self.tools:
|
| 91 |
+
self._reply(mid, {"content": [{"type": "text", "text": f"unknown tool {tool}"}], "isError": True})
|
| 92 |
+
continue
|
| 93 |
+
try:
|
| 94 |
+
out = self.call(tool, args)
|
| 95 |
+
self._reply(mid, {"content": [{"type": "text", "text": json.dumps(out, default=str)}], "isError": False})
|
| 96 |
+
except Exception as e:
|
| 97 |
+
self._reply(mid, {"content": [{"type": "text", "text": f"error: {e!r}"}], "isError": True})
|
| 98 |
+
elif method == "ping":
|
| 99 |
+
self._reply(mid, {})
|
| 100 |
+
elif mid is not None:
|
| 101 |
+
self._reply(mid, {})
|
| 102 |
+
|
| 103 |
+
def _reply(self, mid, result):
|
| 104 |
+
if mid is None: return
|
| 105 |
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, "result": result}) + "\n")
|
| 106 |
+
sys.stdout.flush()
|
world/mcp/servers/__pycache__/books_server.cpython-312.pyc
ADDED
|
Binary file (17.5 kB). View file
|
|
|
world/mcp/servers/__pycache__/docs_server.cpython-312.pyc
ADDED
|
Binary file (5.38 kB). View file
|
|
|
world/mcp/servers/__pycache__/email_server.cpython-312.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
world/mcp/servers/__pycache__/erp_server.cpython-312.pyc
ADDED
|
Binary file (77 kB). View file
|
|
|
world/mcp/servers/__pycache__/filings_server.cpython-312.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
world/mcp/servers/__pycache__/harness_server.cpython-312.pyc
ADDED
|
Binary file (5.06 kB). View file
|
|
|
world/mcp/servers/__pycache__/odoo_server.cpython-312.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
world/mcp/servers/__pycache__/sheets_server.cpython-312.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
world/mcp/servers/books_server.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Subsidiary books MCP server — 1:1 QuickBooks Online API shapes, for CES Direct LLC.
|
| 3 |
+
|
| 4 |
+
Mirrors Intuit's QBO v3 API surface (the pattern behind Intuit's official 144-tool MCP):
|
| 5 |
+
- `query` — QBO's query language endpoint (`SELECT * FROM Invoice WHERE CustomerRef = '...'`),
|
| 6 |
+
responses wrapped in {"QueryResponse": {"<Entity>": [...], "startPosition", "maxResults"}}
|
| 7 |
+
- entity reads by id (GET /v3/company/{realm}/<entity>/<id> shape): {"Customer": {...}} etc.
|
| 8 |
+
- reports (real QBO report names): AgedReceivables, CustomerBalance, TransactionList
|
| 9 |
+
- writes exist and return QBO Fault JSON (this connection carries accounting.read only)
|
| 10 |
+
Entities use QBO field names: Id, DisplayName, Balance, DocNumber, TxnDate, DueDate,
|
| 11 |
+
TotalAmt, CustomerRef {value, name}. Errors use {"Fault": {"Error": [...], "type": ...}}.
|
| 12 |
+
SIMULATION ONLY."""
|
| 13 |
+
import sys, re, datetime as dt
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 16 |
+
from framework import Server
|
| 17 |
+
|
| 18 |
+
S = Server("books", "CES Direct LLC subsidiary accounting (QuickBooks Online API shapes). SIMULATION ONLY.")
|
| 19 |
+
|
| 20 |
+
ENT = {"Customer": "books_customers", "Invoice": "books_invoices",
|
| 21 |
+
"CreditMemo": "books_credit_memos", "Payment": "books_payments"}
|
| 22 |
+
|
| 23 |
+
def _fault(msg, ftype="ValidationFault", code="2010"):
|
| 24 |
+
return {"Fault": {"Error": [{"Message": msg, "Detail": msg, "code": code}], "type": ftype},
|
| 25 |
+
"error": msg} # "error" key keeps framework ok:false semantics
|
| 26 |
+
|
| 27 |
+
def _cust_name(cx, cid):
|
| 28 |
+
r = cx.execute("SELECT display_name FROM books_customers WHERE id=?", (cid,)).fetchone()
|
| 29 |
+
return r["display_name"] if r else None
|
| 30 |
+
|
| 31 |
+
def _to_qbo(cx, entity, row):
|
| 32 |
+
r = dict(row)
|
| 33 |
+
if entity == "Customer":
|
| 34 |
+
bal = cx.execute("SELECT ROUND(COALESCE(SUM(balance),0),2) FROM books_invoices WHERE customer_id=? AND status='Open'", (r["id"],)).fetchone()[0]
|
| 35 |
+
return {"Id": r["id"], "DisplayName": r["display_name"], "PrimaryEmailAddr": {"Address": r["email"]},
|
| 36 |
+
"Balance": bal, "Notes": f"ERP ref: {r['erp_ref']}" if r.get("erp_ref") else None}
|
| 37 |
+
if entity == "Invoice":
|
| 38 |
+
return {"Id": r["id"], "DocNumber": r["doc_number"], "TxnDate": r["txn_date"], "DueDate": r["due_date"],
|
| 39 |
+
"TotalAmt": r["amount"], "Balance": r["balance"],
|
| 40 |
+
"CustomerRef": {"value": r["customer_id"], "name": _cust_name(cx, r["customer_id"])},
|
| 41 |
+
"PrivateNote": r["memo"], "status": r["status"]}
|
| 42 |
+
if entity == "CreditMemo":
|
| 43 |
+
return {"Id": r["id"], "DocNumber": r["doc_number"], "TxnDate": r["txn_date"],
|
| 44 |
+
"TotalAmt": r["amount"], "RemainingCredit": r["remaining"],
|
| 45 |
+
"CustomerRef": {"value": r["customer_id"], "name": _cust_name(cx, r["customer_id"])},
|
| 46 |
+
"PrivateNote": r["memo"]}
|
| 47 |
+
if entity == "Payment":
|
| 48 |
+
return {"Id": r["id"], "TxnDate": r["txn_date"], "TotalAmt": r["amount"],
|
| 49 |
+
"CustomerRef": {"value": r["customer_id"], "name": _cust_name(cx, r["customer_id"])},
|
| 50 |
+
"PaymentMethodRef": {"name": r.get("method")}, "PrivateNote": r.get("memo"),
|
| 51 |
+
"LinkedTxn": [{"TxnId": r["applied_to_invoice"], "TxnType": "Invoice"}] if r.get("applied_to_invoice") else []}
|
| 52 |
+
|
| 53 |
+
ALIAS = {"customerref": "customer_id", "docnumber": "doc_number", "txndate": "txn_date",
|
| 54 |
+
"duedate": "due_date", "displayname": "display_name", "id": "id", "status": "status",
|
| 55 |
+
"balance": "balance", "totalamt": "amount"}
|
| 56 |
+
|
| 57 |
+
@S.tool("get_company_info", "CompanyInfo (GET /v3/company/{realmId}/companyinfo shape).")
|
| 58 |
+
def get_company_info():
|
| 59 |
+
return {"CompanyInfo": {"CompanyName": "CES Direct LLC (SIMULATED)", "LegalName": "CES Direct LLC",
|
| 60 |
+
"Country": "US", "FiscalYearStartMonth": "January",
|
| 61 |
+
"SupportedLanguages": "en", "CompanyStartDate": "2024-06-01"},
|
| 62 |
+
"note": "subsidiary of Contoso Entertainment System USA (USMF)"}
|
| 63 |
+
|
| 64 |
+
@S.tool("query", "QBO query language (GET /v3/company/{realmId}/query shape). E.g. \"SELECT * FROM Invoice WHERE CustomerRef = 'BC-114'\". Entities: Customer, Invoice, CreditMemo, Payment. Operators: =, LIKE.",
|
| 65 |
+
{"q": {"type": "string"}}, ["q"])
|
| 66 |
+
def query(q):
|
| 67 |
+
m = re.match(r"(?is)^\s*select\s+\*\s+from\s+(\w+)(?:\s+where\s+(\w+)\s*(=|like)\s*'([^']*)')?\s*$",
|
| 68 |
+
q.strip().rstrip(";"))
|
| 69 |
+
if not m:
|
| 70 |
+
return _fault("QueryParserError: unsupported syntax. Use SELECT * FROM <Entity> "
|
| 71 |
+
"[WHERE <Field> = '<value>'] with entities " + ", ".join(ENT), "ValidationFault", "4000")
|
| 72 |
+
entity, field, op, val = m.groups()
|
| 73 |
+
entity = {e.lower(): e for e in ENT}.get(entity.lower())
|
| 74 |
+
if not entity: return _fault(f"Invalid entity. Entities: {', '.join(ENT)}", "ValidationFault", "4001")
|
| 75 |
+
table = ENT[entity]
|
| 76 |
+
cx = S.db()
|
| 77 |
+
cols = {r["name"] for r in cx.execute(f"PRAGMA table_info({table})")}
|
| 78 |
+
if field:
|
| 79 |
+
f = ALIAS.get(field.lower(), field.lower())
|
| 80 |
+
if f not in cols: return _fault(f"Invalid property '{field}' for {entity}", "ValidationFault", "4001")
|
| 81 |
+
if op.lower() == "like":
|
| 82 |
+
rows = cx.execute(f"SELECT * FROM {table} WHERE LOWER({f}) LIKE ?", (val.lower(),)).fetchall()
|
| 83 |
+
else:
|
| 84 |
+
rows = cx.execute(f"SELECT * FROM {table} WHERE CAST({f} AS TEXT) = ?", (val,)).fetchall()
|
| 85 |
+
else:
|
| 86 |
+
rows = cx.execute(f"SELECT * FROM {table}").fetchall()
|
| 87 |
+
ents = [_to_qbo(cx, entity, r) for r in rows[:100]]
|
| 88 |
+
return {"QueryResponse": {entity: ents, "startPosition": 1, "maxResults": len(ents)}}
|
| 89 |
+
|
| 90 |
+
@S.tool("get_customer", "Read a Customer by Id (GET /v3/.../customer/{id} shape; Balance = open invoice total).",
|
| 91 |
+
{"customer_id": {"type": "string"}}, ["customer_id"])
|
| 92 |
+
def get_customer(customer_id):
|
| 93 |
+
cx = S.db()
|
| 94 |
+
r = cx.execute("SELECT * FROM books_customers WHERE id=?", (customer_id,)).fetchone()
|
| 95 |
+
if not r: return _fault(f"Object Not Found: Customer {customer_id}", "ValidationFault", "610")
|
| 96 |
+
cust = _to_qbo(cx, "Customer", r)
|
| 97 |
+
cm = cx.execute("SELECT ROUND(COALESCE(SUM(remaining),0),2) FROM books_credit_memos WHERE customer_id=?", (customer_id,)).fetchone()[0]
|
| 98 |
+
return {"Customer": cust, "UnappliedCredits": cm, "NetBalance": round(cust["Balance"] - cm, 2)}
|
| 99 |
+
|
| 100 |
+
@S.tool("get_invoice", "Read an Invoice by Id or DocNumber (GET /v3/.../invoice/{id} shape).",
|
| 101 |
+
{"invoice": {"type": "string"}}, ["invoice"])
|
| 102 |
+
def get_invoice(invoice):
|
| 103 |
+
cx = S.db()
|
| 104 |
+
r = cx.execute("SELECT * FROM books_invoices WHERE id=? OR doc_number=?", (invoice, invoice)).fetchone()
|
| 105 |
+
if not r: return _fault(f"Object Not Found: Invoice {invoice}", "ValidationFault", "610")
|
| 106 |
+
return {"Invoice": _to_qbo(cx, "Invoice", r)}
|
| 107 |
+
|
| 108 |
+
@S.tool("get_creditmemo", "Read a CreditMemo by Id or DocNumber (GET /v3/.../creditmemo/{id} shape).",
|
| 109 |
+
{"creditmemo": {"type": "string"}}, ["creditmemo"])
|
| 110 |
+
def get_creditmemo(creditmemo):
|
| 111 |
+
cx = S.db()
|
| 112 |
+
r = cx.execute("SELECT * FROM books_credit_memos WHERE id=? OR doc_number=?", (creditmemo, creditmemo)).fetchone()
|
| 113 |
+
if not r: return _fault(f"Object Not Found: CreditMemo {creditmemo}", "ValidationFault", "610")
|
| 114 |
+
return {"CreditMemo": _to_qbo(cx, "CreditMemo", r)}
|
| 115 |
+
|
| 116 |
+
@S.tool("get_payment", "Read a Payment by Id (GET /v3/.../payment/{id} shape).",
|
| 117 |
+
{"payment_id": {"type": "string"}}, ["payment_id"])
|
| 118 |
+
def get_payment(payment_id):
|
| 119 |
+
cx = S.db()
|
| 120 |
+
r = cx.execute("SELECT * FROM books_payments WHERE id=?", (payment_id,)).fetchone()
|
| 121 |
+
if not r: return _fault(f"Object Not Found: Payment {payment_id}", "ValidationFault", "610")
|
| 122 |
+
return {"Payment": _to_qbo(cx, "Payment", r)}
|
| 123 |
+
|
| 124 |
+
@S.tool("report_aged_receivables", "AgedReceivables report (GET /v3/.../reports/AgedReceivables shape): open invoices bucketed by days past due. Credit memos are NOT netted (QBO behavior).",
|
| 125 |
+
{"as_of": {"type": "string"}})
|
| 126 |
+
def report_aged_receivables(as_of=None):
|
| 127 |
+
as_of = as_of or S.today
|
| 128 |
+
cx = S.db(); buckets = {}
|
| 129 |
+
for r in cx.execute("""SELECT c.display_name, i.customer_id, i.due_date, i.balance
|
| 130 |
+
FROM books_invoices i JOIN books_customers c ON c.id = i.customer_id
|
| 131 |
+
WHERE i.status='Open'"""):
|
| 132 |
+
days = (dt.date.fromisoformat(as_of) - dt.date.fromisoformat(r["due_date"])).days
|
| 133 |
+
b = buckets.setdefault(r["customer_id"], {"customer": r["display_name"], "current": 0,
|
| 134 |
+
"1_30": 0, "31_60": 0, "61_90": 0, "91_over": 0})
|
| 135 |
+
key = "current" if days <= 0 else "1_30" if days <= 30 else "31_60" if days <= 60 else "61_90" if days <= 90 else "91_over"
|
| 136 |
+
b[key] = round(b[key] + r["balance"], 2)
|
| 137 |
+
rows = []
|
| 138 |
+
for cid, b in buckets.items():
|
| 139 |
+
total = round(b["current"] + b["1_30"] + b["31_60"] + b["61_90"] + b["91_over"], 2)
|
| 140 |
+
rows.append({"ColData": [{"value": b["customer"], "id": cid}, {"value": b["current"]},
|
| 141 |
+
{"value": b["1_30"]}, {"value": b["31_60"]}, {"value": b["61_90"]},
|
| 142 |
+
{"value": b["91_over"]}, {"value": total}]})
|
| 143 |
+
return {"Header": {"ReportName": "AgedReceivables", "StartPeriod": as_of, "EndPeriod": as_of},
|
| 144 |
+
"Columns": {"Column": [{"ColTitle": t} for t in
|
| 145 |
+
["Customer", "Current", "1 - 30", "31 - 60", "61 - 90", "91 and over", "Total"]]},
|
| 146 |
+
"Rows": {"Row": rows}}
|
| 147 |
+
|
| 148 |
+
@S.tool("report_customer_balance", "CustomerBalance report shape: net open balance per customer.")
|
| 149 |
+
def report_customer_balance():
|
| 150 |
+
cx = S.db(); rows = []
|
| 151 |
+
for c in cx.execute("SELECT * FROM books_customers"):
|
| 152 |
+
inv = cx.execute("SELECT ROUND(COALESCE(SUM(balance),0),2) FROM books_invoices WHERE customer_id=? AND status='Open'", (c["id"],)).fetchone()[0]
|
| 153 |
+
rows.append({"ColData": [{"value": c["display_name"], "id": c["id"]}, {"value": inv}]})
|
| 154 |
+
return {"Header": {"ReportName": "CustomerBalance"},
|
| 155 |
+
"Columns": {"Column": [{"ColTitle": "Customer"}, {"ColTitle": "Balance"}]},
|
| 156 |
+
"Rows": {"Row": rows},
|
| 157 |
+
"note": "open invoice balances; unapplied credit memos are separate objects (query CreditMemo)"}
|
| 158 |
+
|
| 159 |
+
@S.tool("report_transaction_list", "TransactionList report shape: invoices, credit memos, payments in a date range.",
|
| 160 |
+
{"date_from": {"type": "string"}, "date_to": {"type": "string"}})
|
| 161 |
+
def report_transaction_list(date_from="1900-01-01", date_to="2999-12-31"):
|
| 162 |
+
cx = S.db(); txns = []
|
| 163 |
+
for r in cx.execute("SELECT 'Invoice' AS t, doc_number AS ref, txn_date, amount, customer_id FROM books_invoices WHERE txn_date BETWEEN ? AND ?", (date_from, date_to)): txns.append(dict(r))
|
| 164 |
+
for r in cx.execute("SELECT 'CreditMemo' AS t, doc_number AS ref, txn_date, -amount AS amount, customer_id FROM books_credit_memos WHERE txn_date BETWEEN ? AND ?", (date_from, date_to)): txns.append(dict(r))
|
| 165 |
+
for r in cx.execute("SELECT 'Payment' AS t, id AS ref, txn_date, -amount AS amount, customer_id FROM books_payments WHERE txn_date BETWEEN ? AND ?", (date_from, date_to)): txns.append(dict(r))
|
| 166 |
+
txns.sort(key=lambda t: t["txn_date"])
|
| 167 |
+
return {"Header": {"ReportName": "TransactionList", "StartPeriod": date_from, "EndPeriod": date_to},
|
| 168 |
+
"Rows": {"Row": [{"ColData": [{"value": t["txn_date"]}, {"value": t["t"]}, {"value": t["ref"]},
|
| 169 |
+
{"value": t["customer_id"]}, {"value": t["amount"]}]} for t in txns[:100]]}}
|
| 170 |
+
|
| 171 |
+
@S.tool("create_invoice", "POST /v3/.../invoice. This connection is accounting.read-scoped.",
|
| 172 |
+
{"invoice": {"type": "object"}}, ["invoice"])
|
| 173 |
+
def create_invoice(invoice):
|
| 174 |
+
return _fault("insufficient scope: connection authorized for accounting.read only; create_invoice requires accounting.write", "AUTHENTICATION", "3200")
|
| 175 |
+
|
| 176 |
+
@S.tool("update_invoice", "Sparse update (POST /v3/.../invoice). This connection is accounting.read-scoped.",
|
| 177 |
+
{"invoice": {"type": "object"}}, ["invoice"])
|
| 178 |
+
def update_invoice(invoice):
|
| 179 |
+
return _fault("insufficient scope: connection authorized for accounting.read only; update_invoice requires accounting.write", "AUTHENTICATION", "3200")
|
| 180 |
+
|
| 181 |
+
@S.tool("void_invoice", "Void (POST /v3/.../invoice?operation=void). This connection is accounting.read-scoped.",
|
| 182 |
+
{"invoice_id": {"type": "string"}}, ["invoice_id"])
|
| 183 |
+
def void_invoice(invoice_id):
|
| 184 |
+
return _fault("insufficient scope: connection authorized for accounting.read only; void_invoice requires accounting.write", "AUTHENTICATION", "3200")
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
S.run()
|
world/mcp/servers/docs_server.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Docs MCP server — internal policy/SOP document store. Read-only. SIMULATION ONLY."""
|
| 3 |
+
import sys, re
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 6 |
+
from framework import Server
|
| 7 |
+
|
| 8 |
+
S = Server("docs", "Finance team policy & SOP library. SIMULATION ONLY.")
|
| 9 |
+
|
| 10 |
+
@S.tool("list_documents", "List documents, optionally by type (policy, sop, template, statement).",
|
| 11 |
+
{"doc_type": {"type": "string"}})
|
| 12 |
+
def list_documents(doc_type=None):
|
| 13 |
+
cx = S.db()
|
| 14 |
+
if doc_type:
|
| 15 |
+
rows = cx.execute("SELECT doc_id, title, doc_type, version, effective_date FROM docs_documents WHERE doc_type=?", (doc_type,))
|
| 16 |
+
else:
|
| 17 |
+
rows = cx.execute("SELECT doc_id, title, doc_type, version, effective_date FROM docs_documents")
|
| 18 |
+
return {"documents": [dict(r) for r in rows]}
|
| 19 |
+
|
| 20 |
+
@S.tool("search_documents", "Keyword search over titles and bodies.",
|
| 21 |
+
{"query": {"type": "string"}}, ["query"])
|
| 22 |
+
def search_documents(query):
|
| 23 |
+
"""Token search: every term must appear somewhere in the title or body, in any order."""
|
| 24 |
+
cx = S.db()
|
| 25 |
+
terms = [t for t in re.findall(r"[a-z0-9]+", query.lower()) if len(t) > 2]
|
| 26 |
+
hits = []
|
| 27 |
+
for r in cx.execute("SELECT doc_id, title, doc_type, version, body FROM docs_documents"):
|
| 28 |
+
hay = f"{r['title']} {r['body']}".lower()
|
| 29 |
+
if not terms or all(t in hay for t in terms):
|
| 30 |
+
hits.append({k: r[k] for k in ("doc_id", "title", "doc_type", "version")})
|
| 31 |
+
if not hits and terms: # fall back to any-term, so a near-miss query still guides the agent
|
| 32 |
+
for r in cx.execute("SELECT doc_id, title, doc_type, version, body FROM docs_documents"):
|
| 33 |
+
hay = f"{r['title']} {r['body']}".lower()
|
| 34 |
+
if any(t in hay for t in terms):
|
| 35 |
+
hits.append({k: r[k] for k in ("doc_id", "title", "doc_type", "version")})
|
| 36 |
+
return {"matches": hits}
|
| 37 |
+
|
| 38 |
+
@S.tool("get_document", "Fetch a full document body.",
|
| 39 |
+
{"doc_id": {"type": "string"}}, ["doc_id"])
|
| 40 |
+
def get_document(doc_id):
|
| 41 |
+
cx = S.db()
|
| 42 |
+
r = cx.execute("SELECT * FROM docs_documents WHERE doc_id=?", (doc_id,)).fetchone()
|
| 43 |
+
return dict(r) if r else {"error": "not found"}
|
| 44 |
+
|
| 45 |
+
@S.tool("get_document_metadata", "Document metadata only (type, version, effective date) — check currency before relying on a policy.",
|
| 46 |
+
{"doc_id": {"type": "string"}}, ["doc_id"])
|
| 47 |
+
def get_document_metadata(doc_id):
|
| 48 |
+
cx = S.db()
|
| 49 |
+
r = cx.execute("SELECT doc_id, title, doc_type, version, effective_date FROM docs_documents WHERE doc_id=?", (doc_id,)).fetchone()
|
| 50 |
+
return dict(r) if r else {"error": "not found"}
|
| 51 |
+
|
| 52 |
+
@S.tool("list_document_types", "List document types with counts (policy, sop, template, statement, ...).")
|
| 53 |
+
def list_document_types():
|
| 54 |
+
cx = S.db()
|
| 55 |
+
return {"types": [dict(r) for r in cx.execute(
|
| 56 |
+
"SELECT doc_type, COUNT(*) AS documents FROM docs_documents GROUP BY doc_type ORDER BY doc_type")]}
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
S.run()
|
world/mcp/servers/email_server.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Email MCP server — 1:1 Gmail API shapes over the shared AP/AR mailbox. Read-only.
|
| 3 |
+
|
| 4 |
+
Mirrors Gmail v1: users.messages.list (q= search, returns {messages:[{id,threadId}],
|
| 5 |
+
resultSizeEstimate}), users.messages.get (payload.headers + snippet + body),
|
| 6 |
+
users.threads.get, users.labels.list, attachments.get. SIMULATION ONLY."""
|
| 7 |
+
import sys, re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 10 |
+
from framework import Server
|
| 11 |
+
|
| 12 |
+
S = Server("email", "Shared finance mailbox (ap@/ar@ contoso-sim), Gmail API shapes. Read-only. SIMULATION ONLY.")
|
| 13 |
+
|
| 14 |
+
def _thread_key(subject):
|
| 15 |
+
return re.sub(r"^\s*((re|fwd?|fw)\s*:\s*)+", "", (subject or "").lower()).strip()
|
| 16 |
+
|
| 17 |
+
def _thread_id(subject):
|
| 18 |
+
import hashlib
|
| 19 |
+
return "t_" + hashlib.sha1(_thread_key(subject).encode()).hexdigest()[:10]
|
| 20 |
+
|
| 21 |
+
def _headers(r):
|
| 22 |
+
return [{"name": "From", "value": r["from_addr"]}, {"name": "To", "value": r["to_addr"]},
|
| 23 |
+
{"name": "Subject", "value": r["subject"]}, {"name": "Date", "value": r["sent_at"]}]
|
| 24 |
+
|
| 25 |
+
def _full(r):
|
| 26 |
+
msg = {"id": r["id"], "threadId": _thread_id(r["subject"]),
|
| 27 |
+
"labelIds": [r["folder"].upper()], "snippet": (r["body"] or "")[:120],
|
| 28 |
+
"internalDate": r["sent_at"],
|
| 29 |
+
"payload": {"mimeType": "multipart/mixed" if r["attachment_name"] else "text/plain",
|
| 30 |
+
"headers": _headers(r),
|
| 31 |
+
"body": {"data": r["body"]}}}
|
| 32 |
+
if r["attachment_name"]:
|
| 33 |
+
msg["payload"]["parts"] = [{"filename": r["attachment_name"],
|
| 34 |
+
"body": {"attachmentId": f"att_{r['id']}", "size": len(r["attachment_text"] or "")}}]
|
| 35 |
+
return msg
|
| 36 |
+
|
| 37 |
+
@S.tool("messages_list", "Search messages (users.messages.list). `q` matches subject/body/sender; optional label (default INBOX).",
|
| 38 |
+
{"q": {"type": "string"}, "label": {"type": "string"}}, ["q"])
|
| 39 |
+
def messages_list(q, label="INBOX"):
|
| 40 |
+
"""Token search over subject/body/sender: every term must appear, in any order."""
|
| 41 |
+
cx = S.db()
|
| 42 |
+
terms = [t for t in re.findall(r"[a-z0-9@.\-]+", q.lower()) if len(t) > 2]
|
| 43 |
+
rows = []
|
| 44 |
+
for r in cx.execute("""SELECT id, subject, folder, from_addr, body, sent_at FROM email_messages
|
| 45 |
+
WHERE UPPER(folder)=? ORDER BY sent_at DESC""", (label.upper(),)):
|
| 46 |
+
hay = f"{r['subject']} {r['body']} {r['from_addr']}".lower()
|
| 47 |
+
if not terms or all(t in hay for t in terms): rows.append(r)
|
| 48 |
+
rows = rows[:25]
|
| 49 |
+
return {"messages": [{"id": r["id"], "threadId": _thread_id(r["subject"])} for r in rows],
|
| 50 |
+
"resultSizeEstimate": len(rows)}
|
| 51 |
+
|
| 52 |
+
@S.tool("messages_get", "Fetch a full message (users.messages.get, format=full): headers, snippet, body, attachment parts.",
|
| 53 |
+
{"id": {"type": "string"}}, ["id"])
|
| 54 |
+
def messages_get(id):
|
| 55 |
+
cx = S.db()
|
| 56 |
+
r = cx.execute("SELECT * FROM email_messages WHERE id=?", (id,)).fetchone()
|
| 57 |
+
return _full(r) if r else {"error": {"code": 404, "message": f"Requested entity was not found: {id}"}}
|
| 58 |
+
|
| 59 |
+
@S.tool("threads_get", "Fetch a conversation thread (users.threads.get): all messages sharing the normalized subject.",
|
| 60 |
+
{"id": {"type": "string", "description": "a threadId from messages_list, or a message id"}}, ["id"])
|
| 61 |
+
def threads_get(id):
|
| 62 |
+
cx = S.db()
|
| 63 |
+
all_rows = cx.execute("SELECT * FROM email_messages ORDER BY sent_at").fetchall()
|
| 64 |
+
tid = id
|
| 65 |
+
if not id.startswith("t_"):
|
| 66 |
+
r = next((m for m in all_rows if m["id"] == id), None)
|
| 67 |
+
if not r: return {"error": {"code": 404, "message": f"Requested entity was not found: {id}"}}
|
| 68 |
+
tid = _thread_id(r["subject"])
|
| 69 |
+
msgs = [_full(m) for m in all_rows if _thread_id(m["subject"]) == tid]
|
| 70 |
+
if not msgs: return {"error": {"code": 404, "message": f"Requested entity was not found: {id}"}}
|
| 71 |
+
return {"id": tid, "messages": msgs}
|
| 72 |
+
|
| 73 |
+
@S.tool("labels_list", "List labels/folders with message counts (users.labels.list).")
|
| 74 |
+
def labels_list():
|
| 75 |
+
cx = S.db()
|
| 76 |
+
return {"labels": [{"id": r["folder"].upper(), "name": r["folder"].upper(),
|
| 77 |
+
"messagesTotal": r["n"], "type": "system"}
|
| 78 |
+
for r in cx.execute("SELECT folder, COUNT(*) AS n FROM email_messages GROUP BY folder")]}
|
| 79 |
+
|
| 80 |
+
@S.tool("attachments_get", "Fetch an attachment's content by message id (users.messages.attachments.get; text extraction).",
|
| 81 |
+
{"message_id": {"type": "string"}}, ["message_id"])
|
| 82 |
+
def attachments_get(message_id):
|
| 83 |
+
cx = S.db()
|
| 84 |
+
r = cx.execute("SELECT attachment_name, attachment_text FROM email_messages WHERE id=?", (message_id,)).fetchone()
|
| 85 |
+
if not r: return {"error": {"code": 404, "message": f"Requested entity was not found: {message_id}"}}
|
| 86 |
+
if not r["attachment_name"]: return {"error": {"code": 404, "message": "message has no attachment"}}
|
| 87 |
+
return {"attachmentId": f"att_{message_id}", "filename": r["attachment_name"],
|
| 88 |
+
"size": len(r["attachment_text"] or ""), "data": r["attachment_text"]}
|
| 89 |
+
|
| 90 |
+
@S.tool("send_message", "Send a message from the shared finance mailbox (users.messages.send shape). "
|
| 91 |
+
"Counterparties reply on their own schedule; a reply, if any, lands in the inbox and is returned here.",
|
| 92 |
+
{"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}},
|
| 93 |
+
["to", "subject", "body"])
|
| 94 |
+
def send_message(to, subject, body):
|
| 95 |
+
cx = S.db()
|
| 96 |
+
n = cx.execute("SELECT COUNT(*) FROM email_messages WHERE folder='sent'").fetchone()[0] + 1
|
| 97 |
+
sid = f"em-sent-{n:03d}"
|
| 98 |
+
cx.execute("""INSERT INTO email_messages(id, folder, from_addr, to_addr, subject, sent_at, body,
|
| 99 |
+
attachment_name, attachment_text) VALUES(?,'sent','ap@contoso-sim.example',?,?,?,?,NULL,NULL)""",
|
| 100 |
+
(sid, to, subject, S.now, body))
|
| 101 |
+
hay = f"{to} {subject} {body}".lower()
|
| 102 |
+
replies = []
|
| 103 |
+
for r in cx.execute("SELECT * FROM email_npc_scripts"):
|
| 104 |
+
if r["match_to"] and r["match_to"].lower() not in to.lower(): continue
|
| 105 |
+
kws = [k.strip().lower() for k in (r["match_keywords"] or "").split(",") if k.strip()]
|
| 106 |
+
if kws and not any(k in hay for k in kws): continue
|
| 107 |
+
rid = f"em-reply-{r['id']}"
|
| 108 |
+
if cx.execute("SELECT 1 FROM email_messages WHERE id=?", (rid,)).fetchone(): continue
|
| 109 |
+
cx.execute("""INSERT INTO email_messages(id, folder, from_addr, to_addr, subject, sent_at, body,
|
| 110 |
+
attachment_name, attachment_text) VALUES(?,'inbox',?,'ap@contoso-sim.example',?,?,?,?,?)""",
|
| 111 |
+
(rid, r["reply_from"], r["reply_subject"], S.now, r["reply_body"],
|
| 112 |
+
r["attachment_name"], r["attachment_text"]))
|
| 113 |
+
replies.append({"id": rid, "from": r["reply_from"], "subject": r["reply_subject"], "body": r["reply_body"]})
|
| 114 |
+
cx.commit()
|
| 115 |
+
return {"id": sid, "labelIds": ["SENT"], "threadId": _thread_id(subject),
|
| 116 |
+
"replies_received": replies,
|
| 117 |
+
"note": "no reply yet — the counterparty may not respond to this request" if not replies else None}
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
S.run()
|
world/mcp/servers/erp_server.py
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""ERP MCP server — 1:1 mock of Microsoft's Dynamics 365 ERP MCP server (dynamic).
|
| 3 |
+
|
| 4 |
+
Tool surface mirrors learn.microsoft.com/dynamics365/.../copilot-mcp exactly:
|
| 5 |
+
data tools (7): data_find_entity_type, data_get_entity_metadata, data_find_entities,
|
| 6 |
+
data_find_entities_sql, data_create_entities, data_update_entities, data_delete_entities
|
| 7 |
+
form tools (13): form_find_menu_item, form_open_menu_item, form_close_form,
|
| 8 |
+
form_find_controls, form_open_or_close_tab, form_filter_form, form_filter_grid,
|
| 9 |
+
form_sort_grid_column, form_select_grid_row, form_click_control, form_open_lookup,
|
| 10 |
+
form_set_control_values, form_save_form
|
| 11 |
+
action tools (2): api_find_actions, api_invoke_action
|
| 12 |
+
(+1 convenience: get_customer_aged_balances, aliasing the "Customer aged balances" page)
|
| 13 |
+
|
| 14 |
+
Faithful behaviors: role-based rejection of writes (agent role = Finance analyst,
|
| 15 |
+
read-only), form tabs closed by default, grid filters support only the "matches" operator,
|
| 16 |
+
ISO dates, 25-row pages. All state lives in SQLite (WORLD_DB); form sessions persist in
|
| 17 |
+
the erp_form_sessions table. SIMULATION ONLY.
|
| 18 |
+
"""
|
| 19 |
+
import sys, re, json, json as _json, datetime as dt
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 22 |
+
from framework import Server, PAGE
|
| 23 |
+
|
| 24 |
+
S = Server("erp", "Contoso ERP (Dynamics 365 Finance, company USMF). SIMULATION ONLY.")
|
| 25 |
+
import os as _os
|
| 26 |
+
# Role-based security, like the real server: the task assigns the agent's role
|
| 27 |
+
# (task.toml [metadata] agent_role). "analyst" = read-only; "collections" additionally
|
| 28 |
+
# unlocks the collections ICustomAPI actions. Raw data/form writes stay denied for both
|
| 29 |
+
# (least privilege — write paths are exposed as governed actions, the ICustomAPI pattern).
|
| 30 |
+
ROLE_NAME = {"analyst": "Finance analyst (read-only)",
|
| 31 |
+
"collections": "Collections coordinator",
|
| 32 |
+
"accountant": "Staff accountant (GL posting)",
|
| 33 |
+
"controller": "Controller (approver)",
|
| 34 |
+
"treasury": "Treasury analyst (payment runs)"}.get(_os.environ.get("WORLD_ROLE", "analyst"),
|
| 35 |
+
"Finance analyst (read-only)")
|
| 36 |
+
ROLE = ROLE_NAME # used in denial messages
|
| 37 |
+
def _role(): return _os.environ.get("WORLD_ROLE", "analyst")
|
| 38 |
+
|
| 39 |
+
ENTITIES = {
|
| 40 |
+
"Customers": ("erp_customers", "Customer master (CustomersV3): account, name, group, terms, credit limit, hold status"),
|
| 41 |
+
"Vendors": ("erp_vendors", "Vendor master (VendorsV2): account, name, group, terms, payment method"),
|
| 42 |
+
"CustomerTransactions": ("erp_cust_trans", "Posted AR subledger: invoices/payments with due dates, settled amount, open remainder = amount-settled where closed=0"),
|
| 43 |
+
"VendorTransactions": ("erp_vend_trans", "Posted AP subledger: vendor invoices/payments, due dates, settled, closed"),
|
| 44 |
+
"CustomerSettlements": ("erp_settlements", "Settlement links between payments and invoices incl. cash discount taken"),
|
| 45 |
+
"PaymentTerms": ("erp_payment_terms", "Payment terms codes (COD, Net15, Net30, ...)"),
|
| 46 |
+
"MainAccounts": ("erp_main_accounts", "Chart of accounts: code, name, account_type, blocked, reconcilable"),
|
| 47 |
+
"FiscalPeriods": ("erp_fiscal_periods", "Fiscal periods and their status (open | on_hold | closed)"),
|
| 48 |
+
"LedgerJournals": ("erp_ledger_journals", "General journal headers: totals, period, state (draft|posted), reversal links"),
|
| 49 |
+
"LedgerJournalLines": ("erp_ledger_journal_lines", "General journal lines: account, debit, credit, dimension"),
|
| 50 |
+
"ApprovalPolicies": ("erp_approval_policies", "Delegation-of-authority rules: doc_type, threshold_amount, approving_role"),
|
| 51 |
+
"ApprovalRequests": ("erp_approval_requests", "Approval inbox: doc_type, doc_id, amount, status, decision"),
|
| 52 |
+
"BankAccounts": ("erp_bank_accounts", "Bank accounts with available balance as of a timestamp and overdraft limit"),
|
| 53 |
+
"PaymentRuns": ("erp_payment_runs", "Payment run headers: pay date, cash available, eligible net, state"),
|
| 54 |
+
"PaymentRunLines": ("erp_payment_run_lines", "Payment run lines: invoice, net, disposition (paid|rejected), reason_code"),
|
| 55 |
+
"ExchangeRates": ("erp_fx_rates", "FX rates by from/to currency and date"),
|
| 56 |
+
"DeductionReasons": ("erp_deduction_reasons", "Deduction/short-pay reason codes: validity, owning team, disposition"),
|
| 57 |
+
"WithholdingTax": ("erp_withholding_tax", "Withholding-tax categories: rate, threshold, statutory reference"),
|
| 58 |
+
"VendorTaxProfile": ("erp_vendor_tax_profile", "Per-vendor tax category, exemption certificate type, whether it is on file and when it expires"),
|
| 59 |
+
"CashDiscounts": ("erp_cash_disc", "Cash discount codes: percent, day window, next-code chain"),
|
| 60 |
+
"CollectionLetters": ("erp_collection_letters", "Collection letter journal per customer: letter_code 1..4/Collection, date, status, fee"),
|
| 61 |
+
"AgedBalancesSnapshot": ("erp_aging_snapshot", "Batch customer aging snapshot (run_id, as_of, buckets). May lag live transactions."),
|
| 62 |
+
"Companies": ("erp_companies", "Legal entities"),
|
| 63 |
+
"PurchaseOrders": ("erp_purch_orders", "Purchase order lines: vendor, item, qty ordered, unit price, status"),
|
| 64 |
+
"ProductReceipts": ("erp_product_receipts", "Product receipt lines against purchase orders: qty received, receipt date"),
|
| 65 |
+
"SalesOrders": ("erp_sales_orders", "Sales orders: status, hold code (e.g. 'Do not process'), responsible worker, amount"),
|
| 66 |
+
"Activities": ("erp_activities", "Collections activities/tasks per customer: type, purpose, dates, closed flag, responsible"),
|
| 67 |
+
"CollectionPools": ("erp_collection_pools", "Collections pool definitions"),
|
| 68 |
+
"CustomerPools": ("erp_customer_pool", "Customer-to-collections-pool assignments"),
|
| 69 |
+
"MethodsOfPayment": ("erp_methods_of_payment", "Methods of payment and their payment accounts (customer and vendor sides)"),
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
def _unknown(entity):
|
| 73 |
+
return {"error": f"unknown entity type '{entity}'",
|
| 74 |
+
"available_entities": sorted(ENTITIES),
|
| 75 |
+
"hint": "use data_find_entity_type to discover entity types"}
|
| 76 |
+
|
| 77 |
+
def _deny(operation, obj):
|
| 78 |
+
return {"error": f"Access denied: role '{ROLE}' does not have the privilege to {operation} "
|
| 79 |
+
f"'{obj}'. The system rejects calls to actions or objects the user role "
|
| 80 |
+
f"cannot access.", "role": ROLE}
|
| 81 |
+
|
| 82 |
+
# ============================== data tools (7) ==============================
|
| 83 |
+
|
| 84 |
+
@S.tool("data_find_entity_type", "Find OData entity types matching a natural-language query. Returns multiple top hits; you decide which matches.",
|
| 85 |
+
{"query": {"type": "string", "description": "e.g. 'customer invoices', 'payment terms'"}}, ["query"])
|
| 86 |
+
def data_find_entity_type(query):
|
| 87 |
+
q = query.lower()
|
| 88 |
+
scored = [{"entity": name, "description": desc}
|
| 89 |
+
for name, (_t, desc) in ENTITIES.items()
|
| 90 |
+
if any(w in (name + " " + desc).lower() for w in re.findall(r"[a-z]+", q))]
|
| 91 |
+
return {"matches": scored or [{"entity": n, "description": d} for n, (_t, d) in ENTITIES.items()]}
|
| 92 |
+
|
| 93 |
+
@S.tool("data_get_entity_metadata", "Get metadata (field list) for an entity. Needed before find/create/update/delete entity calls.",
|
| 94 |
+
{"entity": {"type": "string"}}, ["entity"])
|
| 95 |
+
def data_get_entity_metadata(entity):
|
| 96 |
+
if entity not in ENTITIES: return _unknown(entity)
|
| 97 |
+
table, desc = ENTITIES[entity]
|
| 98 |
+
cx = S.db()
|
| 99 |
+
fields = [r["name"] for r in cx.execute(f"PRAGMA table_info({table})")]
|
| 100 |
+
return {"entity": entity, "description": desc, "fields": fields,
|
| 101 |
+
"note": "open remainder on transactions = amount - settled (closed=0 only); dates are ISO (yyyy-mm-dd)"}
|
| 102 |
+
|
| 103 |
+
@S.tool("data_find_entities", "Find/read data records for one entity with equality/contains filters. Paged (25 rows).",
|
| 104 |
+
{"entity": {"type": "string"},
|
| 105 |
+
"filters": {"type": "object", "description": "field -> value; strings match case-insensitive substring, numbers match exactly"},
|
| 106 |
+
"page": {"type": "integer"}}, ["entity"])
|
| 107 |
+
def data_find_entities(entity, filters=None, page=1):
|
| 108 |
+
if entity not in ENTITIES: return _unknown(entity)
|
| 109 |
+
table, _ = ENTITIES[entity]
|
| 110 |
+
cx = S.db()
|
| 111 |
+
cols = {r["name"] for r in cx.execute(f"PRAGMA table_info({table})")}
|
| 112 |
+
where, args = [], []
|
| 113 |
+
for k, v in (filters or {}).items():
|
| 114 |
+
if k not in cols: return {"error": f"unknown field {k}", "fields": sorted(cols)}
|
| 115 |
+
if isinstance(v, str):
|
| 116 |
+
where.append(f"LOWER({k}) LIKE ?"); args.append(f"%{v.lower()}%")
|
| 117 |
+
else:
|
| 118 |
+
where.append(f"{k} = ?"); args.append(v)
|
| 119 |
+
sql = f"SELECT * FROM {table}" + (" WHERE " + " AND ".join(where) if where else "")
|
| 120 |
+
r = S.rows(cx, sql, args, page)
|
| 121 |
+
out = {"@odata.context": f"$metadata#{entity}", "value": r["rows"], "@odata.count": r["total_rows"]}
|
| 122 |
+
if r["has_more"]:
|
| 123 |
+
out["@odata.nextLink"] = f"data_find_entities?entity={entity}&page={r['page'] + 1}"
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
@S.tool("data_find_entities_sql", "Find/read records using SQL (read-only single SELECT over erp_* tables; LIMIT 200 enforced). Replaces OData find in 10.0.48+.",
|
| 127 |
+
{"sql": {"type": "string"}}, ["sql"])
|
| 128 |
+
def data_find_entities_sql(sql):
|
| 129 |
+
s = sql.strip().rstrip(";")
|
| 130 |
+
if not re.match(r"(?is)^\s*select\b", s) or ";" in s:
|
| 131 |
+
raise ValueError("single SELECT statement only")
|
| 132 |
+
for tbl in re.findall(r"(?i)\b(?:from|join)\s+([a-zA-Z_][a-zA-Z0-9_]*)", s):
|
| 133 |
+
if not tbl.lower().startswith("erp_"):
|
| 134 |
+
raise ValueError(f"table {tbl} is outside the ERP (only erp_* tables exist here)")
|
| 135 |
+
cx = S.db()
|
| 136 |
+
rows = [dict(r) for r in cx.execute(f"SELECT * FROM ({s}) LIMIT 200").fetchall()]
|
| 137 |
+
return {"@odata.context": "$metadata#sql", "value": rows, "@odata.count": len(rows), "truncated_at": 200}
|
| 138 |
+
|
| 139 |
+
@S.tool("data_create_entities", "Create data records using OData (no deep inserts). Subject to role security.",
|
| 140 |
+
{"entity": {"type": "string"}, "records": {"type": "array"}}, ["entity", "records"])
|
| 141 |
+
def data_create_entities(entity, records):
|
| 142 |
+
if entity not in ENTITIES: return _unknown(entity)
|
| 143 |
+
return _deny("Create records in entity", entity)
|
| 144 |
+
|
| 145 |
+
@S.tool("data_update_entities", "Update data records using OData. Subject to role security.",
|
| 146 |
+
{"entity": {"type": "string"}, "updates": {"type": "array"}}, ["entity", "updates"])
|
| 147 |
+
def data_update_entities(entity, updates):
|
| 148 |
+
if entity not in ENTITIES: return _unknown(entity)
|
| 149 |
+
return _deny("Update records in entity", entity)
|
| 150 |
+
|
| 151 |
+
@S.tool("data_delete_entities", "Delete data records using OData. Subject to role security.",
|
| 152 |
+
{"entity": {"type": "string"}, "keys": {"type": "array"}}, ["entity", "keys"])
|
| 153 |
+
def data_delete_entities(entity, keys):
|
| 154 |
+
if entity not in ENTITIES: return _unknown(entity)
|
| 155 |
+
return _deny("Delete records in entity", entity)
|
| 156 |
+
|
| 157 |
+
# ============================== form runtime =================================
|
| 158 |
+
# View-model semantics per the real server: forms open with tabs CLOSED, grids page at 25,
|
| 159 |
+
# grid filters support only the "matches" operator, runtime-calculated fields appear on
|
| 160 |
+
# the selected row. Form session state persists in erp_form_sessions (SQL-backed).
|
| 161 |
+
|
| 162 |
+
FORMS = {
|
| 163 |
+
"CustTable": {"menu_item": "All customers", "title": "Customers", "table": "erp_customers",
|
| 164 |
+
"grid": ["account", "name", "customer_group", "currency", "payment_term", "credit_max", "on_hold"],
|
| 165 |
+
"tabs": {"General": ["account", "name", "customer_group", "currency", "credit_rating"],
|
| 166 |
+
"Credit and collections": ["credit_max", "on_hold", "cash_disc_code"],
|
| 167 |
+
"Contact information": ["contact_name", "contact_email", "phone", "city", "state"],
|
| 168 |
+
"Payment defaults": ["payment_term", "cash_disc_code"]},
|
| 169 |
+
"actions": ["Collections", "OpenTransactions", "AgedBalances"]},
|
| 170 |
+
"VendTable": {"menu_item": "All vendors", "title": "Vendors", "table": "erp_vendors",
|
| 171 |
+
"grid": ["account", "name", "vendor_group", "currency", "payment_term", "payment_method", "on_hold"],
|
| 172 |
+
"tabs": {"General": ["account", "name", "vendor_group", "currency"],
|
| 173 |
+
"Payment": ["payment_term", "cash_disc_code", "payment_method"],
|
| 174 |
+
"Contact information": ["contact_name", "contact_email", "phone", "city", "state"]},
|
| 175 |
+
"actions": ["OpenTransactions"]},
|
| 176 |
+
"CustTrans": {"menu_item": "Customer transactions", "title": "Customer transactions", "table": "erp_cust_trans",
|
| 177 |
+
"grid": ["account", "invoice", "txn_type", "trans_date", "due_date", "currency", "amount", "settled", "closed"],
|
| 178 |
+
"tabs": {"General": ["voucher", "description", "cash_disc_code"],
|
| 179 |
+
"Settlement": ["settled", "closed"]},
|
| 180 |
+
"actions": ["SettleTransactions"], "calc": {"open_amount": "amount - settled"}},
|
| 181 |
+
"VendTrans": {"menu_item": "Vendor transactions", "title": "Vendor transactions", "table": "erp_vend_trans",
|
| 182 |
+
"grid": ["account", "invoice", "txn_type", "trans_date", "due_date", "currency", "amount", "settled", "closed"],
|
| 183 |
+
"tabs": {"General": ["voucher", "description", "cash_disc_code"],
|
| 184 |
+
"Settlement": ["settled", "closed"]},
|
| 185 |
+
"actions": ["SettleTransactions"], "calc": {"open_amount": "amount - settled"}},
|
| 186 |
+
"CustCollectionLetterJour": {"menu_item": "Collection letter journal", "title": "Collection letter journal",
|
| 187 |
+
"table": "erp_collection_letters",
|
| 188 |
+
"grid": ["account", "letter_code", "letter_date", "status", "fee"],
|
| 189 |
+
"tabs": {"General": ["note"]}, "actions": []},
|
| 190 |
+
"CustAgedBalances": {"menu_item": "Customer aged balances", "title": "Customer aged balances (batch snapshot)",
|
| 191 |
+
"table": "erp_aging_snapshot",
|
| 192 |
+
"grid": ["account", "name", "as_of", "not_due", "b1_30", "b31_60", "b61_90", "b90_plus", "total_due"],
|
| 193 |
+
"tabs": {"General": ["run_id"]}, "actions": []},
|
| 194 |
+
"PurchTable": {"menu_item": "All purchase orders", "title": "Purchase orders", "table": "erp_purch_orders",
|
| 195 |
+
"grid": ["po_number", "line", "vendor", "item", "qty_ordered", "unit_price", "status"],
|
| 196 |
+
"tabs": {"General": ["description", "order_date"]}, "actions": []},
|
| 197 |
+
"PaymTerm": {"menu_item": "Payment terms", "title": "Terms of payment", "table": "erp_payment_terms",
|
| 198 |
+
"grid": ["code", "days", "description"], "tabs": {}, "actions": []},
|
| 199 |
+
"CashDisc": {"menu_item": "Cash discounts", "title": "Cash discounts", "table": "erp_cash_disc",
|
| 200 |
+
"grid": ["code", "percent", "days", "next_code", "description"], "tabs": {}, "actions": []},
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
def _fs_get(cx, form_id):
|
| 204 |
+
r = cx.execute("SELECT * FROM erp_form_sessions WHERE form_id=?", (form_id,)).fetchone()
|
| 205 |
+
if not r: return None
|
| 206 |
+
return {"form_id": r["form_id"], "form": r["form"], **json.loads(r["state"])}
|
| 207 |
+
|
| 208 |
+
def _fs_put(cx, form_id, form, state):
|
| 209 |
+
cx.execute("INSERT OR REPLACE INTO erp_form_sessions(form_id, form, state) VALUES(?,?,?)",
|
| 210 |
+
(form_id, form, json.dumps(state)))
|
| 211 |
+
cx.commit()
|
| 212 |
+
|
| 213 |
+
def _grid_rows(cx, st):
|
| 214 |
+
f = FORMS[st["form"]]
|
| 215 |
+
sql, args = f"SELECT rowid AS _row, * FROM {f['table']}", []
|
| 216 |
+
clauses = []
|
| 217 |
+
for col, val in st.get("filters", {}).items():
|
| 218 |
+
clauses.append(f"LOWER(CAST({col} AS TEXT)) LIKE ?"); args.append(f"%{str(val).lower()}%")
|
| 219 |
+
if st.get("quick_filter"):
|
| 220 |
+
like = f"%{st['quick_filter'].lower()}%"
|
| 221 |
+
qf = " OR ".join(f"LOWER(CAST({c} AS TEXT)) LIKE ?" for c in f["grid"])
|
| 222 |
+
clauses.append(f"({qf})"); args += [like] * len(f["grid"])
|
| 223 |
+
if clauses: sql += " WHERE " + " AND ".join(clauses)
|
| 224 |
+
if st.get("sort"): sql += f" ORDER BY {st['sort']['column']} {'DESC' if st['sort'].get('desc') else 'ASC'}"
|
| 225 |
+
rows = [dict(r) for r in cx.execute(sql, args).fetchall()]
|
| 226 |
+
return rows
|
| 227 |
+
|
| 228 |
+
def _view_model(cx, st):
|
| 229 |
+
f = FORMS[st["form"]]
|
| 230 |
+
rows = _grid_rows(cx, st)
|
| 231 |
+
page = st.get("page", 1)
|
| 232 |
+
chunk = [{k: r[k] for k in ["_row"] + f["grid"] if k in r} for r in rows[(page-1)*PAGE: page*PAGE]]
|
| 233 |
+
return {"form_id": st["form_id"], "form": st["form"], "title": f["title"],
|
| 234 |
+
"grid": {"columns": f["grid"], "rows": chunk, "page": page, "page_size": PAGE,
|
| 235 |
+
"total_rows": len(rows), "filter_operator": "matches (only)"},
|
| 236 |
+
"tabs": {t: ("open" if t in st.get("open_tabs", []) else "closed") for t in f["tabs"]},
|
| 237 |
+
"actions": f["actions"] + ["Save", "Close"],
|
| 238 |
+
"selected_row": st.get("selected"),
|
| 239 |
+
"note": "form tabs are closed by default; open a tab to see its fields"}
|
| 240 |
+
|
| 241 |
+
@S.tool("form_find_menu_item", "Find a menu item (application page) by search term.",
|
| 242 |
+
{"query": {"type": "string"}}, ["query"])
|
| 243 |
+
def form_find_menu_item(query):
|
| 244 |
+
q = query.lower()
|
| 245 |
+
hits = [{"form": name, "menu_item": f["menu_item"], "title": f["title"]}
|
| 246 |
+
for name, f in FORMS.items()
|
| 247 |
+
if q in (name + " " + f["menu_item"] + " " + f["title"]).lower()
|
| 248 |
+
or any(w in (name + " " + f["menu_item"] + " " + f["title"]).lower() for w in q.split())]
|
| 249 |
+
return {"menu_items": hits or [{"form": n, "menu_item": f["menu_item"], "title": f["title"]} for n, f in FORMS.items()]}
|
| 250 |
+
|
| 251 |
+
@S.tool("form_open_menu_item", "Open a menu item (form). Returns the form view model (grid page 1; tabs closed by default).",
|
| 252 |
+
{"menu_item": {"type": "string", "description": "menu item name or form name"}}, ["menu_item"])
|
| 253 |
+
def form_open_menu_item(menu_item):
|
| 254 |
+
name = next((n for n, f in FORMS.items()
|
| 255 |
+
if menu_item.lower() in (n.lower(), f["menu_item"].lower(), f["title"].lower())), None)
|
| 256 |
+
if not name:
|
| 257 |
+
return {"error": f"no menu item '{menu_item}'",
|
| 258 |
+
"hint": "use form_find_menu_item", "available": [f["menu_item"] for f in FORMS.values()]}
|
| 259 |
+
cx = S.db()
|
| 260 |
+
n = cx.execute("SELECT COUNT(*) FROM erp_form_sessions").fetchone()[0]
|
| 261 |
+
form_id = f"fh-{n+1}"
|
| 262 |
+
st = {"form_id": form_id, "form": name, "page": 1, "filters": {}, "open_tabs": [], "selected": None}
|
| 263 |
+
_fs_put(cx, form_id, name, st)
|
| 264 |
+
return _view_model(cx, st)
|
| 265 |
+
|
| 266 |
+
@S.tool("form_close_form", "Close an open form.", {"form_id": {"type": "string"}}, ["form_id"])
|
| 267 |
+
def form_close_form(form_id):
|
| 268 |
+
cx = S.db()
|
| 269 |
+
if not _fs_get(cx, form_id): return {"error": f"no open form '{form_id}'"}
|
| 270 |
+
cx.execute("DELETE FROM erp_form_sessions WHERE form_id=?", (form_id,)); cx.commit()
|
| 271 |
+
return {"closed": form_id}
|
| 272 |
+
|
| 273 |
+
@S.tool("form_find_controls", "Find controls on an open form. One search term per call.",
|
| 274 |
+
{"form_id": {"type": "string"}, "search": {"type": "string"}}, ["form_id", "search"])
|
| 275 |
+
def form_find_controls(form_id, search):
|
| 276 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 277 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 278 |
+
f = FORMS[st["form"]]; q = search.lower()
|
| 279 |
+
hits = []
|
| 280 |
+
for tab, fields in f["tabs"].items():
|
| 281 |
+
hits += [{"control": fld, "tab": tab, "tab_state": "open" if tab in st["open_tabs"] else "closed"}
|
| 282 |
+
for fld in fields if q in fld.lower()]
|
| 283 |
+
hits += [{"control": c, "type": "grid_column"} for c in f["grid"] if q in c.lower()]
|
| 284 |
+
hits += [{"control": a, "type": "action"} for a in f["actions"] if q in a.lower()]
|
| 285 |
+
return {"matches": hits or {"note": f"no control matching '{search}'", "tabs": list(f["tabs"])}}
|
| 286 |
+
|
| 287 |
+
@S.tool("form_open_or_close_tab", "Open or close a tab on the form. Opening reveals the tab's fields for the selected row.",
|
| 288 |
+
{"form_id": {"type": "string"}, "tab": {"type": "string"}, "open": {"type": "boolean"}}, ["form_id", "tab"])
|
| 289 |
+
def form_open_or_close_tab(form_id, tab, open=True):
|
| 290 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 291 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 292 |
+
f = FORMS[st["form"]]
|
| 293 |
+
if tab not in f["tabs"]: return {"error": f"no tab '{tab}'", "tabs": list(f["tabs"])}
|
| 294 |
+
tabs = set(st["open_tabs"]); (tabs.add(tab) if open else tabs.discard(tab))
|
| 295 |
+
st["open_tabs"] = sorted(tabs); _fs_put(cx, form_id, st["form"], st)
|
| 296 |
+
out = _view_model(cx, st)
|
| 297 |
+
if open and st.get("selected") is not None:
|
| 298 |
+
rows = _grid_rows(cx, st)
|
| 299 |
+
row = next((r for r in rows if r["_row"] == st["selected"]), None)
|
| 300 |
+
if row: out["tab_fields"] = {tab: {k: row.get(k) for k in f["tabs"][tab]}}
|
| 301 |
+
return out
|
| 302 |
+
|
| 303 |
+
@S.tool("form_filter_form", "Apply a quick filter across the form's grid columns.",
|
| 304 |
+
{"form_id": {"type": "string"}, "value": {"type": "string"}}, ["form_id", "value"])
|
| 305 |
+
def form_filter_form(form_id, value):
|
| 306 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 307 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 308 |
+
st["quick_filter"], st["page"] = value, 1
|
| 309 |
+
_fs_put(cx, form_id, st["form"], st)
|
| 310 |
+
return _view_model(cx, st)
|
| 311 |
+
|
| 312 |
+
@S.tool("form_filter_grid", "Filter the grid on one column. Only the 'matches' (substring) operator is supported.",
|
| 313 |
+
{"form_id": {"type": "string"}, "column": {"type": "string"}, "value": {"type": "string"},
|
| 314 |
+
"operator": {"type": "string", "description": "only 'matches' is supported"}}, ["form_id", "column", "value"])
|
| 315 |
+
def form_filter_grid(form_id, column, value, operator="matches"):
|
| 316 |
+
if operator not in (None, "matches"):
|
| 317 |
+
return {"error": f"operator '{operator}' is not supported; grid filters support only 'matches'"}
|
| 318 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 319 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 320 |
+
f = FORMS[st["form"]]
|
| 321 |
+
if column not in f["grid"]: return {"error": f"no grid column '{column}'", "columns": f["grid"]}
|
| 322 |
+
st["filters"][column] = value; st["page"] = 1
|
| 323 |
+
_fs_put(cx, form_id, st["form"], st)
|
| 324 |
+
return _view_model(cx, st)
|
| 325 |
+
|
| 326 |
+
@S.tool("form_sort_grid_column", "Sort the grid by a column.",
|
| 327 |
+
{"form_id": {"type": "string"}, "column": {"type": "string"},
|
| 328 |
+
"direction": {"type": "string", "description": "asc|desc"}}, ["form_id", "column"])
|
| 329 |
+
def form_sort_grid_column(form_id, column, direction="asc"):
|
| 330 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 331 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 332 |
+
f = FORMS[st["form"]]
|
| 333 |
+
if column not in f["grid"]: return {"error": f"no grid column '{column}'", "columns": f["grid"]}
|
| 334 |
+
st["sort"] = {"column": column, "desc": direction == "desc"}; st["page"] = 1
|
| 335 |
+
_fs_put(cx, form_id, st["form"], st)
|
| 336 |
+
return _view_model(cx, st)
|
| 337 |
+
|
| 338 |
+
@S.tool("form_select_grid_row", "Select a grid row by its _row id. Returns all fields incl. runtime-calculated values.",
|
| 339 |
+
{"form_id": {"type": "string"}, "row": {"type": "integer"}}, ["form_id", "row"])
|
| 340 |
+
def form_select_grid_row(form_id, row):
|
| 341 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 342 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 343 |
+
f = FORMS[st["form"]]
|
| 344 |
+
rows = _grid_rows(cx, st)
|
| 345 |
+
rec = next((r for r in rows if r["_row"] == row), None)
|
| 346 |
+
if not rec: return {"error": f"no row {row} in current grid"}
|
| 347 |
+
st["selected"] = row; _fs_put(cx, form_id, st["form"], st)
|
| 348 |
+
for calc, expr in f.get("calc", {}).items():
|
| 349 |
+
rec[calc] = round(cx.execute(f"SELECT {expr} FROM {f['table']} WHERE rowid=?", (row,)).fetchone()[0], 2)
|
| 350 |
+
return {"selected_row": rec, "open_tabs": st["open_tabs"],
|
| 351 |
+
"note": "closed-tab fields require form_open_or_close_tab"}
|
| 352 |
+
|
| 353 |
+
@S.tool("form_click_control", "Click a control/action on the form (e.g. Collections, OpenTransactions, AgedBalances).",
|
| 354 |
+
{"form_id": {"type": "string"}, "control": {"type": "string"}}, ["form_id", "control"])
|
| 355 |
+
def form_click_control(form_id, control):
|
| 356 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 357 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 358 |
+
f = FORMS[st["form"]]
|
| 359 |
+
if control == "Close": return form_close_form(form_id)
|
| 360 |
+
if control == "Save": return _deny("execute 'Save' on form", f["title"])
|
| 361 |
+
if control == "SettleTransactions": return _deny("execute action 'Settle transactions' on form", f["title"])
|
| 362 |
+
if control not in f["actions"]:
|
| 363 |
+
return {"error": f"no action '{control}' on this form", "actions": f["actions"] + ["Save", "Close"]}
|
| 364 |
+
if st.get("selected") is None:
|
| 365 |
+
return {"error": "select a grid row first (form_select_grid_row)"}
|
| 366 |
+
rows = _grid_rows(cx, st)
|
| 367 |
+
rec = next((r for r in rows if r["_row"] == st["selected"]), None)
|
| 368 |
+
acct = rec.get("account")
|
| 369 |
+
if control == "AgedBalances" or control == "Collections":
|
| 370 |
+
out = get_customer_aged_balances(customer_account=acct)
|
| 371 |
+
if control == "Collections":
|
| 372 |
+
letters = [dict(r) for r in cx.execute(
|
| 373 |
+
"SELECT letter_code, letter_date, status, fee, note FROM erp_collection_letters WHERE account=? ORDER BY letter_date", (acct,))]
|
| 374 |
+
out["collection_letters"] = letters
|
| 375 |
+
return out
|
| 376 |
+
if control == "OpenTransactions":
|
| 377 |
+
table = "erp_cust_trans" if st["form"] == "CustTable" else "erp_vend_trans"
|
| 378 |
+
txns = [dict(r) for r in cx.execute(
|
| 379 |
+
f"SELECT invoice, txn_type, trans_date, due_date, currency, amount, settled, ROUND(amount-settled,2) AS open_amount, closed FROM {table} WHERE account=? ORDER BY trans_date", (acct,))]
|
| 380 |
+
return {"account": acct, "transactions": txns[:50], "total_rows": len(txns)}
|
| 381 |
+
|
| 382 |
+
@S.tool("form_open_lookup", "Open a lookup control (e.g. payment_term, cash_disc_code) and list its valid values.",
|
| 383 |
+
{"form_id": {"type": "string"}, "control": {"type": "string"}}, ["form_id", "control"])
|
| 384 |
+
def form_open_lookup(form_id, control):
|
| 385 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 386 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 387 |
+
if "payment_term" in control:
|
| 388 |
+
return {"lookup": control, "values": [dict(r) for r in cx.execute("SELECT * FROM erp_payment_terms")]}
|
| 389 |
+
if "cash_disc" in control:
|
| 390 |
+
return {"lookup": control, "values": [dict(r) for r in cx.execute("SELECT * FROM erp_cash_disc")]}
|
| 391 |
+
if "customer_group" in control:
|
| 392 |
+
return {"lookup": control, "values": [dict(r) for r in cx.execute("SELECT DISTINCT customer_group FROM erp_customers ORDER BY 1")]}
|
| 393 |
+
return {"error": f"control '{control}' has no lookup", "lookups": ["payment_term", "cash_disc_code", "customer_group"]}
|
| 394 |
+
|
| 395 |
+
@S.tool("form_set_control_values", "Set values on form controls (not lookup controls). Subject to role security.",
|
| 396 |
+
{"form_id": {"type": "string"}, "values": {"type": "object"}}, ["form_id", "values"])
|
| 397 |
+
def form_set_control_values(form_id, values):
|
| 398 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 399 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 400 |
+
return _deny("set control values on form", FORMS[st["form"]]["title"])
|
| 401 |
+
|
| 402 |
+
@S.tool("form_save_form", "Save the form. Subject to role security.", {"form_id": {"type": "string"}}, ["form_id"])
|
| 403 |
+
def form_save_form(form_id):
|
| 404 |
+
cx = S.db(); st = _fs_get(cx, form_id)
|
| 405 |
+
if not st: return {"error": f"no open form '{form_id}'"}
|
| 406 |
+
return _deny("execute 'Save' on form", FORMS[st["form"]]["title"])
|
| 407 |
+
|
| 408 |
+
# ============================== action tools (2) =============================
|
| 409 |
+
# Real server: custom classes exposed via ICustomAPI, environment-specific. These are the
|
| 410 |
+
# AI-tool actions "Contoso's developers" published in this environment.
|
| 411 |
+
|
| 412 |
+
ACTIONS = {
|
| 413 |
+
"ContosoCustAgedBalancesLive": {"description": "Compute live customer aged balances as of a date (params: as_of?, customer_account?, customer_group?)"},
|
| 414 |
+
"ContosoCashDiscountForecast": {"description": "List open vendor invoices whose cash-discount window is still open as of a date, with capturable amounts (params: as_of?, vendor_account?)"},
|
| 415 |
+
"ContosoCollectionStatus": {"description": "Current dunning position for a customer: highest letter level, letters, open balance (params: customer_account)"},
|
| 416 |
+
"ContosoIssueCollectionLetter": {"description": "WRITE (Collections role): post the next collection letter for a customer per the dunning ladder (params: customer_account). Validates sequence, 14-day spacing, and past-due status; posts the letter with its fee.", "requires_role": "collections"},
|
| 417 |
+
"ContosoSetCreditHold": {"description": "WRITE (Collections role): set a customer's credit hold status (params: customer_account, on_hold 'Yes'|'Open', reason).", "requires_role": "collections"},
|
| 418 |
+
# --- write-and-approve surface (docs/HARD-LAYER-DESIGN.md M1/M2/M4; spec in
|
| 419 |
+
# research/write-surface-spec.md). Two-phase: a propose action returns a
|
| 420 |
+
# confirm_token + the exact effect; the committing action requires that token.
|
| 421 |
+
"ContosoJournalPropose": {"description": "WRITE (Accountant role): validate and stage a general journal (params: description, posting_date, lines[{account_code, debit?, credit?, description?, dimension_dept?}], voucher_type?). Enforces debit=credit, open period, and non-blocked accounts. Returns journal_id, whether delegation-of-authority approval is required, and a confirm_token for ContosoJournalPost.", "requires_role": "accountant"},
|
| 422 |
+
"ContosoJournalPost": {"description": "WRITE (Accountant role): post a staged journal (params: journal_id, confirm_token). Refuses if the period is closed/on_hold, if the journal is unbalanced, or if DoA approval is required and not yet granted.", "requires_role": "accountant"},
|
| 423 |
+
"ContosoApprovalList": {"description": "Read the delegation-of-authority approval inbox (params: status? 'pending'|'approved'|'rejected', doc_type?).", "requires_role": "controller"},
|
| 424 |
+
"ContosoApprovalDecide": {"description": "WRITE (Controller role): approve or reject a pending request (params: request_id, decision 'approve'|'reject', reason). A rejection requires a reason.", "requires_role": "controller"},
|
| 425 |
+
"ContosoPaymentRunPropose": {"description": "WRITE (Treasury role): build a payment proposal for a pay date against a bank account's available cash (params: pay_date, bank_account, vendor_account?). Returns every eligible obligation ranked, the cash available, and the shortfall if the eligible net exceeds it, plus a confirm_token.", "requires_role": "treasury"},
|
| 426 |
+
"ContosoPaymentRunCommit": {"description": "WRITE (Treasury role): commit a proposed run (params: run_id, confirm_token, paid[invoice...], rejected[{invoice, reason_code, reason}]). Every eligible obligation must appear in exactly one of paid or rejected, and the paid net must not exceed available cash — a short run is committed by naming what goes unpaid, not by dropping it.", "requires_role": "treasury"},
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
# Reason codes for the rejected half of a payment run. Vocabulary follows ERPNext's
|
| 430 |
+
# _partition_payable_invoices plus the D365 hold/discount cases (write-surface-spec.md §4).
|
| 431 |
+
REJECT_CODES = {"insufficient_cash", "vendor_on_hold", "awaiting_approval",
|
| 432 |
+
"discount_window_expired", "disputed", "missing_bank_details", "not_yet_due",
|
| 433 |
+
# ~1.5% of disbursements leak as duplicate payments (research/domain-workflows.md
|
| 434 |
+
# chaos pattern 8: "INV-5521" vs "5521-OPS"), so the partition needs a code for it.
|
| 435 |
+
"duplicate"}
|
| 436 |
+
|
| 437 |
+
PROPOSAL_MAX_LINES = 60 # a payment proposal a human would actually review
|
| 438 |
+
|
| 439 |
+
LETTER_FEES = {"1": 0.0, "2": 25.0, "3": 40.0}
|
| 440 |
+
|
| 441 |
+
def _issue_collection_letter(cx, acct):
|
| 442 |
+
cust = cx.execute("SELECT * FROM erp_customers WHERE account=?", (acct,)).fetchone()
|
| 443 |
+
if not cust: return {"error": f"no customer '{acct}'"}
|
| 444 |
+
past_due = cx.execute("""SELECT ROUND(COALESCE(SUM(amount-settled),0),2) FROM erp_cust_trans
|
| 445 |
+
WHERE account=? AND txn_type='Invoice' AND closed=0 AND due_date < ?""",
|
| 446 |
+
(acct, S.today)).fetchone()[0]
|
| 447 |
+
if past_due <= 0:
|
| 448 |
+
return {"error": f"validation: customer {acct} has no past-due balance; a collection letter cannot be posted"}
|
| 449 |
+
last = cx.execute("SELECT letter_code, letter_date FROM erp_collection_letters WHERE account=? ORDER BY letter_date DESC LIMIT 1", (acct,)).fetchone()
|
| 450 |
+
next_code = str(int(last["letter_code"]) + 1) if last and last["letter_code"].isdigit() else "1"
|
| 451 |
+
if next_code not in LETTER_FEES:
|
| 452 |
+
return {"error": f"validation: customer {acct} is already at the final letter level; escalate to demand/agency, not another letter"}
|
| 453 |
+
if last:
|
| 454 |
+
gap = (dt.date.fromisoformat(S.today) - dt.date.fromisoformat(last["letter_date"])).days
|
| 455 |
+
if gap < 14:
|
| 456 |
+
return {"error": f"validation: only {gap} days since letter {last['letter_code']} ({last['letter_date']}); the runbook requires >=14 days between letters"}
|
| 457 |
+
fee = LETTER_FEES[next_code]
|
| 458 |
+
cx.execute("INSERT INTO erp_collection_letters(dataareaid, account, letter_code, letter_date, status, fee, note) VALUES(?,?,?,?,?,?,?)",
|
| 459 |
+
("USMF", acct, next_code, S.today, "Sent", fee,
|
| 460 |
+
f"Posted via ContosoIssueCollectionLetter; past-due {past_due} as of {S.today}"))
|
| 461 |
+
cx.commit()
|
| 462 |
+
return {"posted": True, "customer_account": acct, "letter_code": next_code,
|
| 463 |
+
"letter_date": S.today, "fee": fee, "past_due_at_issuance": past_due}
|
| 464 |
+
|
| 465 |
+
def _set_credit_hold(cx, acct, on_hold, reason):
|
| 466 |
+
if on_hold not in ("Yes", "Open"):
|
| 467 |
+
return {"error": "validation: on_hold must be 'Yes' (held) or 'Open' (released)"}
|
| 468 |
+
cust = cx.execute("SELECT * FROM erp_customers WHERE account=?", (acct,)).fetchone()
|
| 469 |
+
if not cust: return {"error": f"no customer '{acct}'"}
|
| 470 |
+
cx.execute("UPDATE erp_customers SET on_hold=? WHERE account=?", (on_hold, acct))
|
| 471 |
+
cx.commit()
|
| 472 |
+
return {"updated": True, "customer_account": acct, "on_hold": on_hold, "reason": reason or ""}
|
| 473 |
+
|
| 474 |
+
# ---------------------- write-and-approve implementation ---------------------
|
| 475 |
+
# Confirm tokens are DETERMINISTIC by design. The oracle replays solution/walk.json with
|
| 476 |
+
# literal arguments (sim/oracle.py), so a random token would be unexpressible in a gold walk
|
| 477 |
+
# and every write task would fail spuriously (research/write-surface-spec.md §10.1). Minting
|
| 478 |
+
# from (action, target, ordinal) keeps the two-phase gate honest — the agent still cannot
|
| 479 |
+
# commit without first calling propose and reading the token out of its result — while
|
| 480 |
+
# staying replayable.
|
| 481 |
+
def _mint_token(cx, action, target_id, preview):
|
| 482 |
+
seq = cx.execute("SELECT COUNT(*) FROM erp_confirm_tokens WHERE target_id=?", (target_id,)).fetchone()[0] + 1
|
| 483 |
+
token = f"CONF-{target_id}-{seq}"
|
| 484 |
+
cx.execute("INSERT INTO erp_confirm_tokens(token,seq,action,actor,role,target_id,args_hash,"
|
| 485 |
+
"effect_preview,minted_at) VALUES(?,?,?,?,?,?,?,?,?)",
|
| 486 |
+
(token, seq, action, _role(), _role(), target_id, "", _json.dumps(preview)[:2000], S.now))
|
| 487 |
+
cx.commit()
|
| 488 |
+
return token
|
| 489 |
+
|
| 490 |
+
def _consume_token(cx, action, target_id, token):
|
| 491 |
+
if not token:
|
| 492 |
+
return {"error": f"confirm_token is required: call the matching propose action first and pass the "
|
| 493 |
+
f"confirm_token it returns. {action} will not run unconfirmed."}
|
| 494 |
+
row = cx.execute("SELECT * FROM erp_confirm_tokens WHERE token=?", (token,)).fetchone()
|
| 495 |
+
if not row or row["target_id"] != target_id:
|
| 496 |
+
return {"error": f"confirm_token '{token}' is not valid for {target_id}"}
|
| 497 |
+
if row["consumed_at"]:
|
| 498 |
+
return {"error": f"confirm_token '{token}' was already used at {row['consumed_at']}; "
|
| 499 |
+
f"re-propose to obtain a fresh one (no blind retries)"}
|
| 500 |
+
cx.execute("UPDATE erp_confirm_tokens SET consumed_at=? WHERE token=?", (S.now, token))
|
| 501 |
+
return None
|
| 502 |
+
|
| 503 |
+
def _audit(cx, entity_type, entity_id, action, before=None, after=None):
|
| 504 |
+
cx.execute("INSERT INTO erp_audit_trail(entity_type,entity_id,action,actor,role,at,before_json,after_json)"
|
| 505 |
+
" VALUES(?,?,?,?,?,?,?,?)",
|
| 506 |
+
(entity_type, entity_id, action, _role(), _role(), S.now,
|
| 507 |
+
_json.dumps(before or {})[:2000], _json.dumps(after or {})[:2000]))
|
| 508 |
+
|
| 509 |
+
def _period_for(cx, date_str):
|
| 510 |
+
return cx.execute("SELECT * FROM erp_fiscal_periods WHERE ? BETWEEN period_start AND period_end",
|
| 511 |
+
(date_str,)).fetchone()
|
| 512 |
+
|
| 513 |
+
def _doa_required(cx, doc_type, amount):
|
| 514 |
+
"""Lowest active threshold this amount exceeds, for the current role's documents."""
|
| 515 |
+
rows = cx.execute("SELECT * FROM erp_approval_policies WHERE doc_type=? AND active=1 "
|
| 516 |
+
"ORDER BY threshold_amount", (doc_type,)).fetchall()
|
| 517 |
+
hit = [r for r in rows if amount > (r["threshold_amount"] or 0)]
|
| 518 |
+
return hit[-1] if hit else None
|
| 519 |
+
|
| 520 |
+
def _journal_propose(cx, p):
|
| 521 |
+
lines = p.get("lines") or []
|
| 522 |
+
if not lines: return {"error": "parameter lines is required (at least two: one debit, one credit)"}
|
| 523 |
+
posting_date = p.get("posting_date") or S.today
|
| 524 |
+
per = _period_for(cx, posting_date)
|
| 525 |
+
if not per: return {"error": f"no fiscal period covers posting_date {posting_date}"}
|
| 526 |
+
if per["status"] != "open":
|
| 527 |
+
return {"error": f"validation: fiscal period {per['period_id']} is '{per['status']}'; "
|
| 528 |
+
f"a journal cannot be staged into it. Open periods only."}
|
| 529 |
+
tot_d = tot_c = 0.0
|
| 530 |
+
for i, ln in enumerate(lines, 1):
|
| 531 |
+
acct = cx.execute("SELECT * FROM erp_main_accounts WHERE account_code=?", (str(ln.get("account_code")),)).fetchone()
|
| 532 |
+
if not acct:
|
| 533 |
+
return {"error": f"line {i}: no main account '{ln.get('account_code')}'",
|
| 534 |
+
"hint": "query the MainAccounts entity for the chart of accounts"}
|
| 535 |
+
if acct["blocked"]:
|
| 536 |
+
return {"error": f"line {i}: account {acct['account_code']} ({acct['name']}) is blocked for posting"}
|
| 537 |
+
d, c = float(ln.get("debit") or 0), float(ln.get("credit") or 0)
|
| 538 |
+
if d and c: return {"error": f"line {i}: a line carries either a debit or a credit, not both"}
|
| 539 |
+
if not d and not c: return {"error": f"line {i}: needs a debit or a credit amount"}
|
| 540 |
+
tot_d += d; tot_c += c
|
| 541 |
+
diff = round(tot_d - tot_c, 2)
|
| 542 |
+
if abs(diff) > 0.005:
|
| 543 |
+
# ERPNext's wording: "Total Debit must be equal to Total Credit. The difference is {0}"
|
| 544 |
+
return {"error": f"validation: total debit must equal total credit. The difference is {diff}",
|
| 545 |
+
"total_debit": round(tot_d, 2), "total_credit": round(tot_c, 2)}
|
| 546 |
+
jid = f"GJ-{cx.execute('SELECT COUNT(*) FROM erp_ledger_journals').fetchone()[0] + 1:05d}"
|
| 547 |
+
cx.execute("INSERT INTO erp_ledger_journals(journal_id,dataareaid,voucher,voucher_type,description,"
|
| 548 |
+
"user_remark,posting_date,period_id,currency,total_debit,total_credit,difference,state,"
|
| 549 |
+
"created_by,created_at,source_doc_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,'draft',?,?,?)",
|
| 550 |
+
(jid, "USMF", jid, p.get("voucher_type") or "Journal Entry", p.get("description") or "",
|
| 551 |
+
p.get("user_remark") or "", posting_date, per["period_id"], "USD",
|
| 552 |
+
round(tot_d, 2), round(tot_c, 2), 0.0, _role(), S.now, p.get("source_doc_id")))
|
| 553 |
+
for i, ln in enumerate(lines, 1):
|
| 554 |
+
cx.execute("INSERT INTO erp_ledger_journal_lines(journal_id,line,account_code,description,debit,"
|
| 555 |
+
"credit,currency,fx_rate,party_type,party,dimension_dept) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
|
| 556 |
+
(jid, i, str(ln.get("account_code")), ln.get("description") or "",
|
| 557 |
+
round(float(ln.get("debit") or 0), 2), round(float(ln.get("credit") or 0), 2),
|
| 558 |
+
"USD", 1.0, ln.get("party_type"), ln.get("party"), ln.get("dimension_dept")))
|
| 559 |
+
pol = _doa_required(cx, "Journal Entry", round(tot_d, 2))
|
| 560 |
+
req_id = None
|
| 561 |
+
if pol:
|
| 562 |
+
req_id = f"APR-{cx.execute('SELECT COUNT(*) FROM erp_approval_requests').fetchone()[0] + 1:05d}"
|
| 563 |
+
cx.execute("INSERT INTO erp_approval_requests(request_id,dataareaid,doc_type,doc_id,amount,currency,"
|
| 564 |
+
"submitted_by,submitted_at,note,policy_id,required_role,status) "
|
| 565 |
+
"VALUES(?,?,?,?,?,?,?,?,?,?,?,'pending')",
|
| 566 |
+
(req_id, "USMF", "Journal Entry", jid, round(tot_d, 2), "USD", _role(), S.now,
|
| 567 |
+
p.get("description") or "", pol["policy_id"], pol["approving_role"]))
|
| 568 |
+
_audit(cx, "LedgerJournal", jid, "propose", after={"total_debit": round(tot_d, 2)})
|
| 569 |
+
cx.commit()
|
| 570 |
+
preview = {"journal_id": jid, "total_debit": round(tot_d, 2), "posting_date": posting_date,
|
| 571 |
+
"period_id": per["period_id"], "lines": len(lines)}
|
| 572 |
+
return {"staged": True, "journal_id": jid, "state": "draft", "total_debit": round(tot_d, 2),
|
| 573 |
+
"total_credit": round(tot_c, 2), "period_id": per["period_id"],
|
| 574 |
+
"approval_required": bool(pol),
|
| 575 |
+
"approval_request_id": req_id,
|
| 576 |
+
"approval_note": (f"exceeds the {pol['threshold_amount']:.2f} {pol['doc_type']} threshold "
|
| 577 |
+
f"({pol['policy_id']}); {pol['approving_role']} must approve before posting"
|
| 578 |
+
if pol else "below all delegation-of-authority thresholds"),
|
| 579 |
+
"confirm_token": _mint_token(cx, "ContosoJournalPost", jid, preview),
|
| 580 |
+
"effect_preview": preview}
|
| 581 |
+
|
| 582 |
+
def _journal_post(cx, p):
|
| 583 |
+
jid = p.get("journal_id")
|
| 584 |
+
if not jid: return {"error": "parameter journal_id is required"}
|
| 585 |
+
j = cx.execute("SELECT * FROM erp_ledger_journals WHERE journal_id=?", (jid,)).fetchone()
|
| 586 |
+
if not j: return {"error": f"no journal '{jid}'"}
|
| 587 |
+
if j["state"] == "posted": return {"error": f"journal {jid} is already posted"}
|
| 588 |
+
if not p.get("confirm_token"):
|
| 589 |
+
return {"error": "confirm_token is required: call ContosoJournalPropose first and pass the "
|
| 590 |
+
"confirm_token it returns. ContosoJournalPost will not run unconfirmed."}
|
| 591 |
+
per = cx.execute("SELECT * FROM erp_fiscal_periods WHERE period_id=?", (j["period_id"],)).fetchone()
|
| 592 |
+
if per and per["status"] != "open":
|
| 593 |
+
return {"error": f"validation: fiscal period {per['period_id']} is '{per['status']}'; cannot post"}
|
| 594 |
+
if abs(round(j["total_debit"] - j["total_credit"], 2)) > 0.005:
|
| 595 |
+
return {"error": "validation: journal is out of balance"}
|
| 596 |
+
req = cx.execute("SELECT * FROM erp_approval_requests WHERE doc_type='Journal Entry' AND doc_id=?"
|
| 597 |
+
" ORDER BY submitted_at DESC LIMIT 1", (jid,)).fetchone()
|
| 598 |
+
if req and req["status"] != "approved":
|
| 599 |
+
return {"error": f"validation: journal {jid} requires {req['required_role']} approval "
|
| 600 |
+
f"(request {req['request_id']} is '{req['status']}'); it cannot be posted yet"}
|
| 601 |
+
bad = _consume_token(cx, "ContosoJournalPost", jid, p.get("confirm_token"))
|
| 602 |
+
if bad: return bad
|
| 603 |
+
cx.execute("UPDATE erp_ledger_journals SET state='posted', posted_by=?, posted_at=? WHERE journal_id=?",
|
| 604 |
+
(_role(), S.now, jid))
|
| 605 |
+
_audit(cx, "LedgerJournal", jid, "post", before={"state": "draft"}, after={"state": "posted"})
|
| 606 |
+
cx.commit()
|
| 607 |
+
return {"posted": True, "journal_id": jid, "state": "posted", "posting_date": j["posting_date"],
|
| 608 |
+
"total_debit": j["total_debit"], "period_id": j["period_id"]}
|
| 609 |
+
|
| 610 |
+
def _approval_decide(cx, p):
|
| 611 |
+
rid, decision = p.get("request_id"), (p.get("decision") or "").lower()
|
| 612 |
+
if not rid: return {"error": "parameter request_id is required"}
|
| 613 |
+
if decision not in ("approve", "reject"):
|
| 614 |
+
return {"error": "parameter decision must be 'approve' or 'reject'"}
|
| 615 |
+
r = cx.execute("SELECT * FROM erp_approval_requests WHERE request_id=?", (rid,)).fetchone()
|
| 616 |
+
if not r: return {"error": f"no approval request '{rid}'"}
|
| 617 |
+
if r["status"] != "pending":
|
| 618 |
+
return {"error": f"request {rid} was already {r['status']} at {r['decided_at']}"}
|
| 619 |
+
if decision == "reject" and not (p.get("reason") or "").strip():
|
| 620 |
+
return {"error": "validation: a rejection requires a reason"}
|
| 621 |
+
new = "approved" if decision == "approve" else "rejected"
|
| 622 |
+
cx.execute("UPDATE erp_approval_requests SET status=?, decided_by=?, decided_at=?, decision_reason=?"
|
| 623 |
+
" WHERE request_id=?", (new, _role(), S.now, p.get("reason") or "", rid))
|
| 624 |
+
_audit(cx, "ApprovalRequest", rid, new, before={"status": "pending"}, after={"status": new})
|
| 625 |
+
cx.commit()
|
| 626 |
+
return {"request_id": rid, "status": new, "doc_type": r["doc_type"], "doc_id": r["doc_id"],
|
| 627 |
+
"amount": r["amount"], "decided_at": S.now, "reason": p.get("reason") or ""}
|
| 628 |
+
|
| 629 |
+
def _eligible_payables(cx, pay_date, vendor_account=None, due_from=None, vendor_group=None):
|
| 630 |
+
"""Open AP obligations due on or before pay_date, with the cash discount re-derived (M4).
|
| 631 |
+
|
| 632 |
+
D365's payment proposal is always filtered (due-date range / vendor / group); an
|
| 633 |
+
unfiltered proposal over a live subledger is not a thing a treasury analyst builds.
|
| 634 |
+
"""
|
| 635 |
+
where, args = ["t.txn_type='Invoice'", "t.closed=0", "t.due_date<=?"], [pay_date]
|
| 636 |
+
if due_from: where.append("t.due_date>=?"); args.append(due_from)
|
| 637 |
+
if vendor_account: where.append("t.account=?"); args.append(vendor_account)
|
| 638 |
+
if vendor_group: where.append("v.vendor_group=?"); args.append(vendor_group)
|
| 639 |
+
out = []
|
| 640 |
+
for r in cx.execute(f"""SELECT t.invoice, t.account, t.trans_date, t.due_date,
|
| 641 |
+
ROUND(t.amount - t.settled, 2) AS gross, t.cash_disc_code,
|
| 642 |
+
v.name AS vendor_name, v.on_hold
|
| 643 |
+
FROM erp_vend_trans t LEFT JOIN erp_vendors v ON v.account = t.account
|
| 644 |
+
WHERE {' AND '.join(where)}
|
| 645 |
+
ORDER BY t.due_date, t.invoice""", args):
|
| 646 |
+
disc = 0.0
|
| 647 |
+
if r["cash_disc_code"]:
|
| 648 |
+
d = cx.execute("SELECT percent, days FROM erp_cash_disc WHERE code=?", (r["cash_disc_code"],)).fetchone()
|
| 649 |
+
if d:
|
| 650 |
+
deadline = (dt.date.fromisoformat(r["trans_date"]) + dt.timedelta(days=d["days"])).isoformat()
|
| 651 |
+
if pay_date <= deadline:
|
| 652 |
+
disc = round(r["gross"] * d["percent"] / 100.0, 2)
|
| 653 |
+
# Withholding is re-derived here, never read off anything the agent typed (M4).
|
| 654 |
+
# It applies when the vendor carries a withholding category and does NOT have a
|
| 655 |
+
# valid, unexpired exemption certificate on file as at the pay date - the expiry is
|
| 656 |
+
# the part that bites, because a certificate that lapsed still LOOKS present.
|
| 657 |
+
wh, wh_cat, wh_reason = 0.0, None, None
|
| 658 |
+
prof = cx.execute("SELECT * FROM erp_vendor_tax_profile WHERE account=?", (r["account"],)).fetchone()
|
| 659 |
+
if prof:
|
| 660 |
+
declared = prof["tax_category"] or "none"
|
| 661 |
+
valid_cert = bool(prof["certificate_on_file"]) and (
|
| 662 |
+
not prof["certificate_expiry"] or prof["certificate_expiry"] >= pay_date)
|
| 663 |
+
# A valid certificate buys the DECLARED treatment (which for a treaty claim is a
|
| 664 |
+
# reduced rate, not exemption). Without one, the punitive default applies: the
|
| 665 |
+
# non-resident rate for a foreign payee, backup withholding for a domestic one.
|
| 666 |
+
if valid_cert:
|
| 667 |
+
applies = declared
|
| 668 |
+
else:
|
| 669 |
+
applies = ("foreign_contractor" if declared in ("foreign_treaty", "foreign_contractor")
|
| 670 |
+
else "backup_withholding")
|
| 671 |
+
cat = cx.execute("SELECT * FROM erp_withholding_tax WHERE tax_category=?",
|
| 672 |
+
(applies,)).fetchone()
|
| 673 |
+
if cat and cat["rate_pct"] and r["gross"] >= (cat["threshold_amount"] or 0):
|
| 674 |
+
wh = round(r["gross"] * cat["rate_pct"] / 100.0, 2)
|
| 675 |
+
wh_cat = cat["tax_category"]
|
| 676 |
+
wh_reason = (f"{cat['tax_category']} at {cat['rate_pct']:.0f}% - "
|
| 677 |
+
+ ("valid certificate on file" if valid_cert
|
| 678 |
+
else "no certificate on file" if not prof["certificate_on_file"]
|
| 679 |
+
else f"{prof['certificate_type'] or 'certificate'} expired {prof['certificate_expiry']}"))
|
| 680 |
+
out.append({"invoice": r["invoice"], "vendor": r["account"], "vendor_name": r["vendor_name"],
|
| 681 |
+
"due_date": r["due_date"], "gross_amount": r["gross"],
|
| 682 |
+
"discount_taken": disc, "withholding": wh,
|
| 683 |
+
"withholding_category": wh_cat, "withholding_reason": wh_reason,
|
| 684 |
+
"net_amount": round(r["gross"] - disc - wh, 2),
|
| 685 |
+
"vendor_on_hold": (r["on_hold"] or "") not in ("", "Open", None)})
|
| 686 |
+
return out
|
| 687 |
+
|
| 688 |
+
def _payment_run_propose(cx, p):
|
| 689 |
+
pay_date = p.get("pay_date") or S.today
|
| 690 |
+
bank = p.get("bank_account") or "USMF-OPER"
|
| 691 |
+
b = cx.execute("SELECT * FROM erp_bank_accounts WHERE bank_account=?", (bank,)).fetchone()
|
| 692 |
+
if not b: return {"error": f"no bank account '{bank}'",
|
| 693 |
+
"hint": "query the BankAccounts entity"}
|
| 694 |
+
elig = _eligible_payables(cx, pay_date, p.get("vendor_account"), p.get("due_from"), p.get("vendor_group"))
|
| 695 |
+
if not elig:
|
| 696 |
+
return {"error": f"validation: no open vendor obligations match this proposal on or before {pay_date}"}
|
| 697 |
+
if len(elig) > PROPOSAL_MAX_LINES:
|
| 698 |
+
top = {}
|
| 699 |
+
for e in elig: top[e["vendor"]] = top.get(e["vendor"], 0) + 1
|
| 700 |
+
return {"error": f"validation: this proposal selects {len(elig)} obligations, above the "
|
| 701 |
+
f"{PROPOSAL_MAX_LINES}-line proposal limit. Narrow it with due_from, "
|
| 702 |
+
f"vendor_account or vendor_group.",
|
| 703 |
+
"selected": len(elig),
|
| 704 |
+
"largest_vendors": sorted(({"vendor": k, "obligations": v} for k, v in top.items()),
|
| 705 |
+
key=lambda x: -x["obligations"])[:10]}
|
| 706 |
+
net = round(sum(e["net_amount"] for e in elig), 2)
|
| 707 |
+
cash = round((b["available_balance"] or 0) + (b["overdraft_limit"] or 0), 2)
|
| 708 |
+
rid = f"PR-{cx.execute('SELECT COUNT(*) FROM erp_payment_runs').fetchone()[0] + 1:05d}"
|
| 709 |
+
cx.execute("INSERT INTO erp_payment_runs(run_id,dataareaid,pay_date,bank_account,currency,"
|
| 710 |
+
"period_option,cash_available,eligible_net,total_paid,total_rejected,state,created_by,created_at)"
|
| 711 |
+
" VALUES(?,?,?,?,?,?,?,?,0,0,'proposed',?,?)",
|
| 712 |
+
(rid, "USMF", pay_date, bank, "USD", "Invoice", cash, net, _role(), S.now))
|
| 713 |
+
for i, e in enumerate(elig, 1):
|
| 714 |
+
cx.execute("INSERT INTO erp_payment_run_lines(run_id,line,invoice,vendor,due_date,gross_amount,"
|
| 715 |
+
"discount_taken,withholding,net_amount,disposition,reason_code,reason,priority_rank)"
|
| 716 |
+
" VALUES(?,?,?,?,?,?,?,?,?,'proposed',NULL,NULL,?)",
|
| 717 |
+
(rid, i, e["invoice"], e["vendor"], e["due_date"], e["gross_amount"],
|
| 718 |
+
e["discount_taken"], e["withholding"], e["net_amount"], i))
|
| 719 |
+
_audit(cx, "PaymentRun", rid, "propose", after={"eligible_net": net, "cash_available": cash})
|
| 720 |
+
cx.commit()
|
| 721 |
+
shortfall = round(net - cash, 2)
|
| 722 |
+
preview = {"run_id": rid, "eligible": len(elig), "eligible_net": net, "cash_available": cash}
|
| 723 |
+
return {"run_id": rid, "pay_date": pay_date, "bank_account": bank, "cash_available": cash,
|
| 724 |
+
"eligible_count": len(elig), "eligible_net": net,
|
| 725 |
+
"shortfall": shortfall if shortfall > 0 else 0.0,
|
| 726 |
+
"fully_fundable": shortfall <= 0,
|
| 727 |
+
"note": ("Eligible obligations exceed available cash. Commit by naming which invoices go "
|
| 728 |
+
"unpaid and why — every eligible invoice must appear in exactly one of paid or "
|
| 729 |
+
"rejected." if shortfall > 0 else "Available cash covers every eligible obligation."),
|
| 730 |
+
"reason_codes": sorted(REJECT_CODES),
|
| 731 |
+
"obligations": elig,
|
| 732 |
+
"confirm_token": _mint_token(cx, "ContosoPaymentRunCommit", rid, preview),
|
| 733 |
+
"effect_preview": preview}
|
| 734 |
+
|
| 735 |
+
def _payment_run_commit(cx, p):
|
| 736 |
+
rid = p.get("run_id")
|
| 737 |
+
if not rid: return {"error": "parameter run_id is required"}
|
| 738 |
+
run = cx.execute("SELECT * FROM erp_payment_runs WHERE run_id=?", (rid,)).fetchone()
|
| 739 |
+
if not run: return {"error": f"no payment run '{rid}'"}
|
| 740 |
+
if run["state"] != "proposed": return {"error": f"run {rid} is already {run['state']}"}
|
| 741 |
+
if not p.get("confirm_token"):
|
| 742 |
+
return {"error": "confirm_token is required: call ContosoPaymentRunPropose first and pass the "
|
| 743 |
+
"confirm_token it returns. ContosoPaymentRunCommit will not run unconfirmed."}
|
| 744 |
+
lines = {r["invoice"]: dict(r) for r in
|
| 745 |
+
cx.execute("SELECT * FROM erp_payment_run_lines WHERE run_id=?", (rid,))}
|
| 746 |
+
paid = [str(x) for x in (p.get("paid") or [])]
|
| 747 |
+
rejected = p.get("rejected") or []
|
| 748 |
+
if not isinstance(rejected, list) or any(not isinstance(x, dict) for x in rejected):
|
| 749 |
+
return {"error": "parameter rejected must be a list of {invoice, reason_code, reason}"}
|
| 750 |
+
rej_map = {str(x.get("invoice")): x for x in rejected}
|
| 751 |
+
# M2: the partition must be total and disjoint — a short run is committed by naming the
|
| 752 |
+
# unpaid set, never by silently dropping obligations.
|
| 753 |
+
both = sorted(set(paid) & set(rej_map))
|
| 754 |
+
unknown = sorted((set(paid) | set(rej_map)) - set(lines))
|
| 755 |
+
missing = sorted(set(lines) - set(paid) - set(rej_map))
|
| 756 |
+
if unknown: return {"error": f"not eligible obligations in run {rid}: {unknown}"}
|
| 757 |
+
if both: return {"error": f"invoices appear in both paid and rejected: {both}"}
|
| 758 |
+
if missing:
|
| 759 |
+
return {"error": f"validation: every eligible obligation must be either paid or rejected with a "
|
| 760 |
+
f"reason. Unaccounted for: {missing}"}
|
| 761 |
+
for inv, x in rej_map.items():
|
| 762 |
+
if x.get("reason_code") not in REJECT_CODES:
|
| 763 |
+
return {"error": f"invoice {inv}: reason_code must be one of {sorted(REJECT_CODES)}"}
|
| 764 |
+
if not (x.get("reason") or "").strip():
|
| 765 |
+
return {"error": f"invoice {inv}: a rejection requires a reason"}
|
| 766 |
+
# M4: totals are re-derived from the subledger, never from anything the agent typed.
|
| 767 |
+
total_paid = round(sum(lines[i]["net_amount"] for i in paid), 2)
|
| 768 |
+
total_rej = round(sum(lines[i]["net_amount"] for i in rej_map), 2)
|
| 769 |
+
if total_paid > run["cash_available"] + 0.005:
|
| 770 |
+
return {"error": f"validation: the paid set nets {total_paid:.2f} but only "
|
| 771 |
+
f"{run['cash_available']:.2f} is available on {run['bank_account']}"}
|
| 772 |
+
bad = _consume_token(cx, "ContosoPaymentRunCommit", rid, p.get("confirm_token"))
|
| 773 |
+
if bad: return bad
|
| 774 |
+
for inv in paid:
|
| 775 |
+
cx.execute("UPDATE erp_payment_run_lines SET disposition='paid' WHERE run_id=? AND invoice=?", (rid, inv))
|
| 776 |
+
for inv, x in rej_map.items():
|
| 777 |
+
cx.execute("UPDATE erp_payment_run_lines SET disposition='rejected', reason_code=?, reason=? "
|
| 778 |
+
"WHERE run_id=? AND invoice=?", (x["reason_code"], x["reason"], rid, inv))
|
| 779 |
+
cx.execute("UPDATE erp_payment_runs SET state='committed', total_paid=?, total_rejected=?, "
|
| 780 |
+
"committed_at=?, approved_by=? WHERE run_id=?",
|
| 781 |
+
(total_paid, total_rej, S.now, _role(), rid))
|
| 782 |
+
_audit(cx, "PaymentRun", rid, "commit", after={"total_paid": total_paid, "total_rejected": total_rej})
|
| 783 |
+
cx.commit()
|
| 784 |
+
return {"committed": True, "run_id": rid, "paid_count": len(paid), "total_paid": total_paid,
|
| 785 |
+
"rejected_count": len(rej_map), "total_rejected": total_rej,
|
| 786 |
+
"cash_available": run["cash_available"],
|
| 787 |
+
"cash_remaining": round(run["cash_available"] - total_paid, 2)}
|
| 788 |
+
|
| 789 |
+
@S.tool("api_find_actions", "Finds actions (ICustomAPI AI tools) you can invoke.",
|
| 790 |
+
{"query": {"type": "string"}})
|
| 791 |
+
def api_find_actions(query=None):
|
| 792 |
+
q = (query or "").lower()
|
| 793 |
+
# Like the real server: only actions the current role can invoke are returned.
|
| 794 |
+
visible = {n: m for n, m in ACTIONS.items()
|
| 795 |
+
if not m.get("requires_role") or m["requires_role"] == _role()}
|
| 796 |
+
return {"actions": [{"name": n, **{k: v for k, v in meta.items() if k != "requires_role"}}
|
| 797 |
+
for n, meta in visible.items()
|
| 798 |
+
if not q or q in n.lower() or q in meta["description"].lower()],
|
| 799 |
+
"role": ROLE_NAME}
|
| 800 |
+
|
| 801 |
+
@S.tool("api_invoke_action", "Invokes an action by name with parameters.",
|
| 802 |
+
{"action": {"type": "string"}, "parameters": {"type": "object"}}, ["action"])
|
| 803 |
+
def api_invoke_action(action, parameters=None):
|
| 804 |
+
p = parameters or {}
|
| 805 |
+
cx = S.db()
|
| 806 |
+
need = ACTIONS.get(action, {}).get("requires_role")
|
| 807 |
+
if need and _role() != need:
|
| 808 |
+
return _deny(f"invoke action '{action}' (requires the {need.title()} role)", "AI tool actions")
|
| 809 |
+
if action == "ContosoIssueCollectionLetter":
|
| 810 |
+
if not p.get("customer_account"): return {"error": "parameter customer_account is required"}
|
| 811 |
+
return _issue_collection_letter(cx, p["customer_account"])
|
| 812 |
+
if action == "ContosoSetCreditHold":
|
| 813 |
+
if not p.get("customer_account"): return {"error": "parameter customer_account is required"}
|
| 814 |
+
return _set_credit_hold(cx, p["customer_account"], p.get("on_hold"), p.get("reason"))
|
| 815 |
+
if action == "ContosoCustAgedBalancesLive":
|
| 816 |
+
return get_customer_aged_balances(**{k: p[k] for k in ("as_of", "customer_account", "customer_group") if k in p})
|
| 817 |
+
if action == "ContosoCashDiscountForecast":
|
| 818 |
+
as_of = p.get("as_of") or S.today
|
| 819 |
+
where, args = ["t.txn_type='Invoice'", "t.closed=0", "t.cash_disc_code IS NOT NULL"], []
|
| 820 |
+
if p.get("vendor_account"): where.append("t.account=?"); args.append(p["vendor_account"])
|
| 821 |
+
rows = []
|
| 822 |
+
for r in cx.execute(f"""SELECT t.account, t.invoice, t.trans_date, t.amount - t.settled AS open,
|
| 823 |
+
d.percent, d.days FROM erp_vend_trans t
|
| 824 |
+
JOIN erp_cash_disc d ON d.code = t.cash_disc_code
|
| 825 |
+
WHERE {' AND '.join(where)}""", args):
|
| 826 |
+
deadline = (dt.date.fromisoformat(r["trans_date"]) + dt.timedelta(days=r["days"])).isoformat()
|
| 827 |
+
if as_of <= deadline:
|
| 828 |
+
rows.append({"vendor": r["account"], "invoice": r["invoice"], "invoice_date": r["trans_date"],
|
| 829 |
+
"discount_deadline": deadline, "open_amount": round(r["open"], 2),
|
| 830 |
+
"discount_pct": r["percent"], "capturable": round(r["open"] * r["percent"] / 100, 2)})
|
| 831 |
+
return {"as_of": as_of, "qualifying": rows, "total_capturable": round(sum(x["capturable"] for x in rows), 2)}
|
| 832 |
+
if action == "ContosoCollectionStatus":
|
| 833 |
+
acct = p.get("customer_account")
|
| 834 |
+
if not acct: return {"error": "parameter customer_account is required"}
|
| 835 |
+
letters = [dict(r) for r in cx.execute("SELECT letter_code, letter_date, status, fee FROM erp_collection_letters WHERE account=? ORDER BY letter_date", (acct,))]
|
| 836 |
+
open_bal = cx.execute("SELECT ROUND(COALESCE(SUM(amount-settled),0),2) FROM erp_cust_trans WHERE account=? AND txn_type='Invoice' AND closed=0", (acct,)).fetchone()[0]
|
| 837 |
+
return {"customer_account": acct, "highest_letter": max((l["letter_code"] for l in letters), default=None),
|
| 838 |
+
"letters": letters, "open_balance": open_bal}
|
| 839 |
+
if action == "ContosoJournalPropose":
|
| 840 |
+
return _journal_propose(cx, p)
|
| 841 |
+
if action == "ContosoJournalPost":
|
| 842 |
+
return _journal_post(cx, p)
|
| 843 |
+
if action == "ContosoApprovalList":
|
| 844 |
+
where, args = [], []
|
| 845 |
+
if p.get("status"): where.append("status=?"); args.append(p["status"])
|
| 846 |
+
if p.get("doc_type"): where.append("doc_type=?"); args.append(p["doc_type"])
|
| 847 |
+
sql = "SELECT * FROM erp_approval_requests" + (" WHERE " + " AND ".join(where) if where else "") + " ORDER BY submitted_at"
|
| 848 |
+
return {"requests": [dict(r) for r in cx.execute(sql, args)]}
|
| 849 |
+
if action == "ContosoApprovalDecide":
|
| 850 |
+
return _approval_decide(cx, p)
|
| 851 |
+
if action == "ContosoPaymentRunPropose":
|
| 852 |
+
return _payment_run_propose(cx, p)
|
| 853 |
+
if action == "ContosoPaymentRunCommit":
|
| 854 |
+
return _payment_run_commit(cx, p)
|
| 855 |
+
return {"error": f"no action '{action}'", "hint": "use api_find_actions", "available": sorted(ACTIONS)}
|
| 856 |
+
|
| 857 |
+
# ==================== internal: live aged balances ==========================
|
| 858 |
+
# Not a public tool — the real D365 MCP has no such tool. Reachable the real ways:
|
| 859 |
+
# the CustAgedBalances form (form tools) and api_invoke_action(ContosoCustAgedBalancesLive).
|
| 860 |
+
|
| 861 |
+
def get_customer_aged_balances(as_of=None, customer_account=None, customer_group=None, page=1):
|
| 862 |
+
as_of = as_of or S.today
|
| 863 |
+
cx = S.db()
|
| 864 |
+
where, args = ["t.txn_type='Invoice'", "t.closed=0"], []
|
| 865 |
+
if customer_account: where.append("t.account=?"); args.append(customer_account)
|
| 866 |
+
if customer_group: where.append("c.customer_group=?"); args.append(customer_group)
|
| 867 |
+
agg = {}
|
| 868 |
+
for r in cx.execute(f"""SELECT t.account, c.name, t.due_date, t.amount-t.settled AS open
|
| 869 |
+
FROM erp_cust_trans t JOIN erp_customers c ON c.account=t.account
|
| 870 |
+
WHERE {' AND '.join(where)}""", args):
|
| 871 |
+
days = (dt.date.fromisoformat(as_of) - dt.date.fromisoformat(r["due_date"])).days
|
| 872 |
+
b = agg.setdefault(r["account"], {"account": r["account"], "name": r["name"],
|
| 873 |
+
"not_due": 0, "b1_30": 0, "b31_60": 0, "b61_90": 0, "b90_plus": 0})
|
| 874 |
+
key = "not_due" if days <= 0 else "b1_30" if days <= 30 else "b31_60" if days <= 60 else "b61_90" if days <= 90 else "b90_plus"
|
| 875 |
+
b[key] = round(b[key] + r["open"], 2)
|
| 876 |
+
out = sorted(agg.values(), key=lambda b: -(b["b1_30"] + b["b31_60"] + b["b61_90"] + b["b90_plus"]))
|
| 877 |
+
for b in out:
|
| 878 |
+
b["past_due_total"] = round(b["b1_30"] + b["b31_60"] + b["b61_90"] + b["b90_plus"], 2)
|
| 879 |
+
b["total_open"] = round(b["past_due_total"] + b["not_due"], 2)
|
| 880 |
+
page = max(1, int(page or 1))
|
| 881 |
+
return {"as_of": as_of, "rows": out[(page-1)*25: page*25], "page": page,
|
| 882 |
+
"total_rows": len(out), "has_more": page*25 < len(out),
|
| 883 |
+
"note": "live computation; the batch AgedBalancesSnapshot entity may differ"}
|
| 884 |
+
|
| 885 |
+
if __name__ == "__main__":
|
| 886 |
+
S.run()
|
world/mcp/servers/filings_server.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Filings MCP server — 1:1 SEC EDGAR data-API response shapes over frozen snapshots.
|
| 3 |
+
|
| 4 |
+
Endpoint mapping (values are real XBRL facts captured from data.sec.gov, frozen):
|
| 5 |
+
lookup_company ≈ company_tickers.json (cik_str / ticker / title)
|
| 6 |
+
get_company_concept ≈ api/xbrl/companyconcept (units.USD[].{end,val,accn,fy,fp,form,filed})
|
| 7 |
+
get_company_facts ≈ api/xbrl/companyfacts (facts["us-gaap"][tag].units)
|
| 8 |
+
get_xbrl_frames ≈ api/xbrl/frames (ccp "CY2024Q4I", data[].{cik,entityName,end,val})
|
| 9 |
+
get_submissions ≈ data.sec.gov/submissions (filings.recent columnar arrays)
|
| 10 |
+
full_text_search ≈ efts.sec.gov/LATEST/search-index (hits.hits[]._source)
|
| 11 |
+
list_available_concepts — snapshot index helper (no EDGAR equivalent; discovery aid).
|
| 12 |
+
Read-only. Rate-limit/User-Agent friction not reproduced (documented escalation lever)."""
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 16 |
+
from framework import Server
|
| 17 |
+
|
| 18 |
+
S = Server("filings", "Public-company filings & XBRL facts (frozen EDGAR snapshot, real API shapes).")
|
| 19 |
+
|
| 20 |
+
def _fact(r):
|
| 21 |
+
return {"end": r["period_end"], "val": r["value"], "accn": r["accession"],
|
| 22 |
+
"fy": int(r["fy"]), "fp": r["fp"], "form": r["form"], "filed": r["filed"]}
|
| 23 |
+
|
| 24 |
+
@S.tool("lookup_company", "Resolve a company name or ticker to CIK (company_tickers.json shape).",
|
| 25 |
+
{"query": {"type": "string"}}, ["query"])
|
| 26 |
+
def lookup_company(query):
|
| 27 |
+
cx = S.db(); like = f"%{query.lower()}%"
|
| 28 |
+
rows = cx.execute("SELECT * FROM filings_companies WHERE LOWER(name) LIKE ? OR LOWER(ticker) LIKE ?",
|
| 29 |
+
(like, like)).fetchall()
|
| 30 |
+
return {"matches": [{"cik_str": int(r["cik"]), "ticker": r["ticker"], "title": r["name"]} for r in rows]}
|
| 31 |
+
|
| 32 |
+
@S.tool("list_available_concepts", "Snapshot index helper: XBRL concepts available for a company (no EDGAR equivalent).",
|
| 33 |
+
{"ticker": {"type": "string"}}, ["ticker"])
|
| 34 |
+
def list_available_concepts(ticker):
|
| 35 |
+
cx = S.db()
|
| 36 |
+
rows = cx.execute("""SELECT DISTINCT f.concept, f.unit FROM filings_facts f
|
| 37 |
+
JOIN filings_companies c ON c.cik=f.cik WHERE LOWER(c.ticker)=?""",
|
| 38 |
+
(ticker.lower(),)).fetchall()
|
| 39 |
+
return {"ticker": ticker.upper(), "concepts": [dict(r) for r in rows]}
|
| 40 |
+
|
| 41 |
+
@S.tool("get_company_concept", "All facts for one us-gaap concept (api/xbrl/companyconcept shape).",
|
| 42 |
+
{"ticker": {"type": "string"}, "concept": {"type": "string", "description": "e.g. AssetsCurrent"}},
|
| 43 |
+
["ticker", "concept"])
|
| 44 |
+
def get_company_concept(ticker, concept):
|
| 45 |
+
cx = S.db()
|
| 46 |
+
c = cx.execute("SELECT * FROM filings_companies WHERE LOWER(ticker)=?", (ticker.lower(),)).fetchone()
|
| 47 |
+
if not c: return {"error": "unknown ticker in snapshot", "hint": "use lookup_company"}
|
| 48 |
+
rows = cx.execute("SELECT * FROM filings_facts WHERE cik=? AND LOWER(concept)=? ORDER BY period_end",
|
| 49 |
+
(c["cik"], concept.lower())).fetchall()
|
| 50 |
+
if not rows:
|
| 51 |
+
return {"error": "concept not in snapshot for this company", "hint": "use list_available_concepts"}
|
| 52 |
+
units = {}
|
| 53 |
+
for r in rows: units.setdefault(r["unit"], []).append(_fact(r))
|
| 54 |
+
return {"cik": int(c["cik"]), "taxonomy": "us-gaap", "tag": rows[0]["concept"],
|
| 55 |
+
"label": rows[0]["concept"], "description": "", "entityName": c["name"], "units": units}
|
| 56 |
+
|
| 57 |
+
@S.tool("get_company_facts", "ALL facts for a company across concepts (api/xbrl/companyfacts shape; large payload like the real endpoint).",
|
| 58 |
+
{"ticker": {"type": "string"}}, ["ticker"])
|
| 59 |
+
def get_company_facts(ticker):
|
| 60 |
+
cx = S.db()
|
| 61 |
+
c = cx.execute("SELECT * FROM filings_companies WHERE LOWER(ticker)=?", (ticker.lower(),)).fetchone()
|
| 62 |
+
if not c: return {"error": "unknown ticker in snapshot", "hint": "use lookup_company"}
|
| 63 |
+
gaap = {}
|
| 64 |
+
for r in cx.execute("SELECT * FROM filings_facts WHERE cik=? ORDER BY concept, period_end", (c["cik"],)):
|
| 65 |
+
tag = gaap.setdefault(r["concept"], {"label": r["concept"], "description": "", "units": {}})
|
| 66 |
+
tag["units"].setdefault(r["unit"], []).append(_fact(r))
|
| 67 |
+
return {"cik": int(c["cik"]), "entityName": c["name"], "facts": {"us-gaap": gaap}}
|
| 68 |
+
|
| 69 |
+
@S.tool("get_xbrl_frames", "One concept, one annual period, across all companies in the snapshot (api/xbrl/frames shape).",
|
| 70 |
+
{"concept": {"type": "string"}, "unit": {"type": "string"}, "fy": {"type": "string", "description": "e.g. 2024"}},
|
| 71 |
+
["concept", "fy"])
|
| 72 |
+
def get_xbrl_frames(concept, fy, unit="USD"):
|
| 73 |
+
cx = S.db()
|
| 74 |
+
rows = cx.execute("""SELECT c.ticker, c.name, f.* FROM filings_facts f
|
| 75 |
+
JOIN filings_companies c ON c.cik=f.cik
|
| 76 |
+
WHERE LOWER(f.concept)=? AND f.unit=? AND f.fy=? ORDER BY c.ticker""",
|
| 77 |
+
(concept.lower(), unit, str(fy))).fetchall()
|
| 78 |
+
if not rows: return {"error": "no facts for that concept/period in snapshot",
|
| 79 |
+
"hint": "list_available_concepts per ticker"}
|
| 80 |
+
return {"taxonomy": "us-gaap", "tag": rows[0]["concept"], "ccp": f"CY{fy}Q4I", "uom": unit,
|
| 81 |
+
"pts": len(rows),
|
| 82 |
+
"data": [{"accn": r["accession"], "cik": int(r["cik"]), "entityName": r["name"],
|
| 83 |
+
"end": r["period_end"], "val": r["value"]} for r in rows]}
|
| 84 |
+
|
| 85 |
+
@S.tool("get_submissions", "Company filing history (data.sec.gov/submissions shape: filings.recent columnar arrays).",
|
| 86 |
+
{"ticker": {"type": "string"}}, ["ticker"])
|
| 87 |
+
def get_submissions(ticker):
|
| 88 |
+
cx = S.db()
|
| 89 |
+
c = cx.execute("SELECT * FROM filings_companies WHERE LOWER(ticker)=?", (ticker.lower(),)).fetchone()
|
| 90 |
+
if not c: return {"error": "unknown ticker in snapshot", "hint": "use lookup_company"}
|
| 91 |
+
rows = cx.execute("SELECT * FROM filings_documents WHERE cik=? ORDER BY filed DESC", (c["cik"],)).fetchall()
|
| 92 |
+
return {"cik": c["cik"], "name": c["name"], "tickers": [c["ticker"]],
|
| 93 |
+
"filings": {"recent": {
|
| 94 |
+
"accessionNumber": [r["accession"] for r in rows],
|
| 95 |
+
"filingDate": [r["filed"] for r in rows],
|
| 96 |
+
"form": [r["form"] for r in rows],
|
| 97 |
+
"primaryDocDescription": [r["title"] for r in rows]}}}
|
| 98 |
+
|
| 99 |
+
@S.tool("full_text_search", "Full-text search across filing documents (efts.sec.gov search shape).",
|
| 100 |
+
{"q": {"type": "string"}}, ["q"])
|
| 101 |
+
def full_text_search(q):
|
| 102 |
+
cx = S.db(); like = f"%{q.lower()}%"
|
| 103 |
+
rows = cx.execute("""SELECT c.ticker, c.cik, c.name, d.form, d.filed, d.accession, d.title, d.excerpt
|
| 104 |
+
FROM filings_documents d JOIN filings_companies c ON c.cik=d.cik
|
| 105 |
+
WHERE LOWER(d.title) LIKE ? OR LOWER(d.excerpt) LIKE ?""", (like, like)).fetchall()
|
| 106 |
+
return {"hits": {"total": {"value": len(rows)},
|
| 107 |
+
"hits": [{"_id": f"{r['accession']}", "_source": {
|
| 108 |
+
"ciks": [r["cik"]], "display_names": [f"{r['name']} ({r['ticker']})"],
|
| 109 |
+
"file_type": r["form"], "file_date": r["filed"],
|
| 110 |
+
"file_description": r["title"], "excerpt": r["excerpt"]}} for r in rows]}}
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
S.run()
|
world/mcp/servers/harness_server.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Harness MCP server — answer submission only. The answers table IS the graded state.
|
| 3 |
+
Verification/reset live in the runner, deliberately off the agent's surface."""
|
| 4 |
+
import sys, json, datetime as dt
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 7 |
+
from framework import Server
|
| 8 |
+
|
| 9 |
+
S = Server("harness", "File your findings here. What you file is what gets graded. "
|
| 10 |
+
"Call reporting_fields first to see what this piece of work requires.")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _schema():
|
| 14 |
+
cx = S.db()
|
| 15 |
+
try:
|
| 16 |
+
rows = cx.execute("SELECT ordinal, field, type, description FROM answer_schema "
|
| 17 |
+
"ORDER BY ordinal, field").fetchall()
|
| 18 |
+
except Exception:
|
| 19 |
+
return []
|
| 20 |
+
return [{"field": r["field"], "type": r["type"], "description": r["description"] or ""}
|
| 21 |
+
for r in rows]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@S.tool("reporting_fields",
|
| 25 |
+
"The fields this piece of work must be filed under, with their expected types. "
|
| 26 |
+
"The request itself will not list them — read them here, the way you would read any "
|
| 27 |
+
"reporting system's schema before filing into it.")
|
| 28 |
+
def reporting_fields():
|
| 29 |
+
fields = _schema()
|
| 30 |
+
if not fields:
|
| 31 |
+
return {"fields": [], "note": "no schema registered; submit the figures the request asks for"}
|
| 32 |
+
return {"fields": fields, "count": len(fields),
|
| 33 |
+
"note": "file every field with submit_answer; use the literal string \"none\" "
|
| 34 |
+
"where the answer is that the thing does not exist"}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@S.tool("submit_answer",
|
| 38 |
+
"File your findings as an object, e.g. {\"outstanding_balance\": 12345.67, "
|
| 39 |
+
"\"currency\": \"USD\"}. Call reporting_fields to see which fields are required. "
|
| 40 |
+
"Resubmitting a field overwrites it. Use the literal string \"none\" where the answer "
|
| 41 |
+
"is that the thing does not exist.",
|
| 42 |
+
{"answers": {"type": "object", "description": "field -> value map"}}, ["answers"])
|
| 43 |
+
def submit_answer(answers):
|
| 44 |
+
if not isinstance(answers, dict) or not answers:
|
| 45 |
+
raise ValueError("answers must be a non-empty object")
|
| 46 |
+
# Tell the agent what it still owes, and what it filed that nothing asked for. This is
|
| 47 |
+
# feedback on the CONTRACT, never on correctness — the value is not inspected here.
|
| 48 |
+
want = {f["field"] for f in _schema()}
|
| 49 |
+
unknown = sorted(set(answers) - want) if want else []
|
| 50 |
+
cx = S.db()
|
| 51 |
+
now = dt.datetime.now(dt.timezone.utc).isoformat()
|
| 52 |
+
for field, value in answers.items():
|
| 53 |
+
cx.execute("INSERT INTO answers(field, value, submitted_at) VALUES(?,?,?) "
|
| 54 |
+
"ON CONFLICT(field) DO UPDATE SET value=excluded.value, submitted_at=excluded.submitted_at",
|
| 55 |
+
(str(field), json.dumps(value, default=str), now))
|
| 56 |
+
cx.commit()
|
| 57 |
+
filed = {r["field"] for r in cx.execute("SELECT field FROM answers")}
|
| 58 |
+
out = {"recorded_fields": sorted(answers.keys())}
|
| 59 |
+
if want:
|
| 60 |
+
out["still_outstanding"] = sorted(want - filed)
|
| 61 |
+
if unknown:
|
| 62 |
+
out["not_requested"] = unknown
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
@S.tool("list_submitted", "See what you have submitted so far.")
|
| 66 |
+
def list_submitted():
|
| 67 |
+
cx = S.db()
|
| 68 |
+
return {"submitted": {r["field"]: json.loads(r["value"]) for r in cx.execute("SELECT * FROM answers")}}
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
S.run()
|
world/mcp/servers/odoo_server.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Odoo MCP server — procure-to-pay and make-or-buy, shaped after Odoo 19's ORM RPC.
|
| 3 |
+
|
| 4 |
+
This is the surface agentic-labs/erp-bench drives. Its 300 tasks each boot a real Odoo in
|
| 5 |
+
Docker and grade it with `odoolib` against the live server; that plumbing does not port, but
|
| 6 |
+
the surface does, because the tasks only ever touch a handful of models through the standard
|
| 7 |
+
`execute_kw` verbs.
|
| 8 |
+
|
| 9 |
+
Shaped from the checkout, not from docs (`research/external/repos/odoo`, wave 4):
|
| 10 |
+
* `odoo/service/model.py` — the real `execute_kw` dispatcher, so the verb set here is
|
| 11 |
+
search_read / create / write / fields_get rather than something invented.
|
| 12 |
+
* `odoo/osv/expression.py` — the domain grammar: a list of `[field, operator, value]` leaves
|
| 13 |
+
with implicit AND, and the operator vocabulary below is its documented set.
|
| 14 |
+
|
| 15 |
+
Deliberate fidelity choices, each of which a task depends on:
|
| 16 |
+
* `min_qty`/`max_qty` on a vendor offer are HORIZON-WIDE totals, not per-line minimums —
|
| 17 |
+
consolidating an offer into one PO is a rule several patterns test.
|
| 18 |
+
* `comment` ("Internal Notes" in the UI) is a real field and is sometimes the ONLY place a
|
| 19 |
+
binding constraint lives, so it is returned like any other field and never summarised away.
|
| 20 |
+
* A draft order is not a commitment: `state` starts `draft` and only `action_confirm` moves
|
| 21 |
+
it to `sale`/`purchase`. Tasks grade confirmed orders.
|
| 22 |
+
|
| 23 |
+
All state is SQLite (WORLD_DB). SIMULATION ONLY.
|
| 24 |
+
"""
|
| 25 |
+
import sys, json, datetime as dt
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 28 |
+
from framework import Server, PAGE
|
| 29 |
+
|
| 30 |
+
S = Server("odoo", "Odoo 19 ERP — procurement, sales and manufacturing. SIMULATION ONLY.")
|
| 31 |
+
|
| 32 |
+
# model -> (table, primary key, writable?)
|
| 33 |
+
MODELS = {
|
| 34 |
+
"res.partner": ("erpb_partners", "ref", False),
|
| 35 |
+
"product.product": ("erpb_products", "code", False),
|
| 36 |
+
"product.supplierinfo": ("erpb_vendor_offers", "id", False),
|
| 37 |
+
"mrp.bom": ("erpb_boms", "id", False),
|
| 38 |
+
"mrp.bom.line": ("erpb_bom_components", "bom_id", False),
|
| 39 |
+
"mrp.workcenter": ("erpb_workcenters", "code", False),
|
| 40 |
+
"stock.quant": ("erpb_stock", "product_code", False),
|
| 41 |
+
"sale.order": ("erpb_sale_orders", "name", True),
|
| 42 |
+
"sale.order.line": ("erpb_sale_order_lines", "id", True),
|
| 43 |
+
"purchase.order": ("erpb_purchase_orders", "name", True),
|
| 44 |
+
"purchase.order.line": ("erpb_purchase_order_lines", "id", True),
|
| 45 |
+
"mrp.production": ("erpb_manufacturing_orders", "name", True),
|
| 46 |
+
}
|
| 47 |
+
SEQ = {"sale.order": ("S%05d", "erpb_sale_orders"),
|
| 48 |
+
"purchase.order": ("P%05d", "erpb_purchase_orders"),
|
| 49 |
+
"mrp.production": ("MO%05d", "erpb_manufacturing_orders")}
|
| 50 |
+
|
| 51 |
+
OPS = {"=": "=", "!=": "!=", ">": ">", ">=": ">=", "<": "<", "<=": "<=",
|
| 52 |
+
"like": "LIKE", "ilike": "LIKE", "in": "IN", "not in": "NOT IN"}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _cols(cx, table):
|
| 56 |
+
return [r[1] for r in cx.execute(f"PRAGMA table_info({table})")]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _where(domain, cols):
|
| 60 |
+
"""Odoo domain -> SQL. Implicit AND between leaves (expression.py's default)."""
|
| 61 |
+
if not domain: return "", []
|
| 62 |
+
sql, args = [], []
|
| 63 |
+
for leaf in domain:
|
| 64 |
+
if not isinstance(leaf, (list, tuple)) or len(leaf) != 3:
|
| 65 |
+
raise ValueError(f"malformed domain leaf {leaf!r}; expected [field, operator, value]")
|
| 66 |
+
f, op, v = leaf
|
| 67 |
+
if f not in cols:
|
| 68 |
+
raise ValueError(f"unknown field {f!r}; known: {', '.join(sorted(cols))}")
|
| 69 |
+
if op not in OPS:
|
| 70 |
+
raise ValueError(f"unsupported operator {op!r}; supported: {', '.join(sorted(OPS))}")
|
| 71 |
+
if op in ("in", "not in"):
|
| 72 |
+
vals = list(v) if isinstance(v, (list, tuple)) else [v]
|
| 73 |
+
sql.append(f"{f} {OPS[op]} ({','.join('?' * len(vals))})"); args += vals
|
| 74 |
+
elif op in ("like", "ilike"):
|
| 75 |
+
sql.append(f"{f} LIKE ?"); args.append(f"%{v}%")
|
| 76 |
+
else:
|
| 77 |
+
sql.append(f"{f} {OPS[op]} ?"); args.append(v)
|
| 78 |
+
return " WHERE " + " AND ".join(sql), args
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _model(model):
|
| 82 |
+
if model not in MODELS:
|
| 83 |
+
raise ValueError(f"unknown model {model!r}; served: {', '.join(sorted(MODELS))}")
|
| 84 |
+
return MODELS[model]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@S.tool("fields_get", "List the fields of a model, with type. Discovery step before search_read.",
|
| 88 |
+
{"model": {"type": "string"}}, ["model"])
|
| 89 |
+
def fields_get(model):
|
| 90 |
+
table, pk, writable = _model(model)
|
| 91 |
+
with S.db() as cx:
|
| 92 |
+
info = [{"name": r[1], "type": r[2] or "text"} for r in cx.execute(f"PRAGMA table_info({table})")]
|
| 93 |
+
return {"model": model, "primary_key": pk, "writable": writable, "fields": info}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@S.tool("search_read",
|
| 97 |
+
"Search and read records. `domain` is a list of [field, operator, value] leaves "
|
| 98 |
+
"combined with AND, e.g. [[\"product_code\",\"=\",\"P123\"],[\"price\",\"<\",100]].",
|
| 99 |
+
{"model": {"type": "string"},
|
| 100 |
+
"domain": {"type": "array", "description": "list of [field, operator, value]"},
|
| 101 |
+
"fields": {"type": "array", "description": "field names; omit for all"},
|
| 102 |
+
"page": {"type": "integer"}},
|
| 103 |
+
["model"])
|
| 104 |
+
def search_read(model, domain=None, fields=None, page=1):
|
| 105 |
+
table, pk, _w = _model(model)
|
| 106 |
+
with S.db() as cx:
|
| 107 |
+
cols = _cols(cx, table)
|
| 108 |
+
sel = "*"
|
| 109 |
+
if fields:
|
| 110 |
+
bad = [f for f in fields if f not in cols]
|
| 111 |
+
if bad: raise ValueError(f"unknown field(s) {bad}; known: {', '.join(sorted(cols))}")
|
| 112 |
+
sel = ", ".join(fields)
|
| 113 |
+
w, args = _where(domain, cols)
|
| 114 |
+
return S.rows(cx, f"SELECT {sel} FROM {table}{w}", args, page)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@S.tool("create", "Create a record. Returns its name/id. Orders are created in state 'draft' — "
|
| 118 |
+
"confirm them with action_confirm.",
|
| 119 |
+
{"model": {"type": "string"}, "values": {"type": "object"}},
|
| 120 |
+
["model", "values"])
|
| 121 |
+
def create(model, values):
|
| 122 |
+
table, pk, writable = _model(model)
|
| 123 |
+
if not writable:
|
| 124 |
+
raise ValueError(f"{model} is master data in this world and is read-only; "
|
| 125 |
+
f"writable models: {', '.join(m for m, v in MODELS.items() if v[2])}")
|
| 126 |
+
vals = dict(values or {})
|
| 127 |
+
with S.db() as cx:
|
| 128 |
+
cols = _cols(cx, table)
|
| 129 |
+
bad = [k for k in vals if k not in cols]
|
| 130 |
+
if bad: raise ValueError(f"unknown field(s) {bad} on {model}; known: {', '.join(sorted(cols))}")
|
| 131 |
+
if model in SEQ and not vals.get("name"):
|
| 132 |
+
fmt, tbl = SEQ[model]
|
| 133 |
+
n = cx.execute(f"SELECT COUNT(*) FROM {tbl}").fetchone()[0] + 1
|
| 134 |
+
vals["name"] = fmt % n
|
| 135 |
+
if "state" in cols and not vals.get("state"):
|
| 136 |
+
vals["state"] = "draft"
|
| 137 |
+
keys = list(vals)
|
| 138 |
+
cx.execute(f"INSERT INTO {table} ({','.join(keys)}) VALUES ({','.join('?' * len(keys))})",
|
| 139 |
+
[vals[k] for k in keys])
|
| 140 |
+
cx.commit()
|
| 141 |
+
return {"model": model, "created": vals.get("name") or cx.execute(
|
| 142 |
+
f"SELECT last_insert_rowid()").fetchone()[0], "values": vals}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@S.tool("write", "Update records matching a domain.",
|
| 146 |
+
{"model": {"type": "string"}, "domain": {"type": "array"}, "values": {"type": "object"}},
|
| 147 |
+
["model", "domain", "values"])
|
| 148 |
+
def write(model, domain, values):
|
| 149 |
+
table, pk, writable = _model(model)
|
| 150 |
+
if not writable:
|
| 151 |
+
raise ValueError(f"{model} is master data in this world and is read-only")
|
| 152 |
+
vals = dict(values or {})
|
| 153 |
+
with S.db() as cx:
|
| 154 |
+
cols = _cols(cx, table)
|
| 155 |
+
bad = [k for k in vals if k not in cols]
|
| 156 |
+
if bad: raise ValueError(f"unknown field(s) {bad} on {model}")
|
| 157 |
+
w, args = _where(domain, cols)
|
| 158 |
+
if not w: raise ValueError("refusing to write with an empty domain")
|
| 159 |
+
sets = ", ".join(f"{k}=?" for k in vals)
|
| 160 |
+
cur = cx.execute(f"UPDATE {table} SET {sets}{w}", list(vals.values()) + args)
|
| 161 |
+
cx.commit()
|
| 162 |
+
return {"model": model, "updated": cur.rowcount}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@S.tool("action_confirm", "Confirm draft orders by name — sale.order -> 'sale', "
|
| 166 |
+
"purchase.order -> 'purchase', mrp.production -> 'confirmed'. "
|
| 167 |
+
"A draft order is not a commitment and is not graded as one.",
|
| 168 |
+
{"model": {"type": "string"}, "names": {"type": "array"}},
|
| 169 |
+
["model", "names"])
|
| 170 |
+
def action_confirm(model, names):
|
| 171 |
+
table, pk, writable = _model(model)
|
| 172 |
+
if not writable or model not in SEQ:
|
| 173 |
+
raise ValueError(f"{model} has no confirm action")
|
| 174 |
+
target = {"sale.order": "sale", "purchase.order": "purchase",
|
| 175 |
+
"mrp.production": "confirmed"}[model]
|
| 176 |
+
names = list(names or [])
|
| 177 |
+
if not names: raise ValueError("names is required")
|
| 178 |
+
with S.db() as cx:
|
| 179 |
+
rows = cx.execute(f"SELECT name, state FROM {table} WHERE name IN "
|
| 180 |
+
f"({','.join('?' * len(names))})", names).fetchall()
|
| 181 |
+
found = {r["name"] for r in rows}
|
| 182 |
+
missing = [n for n in names if n not in found]
|
| 183 |
+
if missing: raise ValueError(f"no such {model}: {missing}")
|
| 184 |
+
cx.execute(f"UPDATE {table} SET state=? WHERE name IN "
|
| 185 |
+
f"({','.join('?' * len(names))})", [target] + names)
|
| 186 |
+
cx.commit()
|
| 187 |
+
return {"model": model, "confirmed": names, "state": target}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
S.run()
|
world/mcp/servers/sheets_server.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sheets MCP server — 1:1 Microsoft Graph workbook API shapes over the shared drive.
|
| 3 |
+
|
| 4 |
+
Mirrors Graph /drive + /workbook: list drive items, worksheets collection,
|
| 5 |
+
range(address='A1:C4') returning the Graph workbookRange object (address, values, text,
|
| 6 |
+
formulas, numberFormat, rowCount/columnCount/cellCount), usedRange, and drive search.
|
| 7 |
+
Each shared-drive file is a workbook with one worksheet ("Sheet1"). Read-only
|
| 8 |
+
(Files.Read scope). SIMULATION ONLY."""
|
| 9 |
+
import sys, json, re
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib"))
|
| 12 |
+
from framework import Server
|
| 13 |
+
|
| 14 |
+
S = Server("sheets", "Finance shared drive (Microsoft Graph workbook API shapes). Read-only. SIMULATION ONLY.")
|
| 15 |
+
|
| 16 |
+
def _file(cx, name):
|
| 17 |
+
return cx.execute("SELECT * FROM sheet_files WHERE name=?", (name,)).fetchone()
|
| 18 |
+
|
| 19 |
+
def _grid(cx, name):
|
| 20 |
+
rows = cx.execute("SELECT row_no, cells FROM sheet_rows WHERE file=? ORDER BY row_no", (name,)).fetchall()
|
| 21 |
+
return [json.loads(r["cells"]) for r in rows]
|
| 22 |
+
|
| 23 |
+
def _cell_v(c):
|
| 24 |
+
"""A cell is a literal, or {"f": "=SUM(...)", "v": cached_value} for formula cells.
|
| 25 |
+
Like real Excel, the API serves the CACHED value — it may have drifted from the
|
| 26 |
+
formula's inputs (paste-values / stale-recalc chaos)."""
|
| 27 |
+
return c.get("v", "") if isinstance(c, dict) else c
|
| 28 |
+
|
| 29 |
+
def _cell_f(c):
|
| 30 |
+
return c.get("f", c.get("v", "")) if isinstance(c, dict) else c
|
| 31 |
+
|
| 32 |
+
def _range_obj(grid, r0, c0, r1, c1, sheet="Sheet1"):
|
| 33 |
+
values, formulas = [], []
|
| 34 |
+
for ri in range(r0, r1 + 1):
|
| 35 |
+
row = grid[ri - 1] if 0 < ri <= len(grid) else []
|
| 36 |
+
cells = [(row[ci - 1] if 0 < ci <= len(row) else "") for ci in range(c0, c1 + 1)]
|
| 37 |
+
values.append([_cell_v(c) for c in cells])
|
| 38 |
+
formulas.append([_cell_f(c) for c in cells])
|
| 39 |
+
addr = f"{sheet}!{_col(c0)}{r0}:{_col(c1)}{r1}"
|
| 40 |
+
return {"address": addr, "addressLocal": addr,
|
| 41 |
+
"rowCount": r1 - r0 + 1, "columnCount": c1 - c0 + 1,
|
| 42 |
+
"cellCount": (r1 - r0 + 1) * (c1 - c0 + 1),
|
| 43 |
+
"rowIndex": r0 - 1, "columnIndex": c0 - 1,
|
| 44 |
+
"values": values, "text": [[str(v) for v in row] for row in values],
|
| 45 |
+
"formulas": formulas, "numberFormat": [["General"] * (c1 - c0 + 1) for _ in range(r1 - r0 + 1)],
|
| 46 |
+
"valueTypes": [[("Empty" if v == "" else "Double" if isinstance(v, (int, float)) else "String")
|
| 47 |
+
for v in row] for row in values]}
|
| 48 |
+
|
| 49 |
+
def _col(n):
|
| 50 |
+
s = ""
|
| 51 |
+
while n: n, r = divmod(n - 1, 26); s = chr(65 + r) + s
|
| 52 |
+
return s
|
| 53 |
+
|
| 54 |
+
def _parse_a1(a1):
|
| 55 |
+
m = re.match(r"(?i)^(?:Sheet1!)?([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$", a1.strip())
|
| 56 |
+
if not m: return None
|
| 57 |
+
def num(col):
|
| 58 |
+
v = 0
|
| 59 |
+
for ch in col.upper(): v = v * 26 + ord(ch) - 64
|
| 60 |
+
return v
|
| 61 |
+
c0, r0 = num(m.group(1)), int(m.group(2))
|
| 62 |
+
c1, r1 = (num(m.group(3)), int(m.group(4))) if m.group(3) else (c0, r0)
|
| 63 |
+
return r0, c0, r1, c1
|
| 64 |
+
|
| 65 |
+
@S.tool("list_drive_items", "List workbook files on the finance shared drive (GET /drive/root/children shape).")
|
| 66 |
+
def list_drive_items():
|
| 67 |
+
cx = S.db()
|
| 68 |
+
return {"value": [{"id": r["name"], "name": r["name"],
|
| 69 |
+
"lastModifiedDateTime": r["modified_at"],
|
| 70 |
+
"createdBy": {"user": {"displayName": r["owner"]}},
|
| 71 |
+
"description": r["description"],
|
| 72 |
+
"file": {"mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}}
|
| 73 |
+
for r in cx.execute("SELECT * FROM sheet_files ORDER BY name")]}
|
| 74 |
+
|
| 75 |
+
@S.tool("get_drive_item", "One file's metadata (GET /drive/items/{id} shape) — check lastModifiedDateTime before trusting a tracker.",
|
| 76 |
+
{"item": {"type": "string", "description": "file name/id"}}, ["item"])
|
| 77 |
+
def get_drive_item(item):
|
| 78 |
+
cx = S.db()
|
| 79 |
+
f = _file(cx, item)
|
| 80 |
+
if not f: return {"error": {"code": "itemNotFound", "message": f"The resource could not be found: {item}"}}
|
| 81 |
+
n = cx.execute("SELECT COUNT(*) FROM sheet_rows WHERE file=?", (item,)).fetchone()[0]
|
| 82 |
+
return {"id": f["name"], "name": f["name"], "lastModifiedDateTime": f["modified_at"],
|
| 83 |
+
"createdBy": {"user": {"displayName": f["owner"]}}, "description": f["description"],
|
| 84 |
+
"rowCount": n}
|
| 85 |
+
|
| 86 |
+
@S.tool("workbook_worksheets", "List worksheets of a workbook (GET /workbook/worksheets shape).",
|
| 87 |
+
{"item": {"type": "string"}}, ["item"])
|
| 88 |
+
def workbook_worksheets(item):
|
| 89 |
+
cx = S.db()
|
| 90 |
+
if not _file(cx, item):
|
| 91 |
+
return {"error": {"code": "itemNotFound", "message": f"The resource could not be found: {item}"}}
|
| 92 |
+
return {"value": [{"id": "{00000000-0001-0000-0000-000000000000}", "name": "Sheet1",
|
| 93 |
+
"position": 0, "visibility": "Visible"}]}
|
| 94 |
+
|
| 95 |
+
@S.tool("workbook_range", "Read a range (GET /workbook/worksheets/Sheet1/range(address='A1:C4') shape). Returns the Graph workbookRange object.",
|
| 96 |
+
{"item": {"type": "string"}, "address": {"type": "string", "description": "A1 notation, e.g. A1:F4"}},
|
| 97 |
+
["item", "address"])
|
| 98 |
+
def workbook_range(item, address):
|
| 99 |
+
cx = S.db()
|
| 100 |
+
if not _file(cx, item):
|
| 101 |
+
return {"error": {"code": "itemNotFound", "message": f"The resource could not be found: {item}"}}
|
| 102 |
+
box = _parse_a1(address)
|
| 103 |
+
if not box: return {"error": {"code": "invalidArgument", "message": f"Invalid range address: {address}"}}
|
| 104 |
+
return _range_obj(_grid(cx, item), *box)
|
| 105 |
+
|
| 106 |
+
@S.tool("workbook_used_range", "Read the used range of Sheet1 (GET /workbook/worksheets/Sheet1/usedRange shape).",
|
| 107 |
+
{"item": {"type": "string"}}, ["item"])
|
| 108 |
+
def workbook_used_range(item):
|
| 109 |
+
cx = S.db()
|
| 110 |
+
if not _file(cx, item):
|
| 111 |
+
return {"error": {"code": "itemNotFound", "message": f"The resource could not be found: {item}"}}
|
| 112 |
+
grid = _grid(cx, item)
|
| 113 |
+
if not grid: return {"error": {"code": "itemNotFound", "message": "worksheet is empty"}}
|
| 114 |
+
return _range_obj(grid, 1, 1, len(grid), max(len(r) for r in grid))
|
| 115 |
+
|
| 116 |
+
@S.tool("drive_search", "Search file contents across the drive (GET /drive/root/search(q='...') shape, cell-level hits).",
|
| 117 |
+
{"q": {"type": "string"}}, ["q"])
|
| 118 |
+
def drive_search(q):
|
| 119 |
+
cx = S.db(); like = f"%{q.lower()}%"
|
| 120 |
+
hits = [{"file": r["file"], "row": r["row_no"], "cells": json.loads(r["cells"])}
|
| 121 |
+
for r in cx.execute("SELECT file, row_no, cells FROM sheet_rows WHERE LOWER(cells) LIKE ? LIMIT 50", (like,))]
|
| 122 |
+
return {"value": hits}
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
S.run()
|
world/schema.sql
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- finance-world state schema. One SQLite file per task run; every MCP server sees only its namespace.
|
| 2 |
+
-- Epoch/world clock lives in meta (WORLD_NOW). SIMULATION ONLY.
|
| 3 |
+
|
| 4 |
+
CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT);
|
| 5 |
+
|
| 6 |
+
-- ============ ERP (Dynamics-365-Finance-shaped, legal entity USMF) ============
|
| 7 |
+
CREATE TABLE erp_companies(dataareaid TEXT PRIMARY KEY, name TEXT);
|
| 8 |
+
CREATE TABLE erp_payment_terms(code TEXT PRIMARY KEY, days INTEGER, description TEXT);
|
| 9 |
+
CREATE TABLE erp_cash_disc(code TEXT PRIMARY KEY, percent REAL, days INTEGER, next_code TEXT, description TEXT);
|
| 10 |
+
CREATE TABLE erp_customers(
|
| 11 |
+
account TEXT PRIMARY KEY, dataareaid TEXT, name TEXT, customer_group TEXT,
|
| 12 |
+
currency TEXT, payment_term TEXT, cash_disc_code TEXT, credit_max REAL,
|
| 13 |
+
credit_rating TEXT, on_hold TEXT, city TEXT, state TEXT,
|
| 14 |
+
contact_name TEXT, contact_email TEXT, phone TEXT);
|
| 15 |
+
CREATE TABLE erp_vendors(
|
| 16 |
+
account TEXT PRIMARY KEY, dataareaid TEXT, name TEXT, vendor_group TEXT,
|
| 17 |
+
currency TEXT, payment_term TEXT, cash_disc_code TEXT, payment_method TEXT,
|
| 18 |
+
on_hold TEXT, city TEXT, state TEXT, contact_name TEXT, contact_email TEXT, phone TEXT);
|
| 19 |
+
-- Posted subledger. Open remainder = amount - settled where closed=0 (three-layer model).
|
| 20 |
+
CREATE TABLE erp_cust_trans(
|
| 21 |
+
id INTEGER PRIMARY KEY, dataareaid TEXT, account TEXT, voucher TEXT, invoice TEXT,
|
| 22 |
+
txn_type TEXT, description TEXT, trans_date TEXT, due_date TEXT, currency TEXT,
|
| 23 |
+
amount REAL, settled REAL DEFAULT 0, closed INTEGER DEFAULT 0, cash_disc_code TEXT,
|
| 24 |
+
disputed INTEGER DEFAULT 0, deduction INTEGER DEFAULT 0, payment_method TEXT);
|
| 25 |
+
CREATE TABLE erp_vend_trans(
|
| 26 |
+
id INTEGER PRIMARY KEY, dataareaid TEXT, account TEXT, voucher TEXT, invoice TEXT,
|
| 27 |
+
txn_type TEXT, description TEXT, trans_date TEXT, due_date TEXT, currency TEXT,
|
| 28 |
+
amount REAL, settled REAL DEFAULT 0, closed INTEGER DEFAULT 0, cash_disc_code TEXT,
|
| 29 |
+
po_number TEXT);
|
| 30 |
+
-- Procurement (3-way match surface: PO -> product receipt -> vendor invoice).
|
| 31 |
+
CREATE TABLE erp_purch_orders(
|
| 32 |
+
po_number TEXT, line INTEGER, dataareaid TEXT, vendor TEXT, item TEXT, description TEXT,
|
| 33 |
+
qty_ordered REAL, unit_price REAL, order_date TEXT, status TEXT,
|
| 34 |
+
PRIMARY KEY(po_number, line));
|
| 35 |
+
CREATE TABLE erp_product_receipts(
|
| 36 |
+
receipt_id TEXT, po_number TEXT, line INTEGER, receipt_date TEXT, qty_received REAL,
|
| 37 |
+
PRIMARY KEY(receipt_id, po_number, line));
|
| 38 |
+
CREATE TABLE erp_settlements(
|
| 39 |
+
id INTEGER PRIMARY KEY, side TEXT, dataareaid TEXT, account TEXT,
|
| 40 |
+
payment_id INTEGER, invoice_id INTEGER, amount REAL, cash_disc_taken REAL DEFAULT 0,
|
| 41 |
+
settle_date TEXT);
|
| 42 |
+
CREATE TABLE erp_collection_letters(
|
| 43 |
+
id INTEGER PRIMARY KEY, dataareaid TEXT, account TEXT, letter_code TEXT,
|
| 44 |
+
letter_date TEXT, status TEXT, fee REAL, note TEXT);
|
| 45 |
+
-- Sales orders (SalesTable): status, hold codes, responsible worker.
|
| 46 |
+
CREATE TABLE erp_sales_orders(
|
| 47 |
+
sales_id TEXT PRIMARY KEY, dataareaid TEXT, account TEXT, customer_name TEXT,
|
| 48 |
+
order_date TEXT, status TEXT, hold_code TEXT, responsible TEXT, amount REAL);
|
| 49 |
+
-- Collections activities/tasks (SmmActivities) and collections pools (CustPool).
|
| 50 |
+
CREATE TABLE erp_activities(
|
| 51 |
+
activity_id TEXT PRIMARY KEY, dataareaid TEXT, account TEXT, activity_type TEXT,
|
| 52 |
+
purpose TEXT, start_date TEXT, end_date TEXT, closed INTEGER DEFAULT 0, responsible TEXT);
|
| 53 |
+
CREATE TABLE erp_collection_pools(pool_id TEXT PRIMARY KEY, name TEXT, criteria TEXT);
|
| 54 |
+
CREATE TABLE erp_customer_pool(account TEXT PRIMARY KEY, pool_id TEXT);
|
| 55 |
+
-- Methods of payment (CustPaymModeTable/VendPaymModeTable) and their payment accounts.
|
| 56 |
+
CREATE TABLE erp_methods_of_payment(
|
| 57 |
+
method TEXT, side TEXT, dataareaid TEXT, description TEXT, payment_account TEXT,
|
| 58 |
+
PRIMARY KEY(method, side));
|
| 59 |
+
-- Form-tool runtime state (mirrors the real server's per-session view models; SQL-backed).
|
| 60 |
+
CREATE TABLE erp_form_sessions(form_id TEXT PRIMARY KEY, form TEXT, state TEXT);
|
| 61 |
+
-- Batch aging snapshot (the "second truth"; may lawfully diverge from live bucketing).
|
| 62 |
+
CREATE TABLE erp_aging_snapshot(
|
| 63 |
+
run_id TEXT, as_of TEXT, dataareaid TEXT, account TEXT, name TEXT,
|
| 64 |
+
not_due REAL, b1_30 REAL, b31_60 REAL, b61_90 REAL, b90_plus REAL, total_due REAL,
|
| 65 |
+
PRIMARY KEY(run_id, account));
|
| 66 |
+
|
| 67 |
+
-- ============ Subsidiary books: CES Direct LLC (QuickBooks-Online-shaped) ============
|
| 68 |
+
CREATE TABLE books_customers(id TEXT PRIMARY KEY, display_name TEXT, erp_ref TEXT, email TEXT);
|
| 69 |
+
CREATE TABLE books_invoices(
|
| 70 |
+
id TEXT PRIMARY KEY, customer_id TEXT, doc_number TEXT, txn_date TEXT, due_date TEXT,
|
| 71 |
+
amount REAL, balance REAL, status TEXT, memo TEXT);
|
| 72 |
+
CREATE TABLE books_credit_memos(
|
| 73 |
+
id TEXT PRIMARY KEY, customer_id TEXT, doc_number TEXT, txn_date TEXT,
|
| 74 |
+
amount REAL, remaining REAL, memo TEXT);
|
| 75 |
+
CREATE TABLE books_payments(
|
| 76 |
+
id TEXT PRIMARY KEY, customer_id TEXT, txn_date TEXT, amount REAL,
|
| 77 |
+
applied_to_invoice TEXT, method TEXT, memo TEXT);
|
| 78 |
+
|
| 79 |
+
-- ============ Shadow spreadsheets ============
|
| 80 |
+
CREATE TABLE sheet_files(name TEXT PRIMARY KEY, owner TEXT, modified_at TEXT, description TEXT);
|
| 81 |
+
CREATE TABLE sheet_rows(file TEXT, row_no INTEGER, cells TEXT, PRIMARY KEY(file, row_no));
|
| 82 |
+
|
| 83 |
+
-- ============ Email (read-only inbox) ============
|
| 84 |
+
CREATE TABLE email_messages(
|
| 85 |
+
id TEXT PRIMARY KEY, folder TEXT, from_addr TEXT, to_addr TEXT, subject TEXT,
|
| 86 |
+
sent_at TEXT, body TEXT, attachment_name TEXT, attachment_text TEXT);
|
| 87 |
+
|
| 88 |
+
-- Scripted counterparties: deterministic replies when the agent sends mail.
|
| 89 |
+
CREATE TABLE email_npc_scripts(
|
| 90 |
+
id TEXT PRIMARY KEY, match_to TEXT, match_keywords TEXT, reply_from TEXT,
|
| 91 |
+
reply_subject TEXT, reply_body TEXT, attachment_name TEXT, attachment_text TEXT);
|
| 92 |
+
|
| 93 |
+
-- ============ Filings (SEC-EDGAR-shaped frozen snapshots) ============
|
| 94 |
+
CREATE TABLE filings_companies(cik TEXT PRIMARY KEY, ticker TEXT, name TEXT);
|
| 95 |
+
CREATE TABLE filings_facts(
|
| 96 |
+
cik TEXT, concept TEXT, unit TEXT, fy TEXT, fp TEXT, period_end TEXT,
|
| 97 |
+
value REAL, form TEXT, filed TEXT, accession TEXT);
|
| 98 |
+
CREATE TABLE filings_documents(cik TEXT, form TEXT, filed TEXT, accession TEXT, title TEXT, excerpt TEXT);
|
| 99 |
+
|
| 100 |
+
-- ============ Document store (policies/SOPs; every body starts "> SIMULATION ONLY") ============
|
| 101 |
+
CREATE TABLE docs_documents(
|
| 102 |
+
doc_id TEXT PRIMARY KEY, title TEXT, doc_type TEXT, version TEXT,
|
| 103 |
+
effective_date TEXT, body TEXT);
|
| 104 |
+
|
| 105 |
+
-- ============ Harness (answers are state; verified deterministically) ============
|
| 106 |
+
CREATE TABLE answers(field TEXT PRIMARY KEY, value TEXT, submitted_at TEXT);
|
| 107 |
+
|
| 108 |
+
-- The reporting contract: what this task requires filed, and in what shape.
|
| 109 |
+
--
|
| 110 |
+
-- This used to be stapled onto the end of the human's message ("Reply with `submit_answer`:
|
| 111 |
+
-- - `dormant_count` (number) ..."), which no colleague would ever type and which handed the
|
| 112 |
+
-- model the decomposition for free — being told to report `overpayment_usd` AND
|
| 113 |
+
-- `underpayment_usd` separately reveals there are two directions of error before you look.
|
| 114 |
+
--
|
| 115 |
+
-- It belongs where it belongs in a real deployment: on the reporting tool. The harness server
|
| 116 |
+
-- exposes it through `reporting_fields`, so the agent discovers the contract by inspecting the
|
| 117 |
+
-- system, exactly as it would any other API, and the prompt is free to be a message.
|
| 118 |
+
CREATE TABLE answer_schema(
|
| 119 |
+
ordinal INTEGER, field TEXT PRIMARY KEY, type TEXT, description TEXT);
|
| 120 |
+
|
| 121 |
+
-- ============ Write-and-approve surface (hard layer M1/M2/M7) ============
|
| 122 |
+
-- Chart of accounts (Odoo account.account / ERPNext Account). account_type vocabulary is
|
| 123 |
+
-- Odoo's, truncated: asset_receivable, asset_cash, asset_current, liability_payable,
|
| 124 |
+
-- liability_current, equity, income, expense, off_balance.
|
| 125 |
+
CREATE TABLE erp_main_accounts(
|
| 126 |
+
account_code TEXT PRIMARY KEY, dataareaid TEXT, name TEXT, account_type TEXT,
|
| 127 |
+
currency TEXT, blocked INTEGER DEFAULT 0, reconcilable INTEGER DEFAULT 0,
|
| 128 |
+
requires_dimension TEXT);
|
| 129 |
+
|
| 130 |
+
-- Fiscal periods / period lock (Odoo company lock dates; mcp-erp close_period/reopen_period).
|
| 131 |
+
CREATE TABLE erp_fiscal_periods(
|
| 132 |
+
period_id TEXT PRIMARY KEY, dataareaid TEXT, period_start TEXT, period_end TEXT,
|
| 133 |
+
status TEXT DEFAULT 'open'); -- open | on_hold | closed
|
| 134 |
+
|
| 135 |
+
-- GL journal header. state: Odoo account.move.state (draft/posted/cancel), one-way draft->posted.
|
| 136 |
+
-- voucher_type: ERPNext Journal Entry.voucher_type subset. reversed_entry_id: Odoo
|
| 137 |
+
-- account.move.reversed_entry_id / ERPNext Journal Entry.reversal_of.
|
| 138 |
+
CREATE TABLE erp_ledger_journals(
|
| 139 |
+
journal_id TEXT PRIMARY KEY, dataareaid TEXT, voucher TEXT, voucher_type TEXT,
|
| 140 |
+
description TEXT, user_remark TEXT, posting_date TEXT, period_id TEXT, currency TEXT,
|
| 141 |
+
total_debit REAL DEFAULT 0, total_credit REAL DEFAULT 0, difference REAL DEFAULT 0,
|
| 142 |
+
state TEXT DEFAULT 'draft',
|
| 143 |
+
reversed_entry_id TEXT, reversal_reason TEXT,
|
| 144 |
+
created_by TEXT, created_at TEXT, posted_by TEXT, posted_at TEXT,
|
| 145 |
+
source_doc_id TEXT); -- the docs_documents row the amounts derive from (M4)
|
| 146 |
+
|
| 147 |
+
-- GL journal lines (Odoo account.move.line debit/credit/balance; mcp-erp PostJournalInput.lines).
|
| 148 |
+
CREATE TABLE erp_ledger_journal_lines(
|
| 149 |
+
journal_id TEXT, line INTEGER, account_code TEXT, description TEXT,
|
| 150 |
+
debit REAL DEFAULT 0, credit REAL DEFAULT 0, currency TEXT, fx_rate REAL DEFAULT 1,
|
| 151 |
+
party_type TEXT, party TEXT, dimension_dept TEXT,
|
| 152 |
+
PRIMARY KEY(journal_id, line));
|
| 153 |
+
|
| 154 |
+
-- Delegation of authority (ERPNext Authorization Rule: transaction/based_on/value/
|
| 155 |
+
-- system_role/approving_role/company). company-scoped rules SHADOW global rules.
|
| 156 |
+
CREATE TABLE erp_approval_policies(
|
| 157 |
+
policy_id TEXT PRIMARY KEY, dataareaid TEXT, doc_type TEXT,
|
| 158 |
+
based_on TEXT DEFAULT 'Grand Total', threshold_amount REAL, currency TEXT,
|
| 159 |
+
applies_to_role TEXT, approving_role TEXT, approving_user TEXT,
|
| 160 |
+
escalation_policy_id TEXT, active INTEGER DEFAULT 1);
|
| 161 |
+
|
| 162 |
+
-- Approval inbox (ERPNext AuthorizationControl outcome, materialised as a queue).
|
| 163 |
+
CREATE TABLE erp_approval_requests(
|
| 164 |
+
request_id TEXT PRIMARY KEY, dataareaid TEXT, doc_type TEXT, doc_id TEXT,
|
| 165 |
+
amount REAL, currency TEXT, submitted_by TEXT, submitted_at TEXT, note TEXT,
|
| 166 |
+
policy_id TEXT, required_role TEXT,
|
| 167 |
+
status TEXT DEFAULT 'pending', -- pending | approved | rejected | withdrawn
|
| 168 |
+
decided_by TEXT, decided_at TEXT, decision_reason TEXT);
|
| 169 |
+
|
| 170 |
+
-- Bank cash position: the constraint that makes M2 bite.
|
| 171 |
+
CREATE TABLE erp_bank_accounts(
|
| 172 |
+
bank_account TEXT PRIMARY KEY, dataareaid TEXT, name TEXT, currency TEXT,
|
| 173 |
+
available_balance REAL, as_of TEXT, overdraft_limit REAL DEFAULT 0);
|
| 174 |
+
|
| 175 |
+
-- Payment run header (ERPNext Payment Order; D365 payment proposal).
|
| 176 |
+
-- period_option: D365 method-of-payment Period (Invoice | Date | Total).
|
| 177 |
+
CREATE TABLE erp_payment_runs(
|
| 178 |
+
run_id TEXT PRIMARY KEY, dataareaid TEXT, pay_date TEXT, bank_account TEXT, currency TEXT,
|
| 179 |
+
period_option TEXT DEFAULT 'Invoice',
|
| 180 |
+
cash_available REAL, eligible_net REAL, total_paid REAL, total_rejected REAL,
|
| 181 |
+
state TEXT DEFAULT 'proposed', -- proposed | committed | cancelled
|
| 182 |
+
created_by TEXT, created_at TEXT, approved_by TEXT, committed_at TEXT);
|
| 183 |
+
|
| 184 |
+
-- Payment run lines: BOTH halves of the partition, one row each.
|
| 185 |
+
-- reason_code enum from erpnext/accounts/bulk_payment.py::_partition_payable_invoices
|
| 186 |
+
-- plus Vendor On Hold / Discount Window Expired / Awaiting Approval / Insufficient Cash.
|
| 187 |
+
CREATE TABLE erp_payment_run_lines(
|
| 188 |
+
run_id TEXT, line INTEGER, invoice TEXT, vendor TEXT, due_date TEXT,
|
| 189 |
+
gross_amount REAL, discount_taken REAL DEFAULT 0, withholding REAL DEFAULT 0,
|
| 190 |
+
net_amount REAL, disposition TEXT, reason_code TEXT, reason TEXT, priority_rank INTEGER,
|
| 191 |
+
PRIMARY KEY(run_id, line));
|
| 192 |
+
|
| 193 |
+
-- FX rates: without these, M4 cannot re-derive any cross-currency amount
|
| 194 |
+
-- (odoo-domain.md §8 gap #15 — we have a currency column and no rate table).
|
| 195 |
+
CREATE TABLE erp_fx_rates(
|
| 196 |
+
from_ccy TEXT, to_ccy TEXT, rate_date TEXT, rate REAL,
|
| 197 |
+
PRIMARY KEY(from_ccy, to_ccy, rate_date));
|
| 198 |
+
|
| 199 |
+
-- Two-phase confirm-gate token store. RUNTIME state: never graded, never readable as an entity.
|
| 200 |
+
CREATE TABLE erp_confirm_tokens(
|
| 201 |
+
token TEXT PRIMARY KEY, seq INTEGER, action TEXT, actor TEXT, role TEXT,
|
| 202 |
+
target_id TEXT, args_hash TEXT, effect_preview TEXT, minted_at TEXT,
|
| 203 |
+
consumed_at TEXT, superseded_by TEXT);
|
| 204 |
+
|
| 205 |
+
-- Audit trail (mcp-erp get_erp_audit_trail; odoo-ai-agent GET /chat/{id}/audit).
|
| 206 |
+
-- Derived from the graded writes; excluded from the state veto, assertable by row_count.
|
| 207 |
+
CREATE TABLE erp_audit_trail(
|
| 208 |
+
audit_id INTEGER PRIMARY KEY, entity_type TEXT, entity_id TEXT, action TEXT,
|
| 209 |
+
actor TEXT, role TEXT, at TEXT, before_json TEXT, after_json TEXT);
|
| 210 |
+
|
| 211 |
+
-- Deduction / short-pay reason codes (art.deduction_coding). Vocabulary follows AR
|
| 212 |
+
-- cash-application practice: research/external/articles/cash-application--{highradius,stuut,
|
| 213 |
+
-- zamp}.md — a deduction is coded, routed to an owner, and either conceded or charged back.
|
| 214 |
+
CREATE TABLE erp_deduction_reasons(
|
| 215 |
+
reason_code TEXT PRIMARY KEY, description TEXT, valid_claim INTEGER,
|
| 216 |
+
owner TEXT, disposition TEXT);
|
| 217 |
+
|
| 218 |
+
-- Withholding tax (erpnext.withholding_tax). ERPNext models this as Tax Withholding
|
| 219 |
+
-- Category + rates with a cumulative threshold; the vendor-side profile carries the
|
| 220 |
+
-- exemption certificate and its expiry, which is what actually decides whether we withhold.
|
| 221 |
+
CREATE TABLE erp_withholding_tax(
|
| 222 |
+
tax_category TEXT PRIMARY KEY, description TEXT, rate_pct REAL,
|
| 223 |
+
threshold_amount REAL DEFAULT 0, statutory_ref TEXT);
|
| 224 |
+
|
| 225 |
+
CREATE TABLE erp_vendor_tax_profile(
|
| 226 |
+
account TEXT PRIMARY KEY, tax_category TEXT, certificate_type TEXT,
|
| 227 |
+
certificate_on_file INTEGER DEFAULT 0, certificate_expiry TEXT, notes TEXT);
|
| 228 |
+
|
| 229 |
+
-- ═══ Procure-to-pay / make-or-buy surface (agentic-labs/erp-bench, 300 tasks) ═══
|
| 230 |
+
--
|
| 231 |
+
-- ERP-Bench ships each task as a Harbor dir that boots a real Odoo 19 in Docker and grades it
|
| 232 |
+
-- with odoolib queries against the live server. The plumbing does not port; the JUDGEMENT does,
|
| 233 |
+
-- because `environment/scenario_data.json` is a fully DECLARATIVE world spec — partners with
|
| 234 |
+
-- budgets, products with per-vendor min/max/price offers, BOMs, workcenters, stock and existing
|
| 235 |
+
-- orders. So the scenario seeds our world and the grading becomes deterministic state diffs
|
| 236 |
+
-- (docs/PARITY.md, docs/INGESTION.md `needs_surface` -> built).
|
| 237 |
+
--
|
| 238 |
+
-- These tables are EMPTY in core by design. Each ERP-Bench scenario is its own small world, so
|
| 239 |
+
-- it arrives through the per-task seed layer rather than the shared ledger — the same mechanic
|
| 240 |
+
-- that already carries every other task's chaos.
|
| 241 |
+
|
| 242 |
+
CREATE TABLE erpb_partners(
|
| 243 |
+
ref TEXT PRIMARY KEY, name TEXT, kind TEXT, -- kind: customer | vendor
|
| 244 |
+
supplier_rank INTEGER DEFAULT 0, budget_dollars REAL, credit_limit REAL,
|
| 245 |
+
payment_term TEXT, email TEXT,
|
| 246 |
+
comment TEXT); -- Odoo "Internal Notes": several tasks hide the binding
|
| 247 |
+
-- max-order-quantity rule here and nowhere else
|
| 248 |
+
|
| 249 |
+
CREATE TABLE erpb_products(
|
| 250 |
+
code TEXT PRIMARY KEY, name TEXT, category TEXT, type TEXT,
|
| 251 |
+
list_price REAL, standard_price REAL,
|
| 252 |
+
routes TEXT, -- csv of {buy, manufacture}: whether make-or-buy is even a choice
|
| 253 |
+
comment TEXT);
|
| 254 |
+
|
| 255 |
+
CREATE TABLE erpb_vendor_offers(
|
| 256 |
+
id INTEGER PRIMARY KEY, product_code TEXT, partner_ref TEXT, name TEXT,
|
| 257 |
+
delay INTEGER, -- lead time in days, against the order's due date
|
| 258 |
+
min_qty REAL, max_qty REAL, -- horizon-wide totals, NOT per-line minimums
|
| 259 |
+
price REAL);
|
| 260 |
+
|
| 261 |
+
CREATE TABLE erpb_boms(
|
| 262 |
+
id INTEGER PRIMARY KEY, product_code TEXT, type TEXT, quantity REAL, warehouse_code TEXT);
|
| 263 |
+
CREATE TABLE erpb_bom_components(
|
| 264 |
+
bom_id INTEGER, component_code TEXT, quantity REAL);
|
| 265 |
+
|
| 266 |
+
CREATE TABLE erpb_workcenters(
|
| 267 |
+
code TEXT PRIMARY KEY, name TEXT, capacity_per_day REAL, cost_per_hour REAL,
|
| 268 |
+
warehouse_code TEXT, comment TEXT);
|
| 269 |
+
|
| 270 |
+
CREATE TABLE erpb_stock(
|
| 271 |
+
product_code TEXT, warehouse_code TEXT, quantity REAL, location_type TEXT);
|
| 272 |
+
|
| 273 |
+
-- The demand named in the instruction: who wants how many, by when, under what budget cap.
|
| 274 |
+
CREATE TABLE erpb_demand(
|
| 275 |
+
id INTEGER PRIMARY KEY, partner_ref TEXT, product_code TEXT, units REAL,
|
| 276 |
+
due_days INTEGER, budget_cap REAL, seeded_order_state TEXT);
|
| 277 |
+
|
| 278 |
+
-- ── agent-written state: what the verifier grades ──
|
| 279 |
+
CREATE TABLE erpb_sale_orders(
|
| 280 |
+
name TEXT PRIMARY KEY, partner_ref TEXT, state TEXT,
|
| 281 |
+
commitment_date TEXT, origin TEXT);
|
| 282 |
+
CREATE TABLE erpb_sale_order_lines(
|
| 283 |
+
id INTEGER PRIMARY KEY, order_name TEXT, product_code TEXT, qty REAL, price_unit REAL);
|
| 284 |
+
|
| 285 |
+
CREATE TABLE erpb_purchase_orders(
|
| 286 |
+
name TEXT PRIMARY KEY, partner_ref TEXT, state TEXT,
|
| 287 |
+
date_planned TEXT,
|
| 288 |
+
origin TEXT); -- the SO reference(s): the SO->PO lineage the tasks require
|
| 289 |
+
CREATE TABLE erpb_purchase_order_lines(
|
| 290 |
+
id INTEGER PRIMARY KEY, order_name TEXT, product_code TEXT, qty REAL, price_unit REAL);
|
| 291 |
+
|
| 292 |
+
CREATE TABLE erpb_manufacturing_orders(
|
| 293 |
+
name TEXT PRIMARY KEY, product_code TEXT, qty REAL, state TEXT,
|
| 294 |
+
workcenter_code TEXT, date_planned TEXT, origin TEXT);
|
world/server.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""LedgerBench-100 world service: Streamable HTTP MCP bridge + token-gated verifier.
|
| 3 |
+
|
| 4 |
+
One process serves the task's eight finance MCP servers (imported in-process from the
|
| 5 |
+
pack's own runtime/) over per-server Streamable HTTP endpoints:
|
| 6 |
+
|
| 7 |
+
POST /mcp/<server> JSON-RPC: initialize | ping | tools/list | tools/call
|
| 8 |
+
GET /health readiness for the compose healthcheck
|
| 9 |
+
POST /verify token-gated deterministic verification (X-Verify-Token)
|
| 10 |
+
|
| 11 |
+
The agent container never sees the verification token: the pack bakes only its
|
| 12 |
+
SHA-256 digest into spec.json. tests/test.sh (copied into the container only at
|
| 13 |
+
verification time) holds the actual token.
|
| 14 |
+
|
| 15 |
+
Everything is offline and deterministic: SQLite world state, frozen WORLD_NOW
|
| 16 |
+
clock, stdlib-only, no LLM anywhere.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import gzip
|
| 21 |
+
import hashlib
|
| 22 |
+
import importlib.util
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import shutil
|
| 26 |
+
import sys
|
| 27 |
+
from http import HTTPStatus
|
| 28 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import Any
|
| 31 |
+
|
| 32 |
+
HERE = Path(__file__).resolve().parent
|
| 33 |
+
SPEC = json.loads((HERE / "spec.json").read_text(encoding="utf-8"))
|
| 34 |
+
RUNTIME = HERE / "runtime"
|
| 35 |
+
RUN_DIR = Path(os.environ.get("LEDGERBENCH_RUN_DIR", "/opt/world/run"))
|
| 36 |
+
PROTOCOL_VERSION = "2025-06-18"
|
| 37 |
+
|
| 38 |
+
_SERVERS: dict[str, Any] = {}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def load_servers() -> dict[str, Any]:
|
| 42 |
+
"""Import the pack's MCP server modules in-process (same handlers, same trace)."""
|
| 43 |
+
if _SERVERS:
|
| 44 |
+
return _SERVERS
|
| 45 |
+
sys.path.insert(0, str(RUNTIME / "lib"))
|
| 46 |
+
for name in SPEC["servers"]:
|
| 47 |
+
spec = importlib.util.spec_from_file_location(
|
| 48 |
+
f"lgr_{name}_server", RUNTIME / "servers" / f"{name}_server.py"
|
| 49 |
+
)
|
| 50 |
+
module = importlib.util.module_from_spec(spec)
|
| 51 |
+
spec.loader.exec_module(module)
|
| 52 |
+
_SERVERS[name] = module.S
|
| 53 |
+
return _SERVERS
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def reset_run_dir() -> None:
|
| 57 |
+
"""Materialize a pristine run: fresh world DB, empty trace, initial hashes."""
|
| 58 |
+
RUN_DIR.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
state = HERE / "state"
|
| 60 |
+
db_gz = state / "world.sqlite.gz"
|
| 61 |
+
db = state / "world.sqlite"
|
| 62 |
+
target = RUN_DIR / "world.sqlite"
|
| 63 |
+
if db.exists():
|
| 64 |
+
shutil.copyfile(db, target)
|
| 65 |
+
else:
|
| 66 |
+
with gzip.open(db_gz, "rb") as fin, open(target, "wb") as fout:
|
| 67 |
+
shutil.copyfileobj(fin, fout)
|
| 68 |
+
shutil.copyfile(state / "initial_state.json", RUN_DIR / "initial_state.json")
|
| 69 |
+
(RUN_DIR / "trace.jsonl").write_text("")
|
| 70 |
+
os.environ["WORLD_DB"] = str(target)
|
| 71 |
+
os.environ["WORLD_NOW"] = SPEC["world_now"]
|
| 72 |
+
os.environ["WORLD_ROLE"] = SPEC["world_role"]
|
| 73 |
+
os.environ["TRACE_FILE"] = str(RUN_DIR / "trace.jsonl")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def build_report(task_dir: Path, run_dir: Path, task_id: str) -> dict[str, Any]:
|
| 77 |
+
"""Deterministic verification report (no clock, no randomness, no network)."""
|
| 78 |
+
sys.path.insert(0, str(RUNTIME))
|
| 79 |
+
from vcode import verify_all # the pack's own deterministic verifier engine
|
| 80 |
+
|
| 81 |
+
verdict = verify_all(str(task_dir), str(run_dir))
|
| 82 |
+
report = {
|
| 83 |
+
"benchmark": SPEC["benchmark"],
|
| 84 |
+
"version": SPEC["version"],
|
| 85 |
+
"task_id": task_id,
|
| 86 |
+
"passed": verdict["reward"] == 1,
|
| 87 |
+
"reward": float(verdict["reward"]),
|
| 88 |
+
"failed_checks": sorted(verdict["failed"]),
|
| 89 |
+
"n_tool_calls": verdict["n_tool_calls"],
|
| 90 |
+
"servers_used": verdict["servers_used"],
|
| 91 |
+
"steps_graded": verdict.get("steps", 1),
|
| 92 |
+
}
|
| 93 |
+
report["report_sha256"] = hashlib.sha256(
|
| 94 |
+
json.dumps(report, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
| 95 |
+
).hexdigest()
|
| 96 |
+
return report
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def rpc_response(server_name: str, request: dict[str, Any]) -> dict[str, Any] | None:
|
| 100 |
+
request_id = request.get("id")
|
| 101 |
+
method = request.get("method")
|
| 102 |
+
if request_id is None and isinstance(method, str) and method.startswith("notifications/"):
|
| 103 |
+
return None
|
| 104 |
+
if request.get("jsonrpc") != "2.0" or not isinstance(method, str):
|
| 105 |
+
return {"jsonrpc": "2.0", "id": request_id,
|
| 106 |
+
"error": {"code": -32600, "message": "Invalid Request"}}
|
| 107 |
+
servers = load_servers()
|
| 108 |
+
if server_name not in servers:
|
| 109 |
+
return {"jsonrpc": "2.0", "id": request_id,
|
| 110 |
+
"error": {"code": -32601, "message": f"unknown server {server_name!r}"}}
|
| 111 |
+
srv = servers[server_name]
|
| 112 |
+
if method == "initialize":
|
| 113 |
+
params = request.get("params") or {}
|
| 114 |
+
return {"jsonrpc": "2.0", "id": request_id, "result": {
|
| 115 |
+
"protocolVersion": params.get("protocolVersion", PROTOCOL_VERSION),
|
| 116 |
+
"capabilities": {"tools": {}},
|
| 117 |
+
"serverInfo": {"name": srv.name, "version": "1.0.0"},
|
| 118 |
+
"instructions": srv.description,
|
| 119 |
+
}}
|
| 120 |
+
if method == "ping":
|
| 121 |
+
return {"jsonrpc": "2.0", "id": request_id, "result": {}}
|
| 122 |
+
if method == "tools/list":
|
| 123 |
+
return {"jsonrpc": "2.0", "id": request_id,
|
| 124 |
+
"result": {"tools": [schema for _, schema in srv.tools.values()]}}
|
| 125 |
+
if method == "tools/call":
|
| 126 |
+
params = request.get("params") or {}
|
| 127 |
+
tool = params.get("name")
|
| 128 |
+
arguments = params.get("arguments") or {}
|
| 129 |
+
if tool not in srv.tools:
|
| 130 |
+
return {"jsonrpc": "2.0", "id": request_id, "result": {
|
| 131 |
+
"content": [{"type": "text", "text": f"unknown tool {tool}"}],
|
| 132 |
+
"isError": True}}
|
| 133 |
+
try:
|
| 134 |
+
out = srv.call(tool, arguments)
|
| 135 |
+
return {"jsonrpc": "2.0", "id": request_id, "result": {
|
| 136 |
+
"content": [{"type": "text", "text": json.dumps(out, default=str)}],
|
| 137 |
+
"isError": False}}
|
| 138 |
+
except Exception as error: # noqa: BLE001 - surface tool failure to the agent
|
| 139 |
+
return {"jsonrpc": "2.0", "id": request_id, "result": {
|
| 140 |
+
"content": [{"type": "text", "text": f"error: {error!r}"}],
|
| 141 |
+
"isError": True}}
|
| 142 |
+
return {"jsonrpc": "2.0", "id": request_id,
|
| 143 |
+
"error": {"code": -32601, "message": "Method not found"}}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class Handler(BaseHTTPRequestHandler):
|
| 147 |
+
server_version = "LedgerBenchWorld/1.0"
|
| 148 |
+
|
| 149 |
+
def log_message(self, fmt: str, *args: Any) -> None: # noqa: A003
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
def _json(self, status: int, value: Any) -> None:
|
| 153 |
+
payload = json.dumps(value, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
| 154 |
+
self.send_response(status)
|
| 155 |
+
self.send_header("Content-Type", "application/json")
|
| 156 |
+
self.send_header("Content-Length", str(len(payload)))
|
| 157 |
+
self.send_header("MCP-Protocol-Version", PROTOCOL_VERSION)
|
| 158 |
+
self.end_headers()
|
| 159 |
+
self.wfile.write(payload)
|
| 160 |
+
|
| 161 |
+
def do_GET(self) -> None: # noqa: N802
|
| 162 |
+
if self.path == "/health":
|
| 163 |
+
self._json(HTTPStatus.OK, {"status": "ok", "task_id": SPEC["task_id"]})
|
| 164 |
+
return
|
| 165 |
+
self._json(HTTPStatus.NOT_FOUND, {"error": "not_found"})
|
| 166 |
+
|
| 167 |
+
def do_POST(self) -> None: # noqa: N802
|
| 168 |
+
length = int(self.headers.get("Content-Length", "0"))
|
| 169 |
+
body = self.rfile.read(length)
|
| 170 |
+
if self.path == "/verify":
|
| 171 |
+
token = self.headers.get("X-Verify-Token") or ""
|
| 172 |
+
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
| 173 |
+
if digest != SPEC["verify_token_sha256"]:
|
| 174 |
+
self._json(HTTPStatus.NOT_FOUND, {"error": "not_found"})
|
| 175 |
+
return
|
| 176 |
+
self._json(HTTPStatus.OK,
|
| 177 |
+
build_report(HERE / "taskspec", RUN_DIR, SPEC["task_id"]))
|
| 178 |
+
return
|
| 179 |
+
if not self.path.startswith("/mcp/"):
|
| 180 |
+
self._json(HTTPStatus.NOT_FOUND, {"error": "not_found"})
|
| 181 |
+
return
|
| 182 |
+
server_name = self.path[len("/mcp/"):].strip("/")
|
| 183 |
+
try:
|
| 184 |
+
request = json.loads(body.decode("utf-8"))
|
| 185 |
+
except (UnicodeError, json.JSONDecodeError):
|
| 186 |
+
self._json(HTTPStatus.BAD_REQUEST,
|
| 187 |
+
{"jsonrpc": "2.0", "id": None,
|
| 188 |
+
"error": {"code": -32700, "message": "Parse error"}})
|
| 189 |
+
return
|
| 190 |
+
if isinstance(request, list):
|
| 191 |
+
responses = [r for item in request
|
| 192 |
+
if (r := rpc_response(server_name, item)) is not None]
|
| 193 |
+
self._json(HTTPStatus.OK, responses)
|
| 194 |
+
return
|
| 195 |
+
response = rpc_response(server_name, request)
|
| 196 |
+
if response is None:
|
| 197 |
+
self.send_response(HTTPStatus.ACCEPTED)
|
| 198 |
+
self.send_header("Content-Length", "0")
|
| 199 |
+
self.end_headers()
|
| 200 |
+
return
|
| 201 |
+
self._json(HTTPStatus.OK, response)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def main() -> None:
|
| 205 |
+
reset_run_dir()
|
| 206 |
+
load_servers()
|
| 207 |
+
host = os.environ.get("LEDGERBENCH_HOST", "0.0.0.0")
|
| 208 |
+
port = int(os.environ.get("LEDGERBENCH_PORT", "8974"))
|
| 209 |
+
ThreadingHTTPServer((host, port), Handler).serve_forever()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__":
|
| 213 |
+
main()
|
world/vcode.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Deterministic verifier engine. No LLM in the reward path.
|
| 3 |
+
|
| 4 |
+
Reads tests/checks.json from a task dir and a run dir (world.sqlite, trace.jsonl,
|
| 5 |
+
initial_state.json). Emits {"reward": 0|1, "failed": [...]} on stdout; always exits 0.
|
| 6 |
+
|
| 7 |
+
checks.json:
|
| 8 |
+
answer_checks: [{field, type: number|string|contains_all, expect, tol_abs?, tol_rel?}]
|
| 9 |
+
number: value parsed from "$1,234.56", "1234.56", 1234.56; pass if within
|
| 10 |
+
max(tol_abs, |expect|*tol_rel); default exact to 0.01.
|
| 11 |
+
string: case/space-insensitive equality.
|
| 12 |
+
contains_all: every listed substring appears (case-insensitive) in the value; an
|
| 13 |
+
optional `forbid` list must NOT appear, so a set answer is graded for
|
| 14 |
+
over-inclusion as well as omission.
|
| 15 |
+
scale: the unit a figure is stated in (units/thousands/millions/billions/percent),
|
| 16 |
+
graded as its own field the way TAT-QA does. Any numeric check additionally
|
| 17 |
+
reports `scale_error` when the answer is a clean 1e3/1e6/1e9 multiple of the
|
| 18 |
+
truth, so a unit slip is never filed as ordinary arithmetic error.
|
| 19 |
+
yes_no: polarity of a yes/no field, with any trailing justification allowed
|
| 20 |
+
("no - no record in the ERP" passes for expect "no"). Same lesson as
|
| 21 |
+
none_answer: grade the finding, not the prose.
|
| 22 |
+
none_answer: the empty-answer trap (replaces the old expect:"none" string check —
|
| 23 |
+
see docs/AUDIT.md A5). Passes when the value OPENS with a negative
|
| 24 |
+
("none", "no ...", "n/a", "nil", "not found", "zero"), with any trailing
|
| 25 |
+
justification allowed, and fails if any `forbid` substring appears — so the
|
| 26 |
+
trap asserts "did not invent a record" instead of "wrote exactly one word".
|
| 27 |
+
trace_checks: [{type: required_servers, servers: [...]},
|
| 28 |
+
{type: min_calls, server, n},
|
| 29 |
+
{type: reads_before_submit}]
|
| 30 |
+
state_checks: [{type: writes_only, tables: ["answers"]}, # anti-hack veto
|
| 31 |
+
{type: row_count, sql, expect, name?},
|
| 32 |
+
{type: sql, sql, expect, tol_abs?, tol_rel?, name?}]
|
| 33 |
+
sql: grade the world the agent left behind (write tasks) — the committed run, the
|
| 34 |
+
paid/rejected partition, the reason codes. Numbers compare with tolerance.
|
| 35 |
+
"""
|
| 36 |
+
import json, re, sqlite3, hashlib, sys
|
| 37 |
+
from pathlib import Path
|
| 38 |
+
|
| 39 |
+
def table_hashes(db):
|
| 40 |
+
cx = sqlite3.connect(db)
|
| 41 |
+
out = {}
|
| 42 |
+
for (t,) in cx.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"):
|
| 43 |
+
rows = cx.execute(f"SELECT * FROM {t}").fetchall()
|
| 44 |
+
h = hashlib.sha256(repr(sorted(map(repr, rows))).encode()).hexdigest()[:16]
|
| 45 |
+
out[t] = [len(rows), h]
|
| 46 |
+
cx.close()
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
def parse_number(v):
|
| 50 |
+
if isinstance(v, (int, float)): return float(v)
|
| 51 |
+
s = re.sub(r"[,$\s]|USD", "", str(v), flags=re.I).rstrip("%")
|
| 52 |
+
m = re.match(r"^-?\d+(\.\d+)?$", s)
|
| 53 |
+
return float(s) if m else None
|
| 54 |
+
|
| 55 |
+
def norm(v): return re.sub(r"\s+", " ", str(v)).strip().lower()
|
| 56 |
+
|
| 57 |
+
# An empty-answer trap is satisfied by a value that OPENS with a negative. Trailing
|
| 58 |
+
# justification is allowed and expected — a model that explains "none, because no remittance
|
| 59 |
+
# advice was on file" is more useful than one that emits the bare token, and grading them
|
| 60 |
+
# differently measured prose, not grounding (docs/AUDIT.md A5).
|
| 61 |
+
NEG_RE = re.compile(r"^(none|no|n/?a|nil|nothing|zero|not\s+(found|applicable|available|on\s+file))\b")
|
| 62 |
+
|
| 63 |
+
# Same lesson as NEG_RE, for yes/no fields: a finance answer worth reading is "no - Meadow
|
| 64 |
+
# Analytics has no record in the ERP", not the bare token. Grade the polarity, not the prose.
|
| 65 |
+
YES_RE = re.compile(r"^(yes|y|true|correct|confirmed|affirmative)\b")
|
| 66 |
+
NO_RE = re.compile(r"^(no|n|false|incorrect|negative|none|not)\b")
|
| 67 |
+
|
| 68 |
+
# TAT-QA grades `scale` (thousand/million/billion/percent) as a field in its own right,
|
| 69 |
+
# because a financial number without its unit is not an answer (round-2 ledger row 28). We
|
| 70 |
+
# do the same, and additionally diagnose the classic magnitude slip on ANY numeric check
|
| 71 |
+
# rather than letting it hide inside a generic "off by a lot".
|
| 72 |
+
SCALE_SYNONYMS = {
|
| 73 |
+
"units": {"units", "unit", "absolute", "ones", "dollars", "usd", "as reported", "none"},
|
| 74 |
+
"thousands": {"thousand", "thousands", "k", "000s", "in thousands"},
|
| 75 |
+
"millions": {"million", "millions", "m", "mm", "in millions"},
|
| 76 |
+
"billions": {"billion", "billions", "b", "bn", "in billions"},
|
| 77 |
+
"percent": {"percent", "percentage", "%", "pct"},
|
| 78 |
+
}
|
| 79 |
+
SCALE_FACTOR = {"units": 1, "thousands": 1e3, "millions": 1e6, "billions": 1e9}
|
| 80 |
+
|
| 81 |
+
def scale_of(v):
|
| 82 |
+
s = norm(v).replace("(", " ").replace(")", " ").strip(" .")
|
| 83 |
+
for canon, words in SCALE_SYNONYMS.items():
|
| 84 |
+
if s == canon or s in words: return canon
|
| 85 |
+
# specific scales win over the generic "units" bucket: "USD millions" is millions, not
|
| 86 |
+
# units, even though "usd" is a units synonym.
|
| 87 |
+
for canon in ("billions", "millions", "thousands", "percent", "units"):
|
| 88 |
+
words = SCALE_SYNONYMS[canon]
|
| 89 |
+
if any(re.search(rf"\b{re.escape(w)}\b", s) for w in words if len(w) > 2): return canon
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
def magnitude_slip(got, exp):
|
| 93 |
+
"""Return the factor if the answer is a clean 1e3/1e6/1e9 multiple of the truth."""
|
| 94 |
+
if not got or not exp: return None
|
| 95 |
+
for f in (1e3, 1e6, 1e9):
|
| 96 |
+
for cand, label in ((exp * f, f), (exp / f, 1 / f)):
|
| 97 |
+
if cand and abs(got - cand) <= max(0.01, abs(cand) * 1e-4):
|
| 98 |
+
return label
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
def polarity(v):
|
| 102 |
+
s = norm(v)
|
| 103 |
+
if YES_RE.match(s): return "yes"
|
| 104 |
+
if NO_RE.match(s): return "no"
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
def verify(task_dir, run_dir):
|
| 108 |
+
"""Verify one step. `task_dir` is a task root (tests/checks.json) or a step dir (checks.json)."""
|
| 109 |
+
p = Path(task_dir) / "tests/checks.json"
|
| 110 |
+
checks = json.loads((p if p.exists() else Path(task_dir) / "checks.json").read_text())
|
| 111 |
+
db = Path(run_dir) / "world.sqlite"
|
| 112 |
+
failed = []
|
| 113 |
+
|
| 114 |
+
cx = sqlite3.connect(db)
|
| 115 |
+
answers = {f: json.loads(v) for f, v in cx.execute("SELECT field, value FROM answers")}
|
| 116 |
+
cx.close()
|
| 117 |
+
|
| 118 |
+
for c in checks.get("answer_checks", []):
|
| 119 |
+
fld, typ = c["field"], c.get("type", "string")
|
| 120 |
+
name = f"answer:{fld}"
|
| 121 |
+
if fld not in answers:
|
| 122 |
+
failed.append(name + ":missing"); continue
|
| 123 |
+
got = answers[fld]
|
| 124 |
+
if typ == "number":
|
| 125 |
+
g = parse_number(got)
|
| 126 |
+
if g is None: failed.append(name + ":not_numeric"); continue
|
| 127 |
+
exp = float(c["expect"])
|
| 128 |
+
tol = max(float(c.get("tol_abs", 0.01)), abs(exp) * float(c.get("tol_rel", 0)))
|
| 129 |
+
if abs(g - exp) > tol:
|
| 130 |
+
slip = magnitude_slip(g, exp)
|
| 131 |
+
if slip:
|
| 132 |
+
# reported in the wrong unit rather than computed wrongly: a different
|
| 133 |
+
# failure mode, and one worth naming separately in the reports.
|
| 134 |
+
scale = {1e3: "thousands", 1e6: "millions", 1e9: "billions"}.get(slip)
|
| 135 |
+
failed.append(name + f":scale_error(got={g}, want={exp}, off by "
|
| 136 |
+
f"{'x' if slip > 1 else '/'}{int(slip if slip > 1 else 1/slip)}"
|
| 137 |
+
+ (f" - looks reported in {scale}" if scale else "") + ")")
|
| 138 |
+
else:
|
| 139 |
+
failed.append(name + f":off(got={g})")
|
| 140 |
+
elif typ == "none_answer":
|
| 141 |
+
g = norm(got)
|
| 142 |
+
if not NEG_RE.match(g):
|
| 143 |
+
failed.append(name + f":expected_none(got={g[:60]})")
|
| 144 |
+
else:
|
| 145 |
+
# the anti-hallucination half: naming a real record while claiming "none"
|
| 146 |
+
# is a harder failure than being wrong, and is what the trap exists to catch.
|
| 147 |
+
bad = [s for s in c.get("forbid", []) if norm(s) in g]
|
| 148 |
+
if bad: failed.append(name + f":hallucinated({bad})")
|
| 149 |
+
elif typ == "scale":
|
| 150 |
+
g = scale_of(got)
|
| 151 |
+
exp_s = scale_of(c["expect"]) or norm(c["expect"])
|
| 152 |
+
if g is None:
|
| 153 |
+
failed.append(name + f":unparseable_scale(got={norm(got)[:40]})")
|
| 154 |
+
elif g != exp_s:
|
| 155 |
+
failed.append(name + f":wrong_scale(got={g}, want={exp_s})")
|
| 156 |
+
elif typ == "yes_no":
|
| 157 |
+
got_p, exp_p = polarity(got), norm(c["expect"])
|
| 158 |
+
if got_p is None:
|
| 159 |
+
failed.append(name + f":unparseable_yes_no(got={norm(got)[:60]})")
|
| 160 |
+
elif got_p != exp_p:
|
| 161 |
+
failed.append(name + f":wrong_polarity(got={got_p}, want={exp_p})")
|
| 162 |
+
else:
|
| 163 |
+
bad = [s for s in c.get("forbid", []) if norm(s) in norm(got)]
|
| 164 |
+
if bad: failed.append(name + f":hallucinated({bad})")
|
| 165 |
+
elif typ == "contains_all":
|
| 166 |
+
g = norm(got)
|
| 167 |
+
missing = [s for s in c["expect"] if norm(s) not in g]
|
| 168 |
+
if missing: failed.append(name + f":missing_terms({missing})")
|
| 169 |
+
# `forbid` is the other half of a set answer: naming the right records is only
|
| 170 |
+
# correct if it does not ALSO name the wrong ones (over-inclusion is a distinct
|
| 171 |
+
# failure from omission and is reported as one).
|
| 172 |
+
over = [s for s in c.get("forbid", []) if norm(s) in g]
|
| 173 |
+
if over: failed.append(name + f":forbidden_terms({over})")
|
| 174 |
+
else:
|
| 175 |
+
if norm(got) != norm(c["expect"]): failed.append(name + f":mismatch(got={norm(got)[:60]})")
|
| 176 |
+
|
| 177 |
+
trace = []
|
| 178 |
+
tf = Path(run_dir) / "trace.jsonl"
|
| 179 |
+
if tf.exists():
|
| 180 |
+
trace = [json.loads(l) for l in tf.read_text().splitlines() if l.strip()]
|
| 181 |
+
for c in checks.get("trace_checks", []):
|
| 182 |
+
t = c["type"]
|
| 183 |
+
if t == "required_servers":
|
| 184 |
+
used = {r["server"] for r in trace if r.get("ok")}
|
| 185 |
+
miss = [s for s in c["servers"] if s not in used]
|
| 186 |
+
if miss: failed.append(f"trace:required_servers_missing({miss})")
|
| 187 |
+
elif t == "min_calls":
|
| 188 |
+
n = sum(1 for r in trace if r["server"] == c["server"] and r.get("ok"))
|
| 189 |
+
if n < c["n"]: failed.append(f"trace:min_calls({c['server']}<{c['n']})")
|
| 190 |
+
elif t == "reads_before_submit":
|
| 191 |
+
first_submit = next((i for i, r in enumerate(trace)
|
| 192 |
+
if r["server"] == "harness" and r["tool"] == "submit_answer"), None)
|
| 193 |
+
reads_before = any(r["server"] != "harness" and r.get("ok") for r in trace[:first_submit or 0])
|
| 194 |
+
if first_submit is None or not reads_before:
|
| 195 |
+
failed.append("trace:no_reads_before_submit")
|
| 196 |
+
|
| 197 |
+
init = json.loads((Path(run_dir) / "initial_state.json").read_text())
|
| 198 |
+
final = table_hashes(db)
|
| 199 |
+
RUNTIME_TABLES = {"erp_form_sessions"} # tool-session state, never an off-task write
|
| 200 |
+
cx = sqlite3.connect(db)
|
| 201 |
+
for c in checks.get("state_checks", []):
|
| 202 |
+
t = c["type"]
|
| 203 |
+
if t == "writes_only":
|
| 204 |
+
allowed = set(c.get("tables", ["answers"])) | RUNTIME_TABLES
|
| 205 |
+
dirty = [x for x in final if x not in allowed and final[x] != init.get(x)]
|
| 206 |
+
if dirty: failed.append(f"state:off_task_writes({dirty})")
|
| 207 |
+
elif t == "row_count":
|
| 208 |
+
n = cx.execute(c["sql"]).fetchone()[0]
|
| 209 |
+
if n != c["expect"]:
|
| 210 |
+
failed.append(f"state:row_count({c.get('name', c['sql'][:40])}: got {n}, want {c['expect']})")
|
| 211 |
+
elif t == "sql":
|
| 212 |
+
# Grade the world the agent left behind, not the story it told about it. Used by
|
| 213 |
+
# write tasks: the run it committed, the partition it chose, the reasons it gave.
|
| 214 |
+
# Numeric comparisons carry a tolerance; everything else is normalized equality.
|
| 215 |
+
got = cx.execute(c["sql"]).fetchone()
|
| 216 |
+
got = (got[0] if got else None)
|
| 217 |
+
exp, name_ = c["expect"], c.get("name", c["sql"][:40])
|
| 218 |
+
if isinstance(exp, (int, float)) and not isinstance(exp, bool):
|
| 219 |
+
g = parse_number(got)
|
| 220 |
+
tol = max(float(c.get("tol_abs", 0.01)), abs(float(exp)) * float(c.get("tol_rel", 0)))
|
| 221 |
+
if g is None or abs(g - float(exp)) > tol:
|
| 222 |
+
failed.append(f"state:sql({name_}: got {got}, want {exp})")
|
| 223 |
+
elif norm(got) != norm(exp):
|
| 224 |
+
failed.append(f"state:sql({name_}: got {norm(got)[:60]}, want {norm(exp)[:60]})")
|
| 225 |
+
elif t == "cell_equals":
|
| 226 |
+
row = cx.execute(c["sql"]).fetchone()
|
| 227 |
+
got = row[0] if row else None
|
| 228 |
+
exp = c["expect"]
|
| 229 |
+
ok = (abs(float(got) - float(exp)) <= float(c.get("tol_abs", 0))
|
| 230 |
+
if isinstance(exp, (int, float)) and got is not None
|
| 231 |
+
else norm(got) == norm(exp))
|
| 232 |
+
if not ok:
|
| 233 |
+
failed.append(f"state:cell_equals({c.get('name', c['sql'][:40])}: got {got!r}, want {exp!r})")
|
| 234 |
+
cx.close()
|
| 235 |
+
|
| 236 |
+
return {"reward": 1 if not failed else 0, "failed": failed,
|
| 237 |
+
"n_tool_calls": len(trace),
|
| 238 |
+
"servers_used": sorted({r['server'] for r in trace})}
|
| 239 |
+
|
| 240 |
+
def steps_of(task_dir):
|
| 241 |
+
"""Multi-step tasks (Harbor [[steps]] shape): steps/NN/{instruction.md,checks.json,walk.json}.
|
| 242 |
+
Step 0 is the task root; later steps run in the SAME world, so state carries across turns."""
|
| 243 |
+
d = Path(task_dir) / "steps"
|
| 244 |
+
return sorted(p for p in d.glob("*") if (p / "checks.json").exists()) if d.is_dir() else []
|
| 245 |
+
|
| 246 |
+
def verify_all(task_dir, run_dir):
|
| 247 |
+
"""Verify the root step plus every later step; reward 1 only if all pass."""
|
| 248 |
+
res = verify(task_dir, run_dir)
|
| 249 |
+
out = {"reward": res["reward"], "failed": list(res["failed"]),
|
| 250 |
+
"n_tool_calls": res["n_tool_calls"], "servers_used": res["servers_used"], "steps": 1}
|
| 251 |
+
for s in steps_of(task_dir):
|
| 252 |
+
r = verify(s, run_dir)
|
| 253 |
+
out["steps"] += 1
|
| 254 |
+
out["failed"] += [f"{s.name}:{f}" for f in r["failed"]]
|
| 255 |
+
out["reward"] = min(out["reward"], r["reward"])
|
| 256 |
+
return out
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
import argparse
|
| 260 |
+
ap = argparse.ArgumentParser()
|
| 261 |
+
ap.add_argument("--task-dir", required=True); ap.add_argument("--run-dir", required=True)
|
| 262 |
+
a = ap.parse_args()
|
| 263 |
+
print(json.dumps(verify_all(a.task_dir, a.run_dir)))
|