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.
This commit is contained in:
@@ -11,6 +11,8 @@ import hashlib
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -20,6 +22,17 @@ from obsidian_wiki.kingdee_api import fetch_kingdee_sales_orders, load_kingdee_c
|
||||
|
||||
BUSINESS_DB_RELATIVE_PATH = Path("_meta") / "business-facts.sqlite"
|
||||
KINGDEE_SYNC_STATE_SOURCE = "kingdee_sales_orders_modifytime"
|
||||
_READ_ONLY = ContextVar("business_facts_read_only", default=False)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def read_only_queries():
|
||||
"""Reuse business queries without creating/migrating the sync-owned database."""
|
||||
token = _READ_ONLY.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_READ_ONLY.reset(token)
|
||||
|
||||
ORDER_COLUMNS = (
|
||||
"order_id",
|
||||
@@ -166,6 +179,11 @@ def business_db_path_for_vault(vault_path: str | Path) -> Path:
|
||||
|
||||
|
||||
def connect(db_path: Path) -> sqlite3.Connection:
|
||||
if _READ_ONLY.get():
|
||||
conn = sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA query_only=ON")
|
||||
return conn
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -175,6 +193,10 @@ def connect(db_path: Path) -> sqlite3.Connection:
|
||||
|
||||
|
||||
def init_db(db_path: Path) -> None:
|
||||
if _READ_ONLY.get():
|
||||
if not db_path.is_file():
|
||||
raise RuntimeError("Business database is unavailable; run the operator's Kingdee sync first.")
|
||||
return
|
||||
with connect(db_path) as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""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()
|
||||
+85
-39
@@ -16,6 +16,8 @@ from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from obsidian_wiki import __version__
|
||||
from obsidian_wiki.config import config_value, resolve_vault_path
|
||||
from obsidian_wiki.business_facts import business_db_path_for_vault
|
||||
from obsidian_wiki.mcp_business import BUSINESS_TOOLS, BusinessQueries, register_business_tools
|
||||
from obsidian_wiki.file_assets import clean_config_value, db_path_for_vault, registry_path_for_vault
|
||||
from obsidian_wiki.mcp_ingest import (
|
||||
DEFAULT_INGEST_JOB_TIMEOUT_SECONDS,
|
||||
@@ -63,13 +65,14 @@ PUBLIC_UPLOAD_URL_ENV = "OBSIDIAN_MCP_INGEST_PUBLIC_UPLOAD_URL"
|
||||
ALLOWED_HOSTS_ENV = "OBSIDIAN_MCP_ALLOWED_HOSTS"
|
||||
ALLOWED_ORIGINS_ENV = "OBSIDIAN_MCP_ALLOWED_ORIGINS"
|
||||
MCP_SERVER_NAME = "wiki-file-assets"
|
||||
CAPABILITIES_SCHEMA_VERSION = 3
|
||||
TOOLS_VERSION = 3
|
||||
CAPABILITIES_SCHEMA_VERSION = 4
|
||||
TOOLS_VERSION = 4
|
||||
TOOL_FILE_ASSETS = "file-assets"
|
||||
TOOL_INGEST = "ingest"
|
||||
TOOL_QUERY = "query"
|
||||
TOOL_BUSINESS = "business"
|
||||
DEFAULT_ENABLED_TOOLS = {TOOL_FILE_ASSETS}
|
||||
AVAILABLE_TOOLS = {TOOL_FILE_ASSETS, TOOL_INGEST, TOOL_QUERY}
|
||||
AVAILABLE_TOOLS = {TOOL_FILE_ASSETS, TOOL_INGEST, TOOL_QUERY, TOOL_BUSINESS}
|
||||
|
||||
|
||||
def text_note_file_name(title: str | None) -> str:
|
||||
@@ -114,6 +117,8 @@ def normalize_tool_name(name: str) -> str:
|
||||
"upload": TOOL_INGEST,
|
||||
"uploads": TOOL_INGEST,
|
||||
"opencode-ingest": TOOL_INGEST,
|
||||
"business": TOOL_BUSINESS,
|
||||
"orders": TOOL_BUSINESS,
|
||||
"query": TOOL_QUERY,
|
||||
"wiki-query": TOOL_QUERY,
|
||||
"ask": TOOL_QUERY,
|
||||
@@ -205,6 +210,8 @@ def create_server(
|
||||
enable_file_assets: bool = True,
|
||||
enable_ingest: bool = False,
|
||||
enable_query: bool = False,
|
||||
enable_business: bool = False,
|
||||
business_db_path: str | Path | None = None,
|
||||
project_root: str | Path | None = None,
|
||||
ingest_runtime_root: str | Path | None = None,
|
||||
query_runtime_root: str | Path | None = None,
|
||||
@@ -265,39 +272,41 @@ def create_server(
|
||||
transport_security=transport_security,
|
||||
)
|
||||
|
||||
@server.tool()
|
||||
def file_index_status() -> dict[str, Any]:
|
||||
"""Show the configured vault, file index, registry, and MCP limits."""
|
||||
registry = registry_path_for_vault(vault)
|
||||
status = {
|
||||
"db_exists": db.is_file(),
|
||||
"registry_exists": registry.is_file(),
|
||||
"source_registry_records": len(load_registry_by_file_id(vault)),
|
||||
"profile_name": profile_name,
|
||||
"max_file_bytes": max_file_bytes,
|
||||
"expose_paths": expose_paths,
|
||||
"allow_source_files": allow_source_files,
|
||||
"enabled_tools": sorted(
|
||||
([TOOL_FILE_ASSETS] if enable_file_assets else [])
|
||||
+ ([TOOL_INGEST] if enable_ingest else [])
|
||||
+ ([TOOL_QUERY] if enable_query else [])
|
||||
),
|
||||
"ingest_enabled": enable_ingest,
|
||||
"query_enabled": enable_query,
|
||||
"ingest_opencode_model": ingest_opencode_model or "",
|
||||
"ingest_opencode_variant": ingest_opencode_variant or "",
|
||||
"query_opencode_model": query_opencode_model or "",
|
||||
"query_opencode_variant": query_opencode_variant or "",
|
||||
}
|
||||
if expose_paths:
|
||||
status.update(
|
||||
{
|
||||
"vault_path": str(vault),
|
||||
"db_path": str(db),
|
||||
"registry_path": str(registry),
|
||||
}
|
||||
)
|
||||
return status
|
||||
if enable_file_assets:
|
||||
@server.tool()
|
||||
def file_index_status() -> dict[str, Any]:
|
||||
"""Show the configured vault, file index, registry, and MCP limits."""
|
||||
registry = registry_path_for_vault(vault)
|
||||
status = {
|
||||
"db_exists": db.is_file(),
|
||||
"registry_exists": registry.is_file(),
|
||||
"source_registry_records": len(load_registry_by_file_id(vault)),
|
||||
"profile_name": profile_name,
|
||||
"max_file_bytes": max_file_bytes,
|
||||
"expose_paths": expose_paths,
|
||||
"allow_source_files": allow_source_files,
|
||||
"enabled_tools": sorted(
|
||||
([TOOL_FILE_ASSETS] if enable_file_assets else [])
|
||||
+ ([TOOL_INGEST] if enable_ingest else [])
|
||||
+ ([TOOL_QUERY] if enable_query else [])
|
||||
+ ([TOOL_BUSINESS] if enable_business else [])
|
||||
),
|
||||
"ingest_enabled": enable_ingest,
|
||||
"query_enabled": enable_query,
|
||||
"ingest_opencode_model": ingest_opencode_model or "",
|
||||
"ingest_opencode_variant": ingest_opencode_variant or "",
|
||||
"query_opencode_model": query_opencode_model or "",
|
||||
"query_opencode_variant": query_opencode_variant or "",
|
||||
}
|
||||
if expose_paths:
|
||||
status.update(
|
||||
{
|
||||
"vault_path": str(vault),
|
||||
"db_path": str(db),
|
||||
"registry_path": str(registry),
|
||||
}
|
||||
)
|
||||
return status
|
||||
|
||||
@server.tool()
|
||||
def get_mcp_capabilities() -> dict[str, Any]:
|
||||
@@ -306,6 +315,7 @@ def create_server(
|
||||
([TOOL_FILE_ASSETS] if enable_file_assets else [])
|
||||
+ ([TOOL_INGEST] if enable_ingest else [])
|
||||
+ ([TOOL_QUERY] if enable_query else [])
|
||||
+ ([TOOL_BUSINESS] if enable_business else [])
|
||||
)
|
||||
return {
|
||||
"server_name": MCP_SERVER_NAME,
|
||||
@@ -318,8 +328,17 @@ def create_server(
|
||||
enable_file_assets=enable_file_assets,
|
||||
enable_ingest=enable_ingest,
|
||||
enable_query=enable_query,
|
||||
enable_business=enable_business,
|
||||
),
|
||||
"file_index": _file_index_capabilities(vault, db),
|
||||
"file_index": _file_index_capabilities(vault, db) if enable_file_assets else {"enabled": False},
|
||||
"business": {
|
||||
"enabled": enable_business,
|
||||
"tools": BUSINESS_TOOLS if enable_business else [],
|
||||
"preferred_tool": "query_business_template" if enable_business else None,
|
||||
"read_only": True,
|
||||
"requires_opencode": False,
|
||||
"requires_wiki": False,
|
||||
},
|
||||
"file_assets": {
|
||||
"enabled": enable_file_assets,
|
||||
"tools": (
|
||||
@@ -462,6 +481,20 @@ def create_server(
|
||||
},
|
||||
}
|
||||
|
||||
if enable_business:
|
||||
configured_db = business_db_path or runtime_config_value("OBSIDIAN_MCP_BUSINESS_DB", "")
|
||||
business_db = Path(configured_db).expanduser() if configured_db else business_db_path_for_vault(vault)
|
||||
defaults = {}
|
||||
for key, env in (
|
||||
("internal_parties", "OBSIDIAN_BUSINESS_INTERNAL_PARTIES"),
|
||||
("internal_party_ids", "OBSIDIAN_BUSINESS_INTERNAL_PARTY_IDS"),
|
||||
("include_internal_orders", "OBSIDIAN_BUSINESS_INCLUDE_INTERNAL_ORDERS"),
|
||||
):
|
||||
value = runtime_config_value(env, "")
|
||||
if value:
|
||||
defaults[key] = value
|
||||
register_business_tools(server, BusinessQueries(business_db, defaults=defaults))
|
||||
|
||||
owns_ingest_manager = False
|
||||
if enable_ingest:
|
||||
if ingest_manager is None:
|
||||
@@ -1290,6 +1323,8 @@ def run_http_server(
|
||||
enable_file_assets: bool = True,
|
||||
enable_ingest: bool = False,
|
||||
enable_query: bool = False,
|
||||
enable_business: bool = False,
|
||||
business_db_path: str | Path | None = None,
|
||||
project_root: str | Path | None = None,
|
||||
ingest_runtime_root: str | Path | None = None,
|
||||
query_runtime_root: str | Path | None = None,
|
||||
@@ -1375,6 +1410,8 @@ def run_http_server(
|
||||
enable_file_assets=enable_file_assets,
|
||||
enable_ingest=enable_ingest,
|
||||
enable_query=enable_query,
|
||||
enable_business=enable_business,
|
||||
business_db_path=business_db_path,
|
||||
project_root=project_root,
|
||||
ingest_runtime_root=ingest_runtime_root,
|
||||
query_runtime_root=query_runtime_root,
|
||||
@@ -1414,6 +1451,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="obsidian-wiki-mcp", description="Run the obsidian-wiki MCP server")
|
||||
parser.add_argument("--vault", metavar="PATH", help="absolute path to the Obsidian vault")
|
||||
parser.add_argument("--db", metavar="PATH", help="SQLite file asset index path")
|
||||
parser.add_argument("--business-db", metavar="PATH", help="Existing sales-order SQLite database (independent of the file index)")
|
||||
parser.add_argument("--profile", default=None, help=f"bot profile name, default: {DEFAULT_PROFILE_NAME}")
|
||||
parser.add_argument("--max-file-bytes", type=int, default=None, help="maximum resource size, 0 disables the limit")
|
||||
parser.add_argument(
|
||||
@@ -1479,6 +1517,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
enable_file_assets = TOOL_FILE_ASSETS in enabled_tools
|
||||
enable_ingest = TOOL_INGEST in enabled_tools
|
||||
enable_query = TOOL_QUERY in enabled_tools
|
||||
enable_business = TOOL_BUSINESS in enabled_tools
|
||||
business_db_path = args.business_db or runtime_config_value("OBSIDIAN_MCP_BUSINESS_DB", "") or None
|
||||
ingest_max_file_bytes = runtime_config_int("OBSIDIAN_MCP_INGEST_MAX_FILE_BYTES", DEFAULT_INGEST_MAX_FILE_BYTES)
|
||||
ingest_max_chunk_bytes = runtime_config_int("OBSIDIAN_MCP_INGEST_MAX_CHUNK_BYTES", DEFAULT_INGEST_MAX_CHUNK_BYTES)
|
||||
ingest_max_files_per_job = runtime_config_int(
|
||||
@@ -1529,6 +1569,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
enable_file_assets=enable_file_assets,
|
||||
enable_ingest=enable_ingest,
|
||||
enable_query=enable_query,
|
||||
enable_business=enable_business,
|
||||
business_db_path=business_db_path,
|
||||
project_root=Path.cwd(),
|
||||
ingest_runtime_root=ingest_runtime_root,
|
||||
query_runtime_root=query_runtime_root,
|
||||
@@ -1571,6 +1613,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
enable_file_assets=enable_file_assets,
|
||||
enable_ingest=enable_ingest,
|
||||
enable_query=enable_query,
|
||||
enable_business=enable_business,
|
||||
business_db_path=business_db_path,
|
||||
project_root=Path.cwd(),
|
||||
ingest_runtime_root=ingest_runtime_root,
|
||||
query_runtime_root=query_runtime_root,
|
||||
@@ -1630,8 +1674,10 @@ def _upload_url_from_public_base(public_base_url: str, upload_path: str) -> str
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, upload_path, "", ""))
|
||||
|
||||
|
||||
def _recommended_first_steps(*, enable_file_assets: bool, enable_ingest: bool, enable_query: bool) -> list[str]:
|
||||
def _recommended_first_steps(*, enable_file_assets: bool, enable_ingest: bool, enable_query: bool, enable_business: bool = False) -> list[str]:
|
||||
steps: list[str] = []
|
||||
if enable_business:
|
||||
steps.append("Use get_business_schema, then query_business_template for direct sales-order queries; get_business_status reports freshness.")
|
||||
if enable_query:
|
||||
steps.append("Use ask_wiki for ordinary wiki, business facts, or hybrid questions.")
|
||||
if enable_file_assets:
|
||||
@@ -1640,7 +1686,7 @@ def _recommended_first_steps(*, enable_file_assets: bool, enable_ingest: bool, e
|
||||
steps.append("Use ingest_text_note for short text notes.")
|
||||
steps.append("Use create_ingest_upload_ticket before remote HTTP file upload.")
|
||||
if not steps:
|
||||
steps.append("No optional MCP tool groups are enabled; ask the operator to enable file-assets, query, or ingest.")
|
||||
steps.append("No optional MCP tool groups are enabled; ask the operator to enable business, file-assets, query, or ingest.")
|
||||
return steps
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user