glosslayer 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ """MCP server: lets AI agents read the accepted model and propose changes.
2
+
3
+ AI can *read* (with confidentiality enforced by :mod:`glosslayer.ai`) and *propose*.
4
+ It can never accept: proposals land in the review queue as ``ai:<agent>``.
5
+
6
+ gloss mcp --db sqlite:///gloss.db --agent claude
7
+
8
+ Embedded in a host, pass a view bound to the person the agent works for and the agent
9
+ reads what that person may read, capped at the AI level:
10
+
11
+ build_server(g.as_actor(Human(user.id)), agent="claude")
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any
17
+
18
+ from . import ai
19
+ from .ids import SubjectId
20
+ from .ledger import Gloss, Proposal
21
+ from .model import ATTRIBUTES
22
+
23
+
24
+ def _propose_doc() -> str:
25
+ return (
26
+ "Propose a semantic fact for human review. It is NOT applied until a person accepts it. "
27
+ "Subject examples: 'dataset:sales.orders', 'field:sales.orders/amount', 'metric:total_revenue', "
28
+ "'metric:sales.orders/avg_price', 'metric:sales::revenue' (owned by the namespace 'sales'), "
29
+ "'relationship:sales::orders_customers'. Valid attributes per subject kind: "
30
+ + "; ".join(f"{k.value}: {', '.join(sorted(v))}" for k, v in ATTRIBUTES.items())
31
+ + ". Give a confidence between 0 and 1 and a short rationale. Facts that belong together "
32
+ "(the four parts of a relationship, the parts of a metric) should share a `group` string."
33
+ )
34
+
35
+
36
+ def _server_class() -> Any:
37
+ try: # mcp >= 2
38
+ from mcp.server.mcpserver import MCPServer
39
+
40
+ return MCPServer
41
+ except ImportError: # mcp 1.x
42
+ try:
43
+ from mcp.server.fastmcp import FastMCP
44
+
45
+ return FastMCP
46
+ except ImportError as exc:
47
+ raise RuntimeError("The MCP server needs the 'mcp' extra: pip install glosslayer[mcp]") from exc
48
+
49
+
50
+ def build_server(gloss: Gloss, *, agent: str = "assistant") -> Any:
51
+ """An MCP server whose tools read and propose as ``ai:<agent>``, or as the bound person via that agent."""
52
+ Server = _server_class()
53
+ server = Server(
54
+ name="gloss",
55
+ instructions=(
56
+ "Gloss holds the reviewed semantic model of this organisation's data: datasets, fields, "
57
+ "relationships and metrics with their agreed meaning. Call get_model_context before writing "
58
+ "queries or answering questions about data, and search_model to find the right dataset or metric. "
59
+ "If a definition is missing or wrong, call propose_fact; a person will review it. "
60
+ "Items marked redacted exist but are confidential: do not guess their contents."
61
+ ),
62
+ )
63
+ source = f"ai:{agent}"
64
+ # An unbound ledger: the agent acts for itself. A person's view: the person acts through the agent.
65
+ view = gloss.as_actor(source) if gloss.actor is None else gloss.as_actor(gloss.actor, via=source)
66
+
67
+ @server.tool()
68
+ def search_model(text: str, limit: int = 20, kinds: list[str] | None = None) -> list[dict[str, Any]]:
69
+ """Search the agreed data model: tables, columns, relationships, metrics and semantic types,
70
+ by name, description or synonym. Plain questions work ("revenue per country"); filler words are
71
+ ignored and prefixes count. Hits matching every word come first. If none do, hits matching some
72
+ words are returned, each with `matched` listing which. Misspellings are corrected (`did_you_mean`).
73
+ `kinds` narrows the search, e.g. ["metric"] or ["field", "dataset"]. Items marked redacted exist
74
+ but are confidential: don't guess their contents. Follow up with get_model_context for details."""
75
+ return ai.search(view, text, limit=limit, kinds=kinds)
76
+
77
+ @server.tool()
78
+ def get_model_context(datasets: list[str] | None = None) -> dict[str, Any]:
79
+ """Return the accepted semantic model (optionally only the given dataset keys) as compact JSON."""
80
+ return ai.model_context(view, datasets=datasets)
81
+
82
+ @server.tool(description=_propose_doc())
83
+ def propose_fact(
84
+ subject: str,
85
+ attribute: str,
86
+ value: Any,
87
+ confidence: float | None = None,
88
+ rationale: str | None = None,
89
+ group: str | None = None,
90
+ ) -> dict[str, Any]:
91
+ SubjectId.parse(subject)
92
+ evidence = [{"rationale": rationale}] if rationale else []
93
+ res = view.propose_many(
94
+ [Proposal(subject, attribute, value, confidence, evidence, rationale, group)], source=source
95
+ )[0]
96
+ return {"outcome": res.outcome, "id": res.assertion.id, "status": res.assertion.status.value}
97
+
98
+ @server.tool()
99
+ def review_status(subject: str) -> list[dict[str, Any]]:
100
+ """Every fact about one subject with its review status: what is agreed and what is still open."""
101
+ return ai.review_status(view, subject)
102
+
103
+ return server
104
+
105
+
106
+ def run(gloss: Gloss, *, agent: str = "assistant", transport: str = "stdio") -> None:
107
+ """Build the MCP server and serve it over ``transport`` (stdio, sse or streamable-http) until stopped."""
108
+ build_server(gloss, agent=agent).run(transport=transport)