Files
obsidian-wiki/obsidian_wiki/mcp_business.py
T
Codex 6c451c3eb6 feat(mcp): separate direct order queries from wiki tools
Add an opt-in business group with schema, template, guarded SQL, and status tools. Reuse existing order statistics through read-only SQLite connections without OpenCode or wiki retrieval.

Add tools set for switching enabled groups with one restart. Gate file diagnostics with file-assets and document business-only operation while retaining the independent Kingdee sync task.

Validation: 217 unit tests passed; business tool tests rerun after read-only annotations. Live authenticated MCP schema/status/template/SQL calls passed, ask_wiki was unavailable, uploads returned 404, and unauthenticated requests returned 401.
2026-10-31 06:47:43 +00:00

135 lines
5.6 KiB
Python

"""Direct business MCP tools, independent of Wiki retrieval and OpenCode."""
from __future__ import annotations
import sqlite3
from pathlib import Path
from typing import Any, Callable
from obsidian_wiki import business_facts as facts
BUSINESS_TOOLS = [
"get_business_schema",
"query_business_template",
"execute_business_sql",
"get_business_status",
]
TEMPLATE_PARAMETERS = {
"year", "month", "start_date", "end_date", "end_date_exclusive",
"limit", "granularity", "staff_role_scope", "customer", "product", "staff",
"org", "department", "project", "warehouse", "billstatus", "orderstatus",
"closestatus", "currency", "include_internal_orders",
}
class BusinessQueries:
def __init__(self, db_path: Path, *, defaults: dict[str, Any] | None = None):
self.db_path = db_path.expanduser().resolve()
self.defaults = dict(defaults or {})
def schema(self) -> dict[str, Any]:
schema = facts.business_schema()
schema["purpose"] = "Query synchronized Kingdee sales orders directly. No Wiki or server-side LLM is involved."
schema["defaults"] = self.defaults
schema["read_only"] = True
schema["sql_guardrails"]["intercompany_filter"] = (
"Templates apply configured internal-party exclusions automatically. "
"Custom SQL must apply the same rule using defaults unless auditing internal transfers."
)
for template in schema["templates"]:
template["optional_parameters"] = [
p for p in template["optional_parameters"]
if p not in {"internal_parties", "internal_party_ids"}
]
return schema
def _read(self, operation: Callable[[], dict[str, Any]]) -> dict[str, Any]:
with facts.read_only_queries():
try:
facts.init_db(self.db_path)
return operation()
except sqlite3.Error as exc:
# Do not leak local database paths or query fragments through MCP errors.
raise RuntimeError("Business query failed; check the schema, query permissions, and sync status.") from exc
def _freshness(self) -> dict[str, Any]:
last_sync = facts.last_successful_sync(self.db_path)
stale = facts.sync_is_stale(last_sync)
return {
"data_source": "kingdee_sales_orders",
"last_sync": last_sync,
"is_stale": stale,
"warnings": ["Data may be incomplete since the last successful sync."] if stale else [],
}
def status(self) -> dict[str, Any]:
if not self.db_path.is_file():
return {"available": False, "last_sync": "", "is_stale": True,
"warnings": ["Business database is unavailable; run the operator's Kingdee sync first."]}
def read():
with facts.connect(self.db_path) as conn:
row = conn.execute(
"SELECT COUNT(*) AS stored_orders, MIN(order_date) AS earliest_order_date, "
"MAX(order_date) AS latest_order_date FROM orders"
).fetchone()
return {"available": True, **dict(row), **self._freshness()}
return self._read(read)
def template(self, template_name: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
params = dict(params or {})
unknown = params.keys() - TEMPLATE_PARAMETERS
if unknown:
raise ValueError("Unsupported template parameters: " + ", ".join(sorted(unknown)))
effective = {**self.defaults, **params}
def read():
result = facts.execute_business_template(self.db_path, template_name, **effective)
result.update(self._freshness())
return result
return self._read(read)
def sql(self, sql: str, limit: int = facts.SQL_DEFAULT_LIMIT) -> dict[str, Any]:
def read():
result = facts.execute_business_sql(self.db_path, sql, limit=limit)
result.update(self._freshness())
result["counting_basis"] = "Custom SQL; internal-party exclusions must be expressed in the query."
return result
return self._read(read)
def register_business_tools(server: Any, queries: BusinessQueries) -> None:
from mcp.types import ToolAnnotations
read_only = ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False)
@server.tool(annotations=read_only)
def get_business_schema() -> dict[str, Any]:
"""Read sales-order tables, query templates, parameters, and counting rules before querying."""
return queries.schema()
@server.tool(annotations=read_only)
def query_business_template(template_name: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
"""Query orders, sales, customers, products, staff, or delivery plans. Prefer this over SQL.
Read get_business_schema first. params needs year/month or start_date/end_date_exclusive,
with optional customer/product/staff filters. Returns results and last sync time.
"""
return queries.template(template_name, params)
@server.tool(annotations=read_only)
def execute_business_sql(sql: str, limit: int = facts.SQL_DEFAULT_LIMIT) -> dict[str, Any]:
"""Run one guarded SELECT/WITH SELECT when no template fits. No raw JSON or writes.
Apply internal-party exclusion rules from get_business_schema for normal sales metrics.
"""
return queries.sql(sql, limit)
@server.tool(annotations=read_only)
def get_business_status() -> dict[str, Any]:
"""Check order-data availability, stored order date range, and last successful sync."""
return queries.status()