Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(mcp): fix decision persistence/query, add NER model params and graph tools
修宴0e4063993045
diff --git a/semantica/mcp_server/__init__.py b/semantica/mcp_server/__init__.pyindex 6f642bab..c3005140 100644--- a/semantica/mcp_server/__init__.py+++ b/semantica/mcp_server/__init__.py@@ -65,7 +65,7 @@ def _get_graph():kg_path = os.environ.get("SEMANTICA_KG_PATH")if kg_path and os.path.exists(kg_path):try:- _graph.load(kg_path)+ _graph.load_from_file(kg_path)log.info("Loaded graph from %s", kg_path)except Exception as exc:log.warning("Could not load graph from %s: %s", kg_path, exc)@@ -77,30 +77,54 @@ def _get_graph():# ══════════════════════════════════════════════════════════════════════════════def _tool_extract_entities(args: dict) -> dict:- """Extract named entities from text."""+ """Extract named entities from text.++ Optional ``model`` (spaCy pipeline, e.g. ``zh_core_web_sm`` for Chinese)+ and ``language`` allow non-English NER; defaults to the Semantica English+ pipeline when omitted. ``method`` defaults to ``ml`` (spaCy); other+ options are ``huggingface``, ``llm``, ``pattern``.+ """text = args.get("text", "")if not text:return {"error": "text is required"}from semantica.semantic_extract import NamedEntityRecognizer- entities = NamedEntityRecognizer().extract_entities(text)+ init_kwargs = {}+ for k in ("model", "language", "confidence_threshold"):+ if args.get(k) is not None:+ init_kwargs[k] = args[k]+ method = args.get("method", "ml")+ ner = NamedEntityRecognizer(methods=[method], **init_kwargs)+ entities = ner.extract_entities(text)return {"entities": [- {"label": getattr(e, "label", str(e)),- "type": getattr(e, "type", None),- "start": getattr(e, "start", None),- "end": getattr(e, "end", None)}+ {"text": getattr(e, "text", ""),+ "label": getattr(e, "label", ""),+ "type": getattr(e, "label", None),+ "start": getattr(e, "start_char", getattr(e, "start", None)),+ "end": getattr(e, "end_char", getattr(e, "end", None)),+ "confidence": getattr(e, "confidence", 1.0)}for e in (entities or [])]}def _tool_extract_relations(args: dict) -> dict:- """Extract relations and triplets from text."""+ """Extract relations and triplets from text.++ Optional ``model``/``language`` enable non-English extraction.+ ``method`` defaults to ``pattern``; ``dependency`` uses spaCy syntactic+ parsing (requires a spaCy model, e.g. ``zh_core_web_sm``).+ """text = args.get("text", "")if not text:return {"error": "text is required"}from semantica.semantic_extract import RelationExtractor, TripletExtractor- relations = RelationExtractor().extract_relations(text)+ rel_kwargs = {}+ for k in ("model", "language"):+ if args.get(k) is not None:+ rel_kwargs[k] = args[k]+ method = args.get("method", "pattern")+ relations = RelationExtractor(method=method, **rel_kwargs).extract_relations(text)triplets = TripletExtractor().extract_triplets(text)return {"relations": [@@ -147,10 +171,12 @@ def _tool_query_decisions(args: dict) -> dict:graph = _get_graph()try:if query:- results = graph.find_similar_decisions(query, max_results=limit)+ results = graph.find_similar_decisions(query, max_results=limit, min_similarity=0.05)elif category:nodes = graph.find_nodes(node_type="decision")- results = [n for n in nodes if n.get("category") == category][:limit]+ results = [n for n in nodes+ if n.get("category") == category+ or n.get("metadata", {}).get("category") == category][:limit]else:results = graph.find_nodes(node_type="decision")[:limit]return {"decisions": results if isinstance(results, list) else list(results)}@@ -166,7 +192,9 @@ def _tool_find_precedents(args: dict) -> dict:max_results = int(args.get("max_results", 5))graph = _get_graph()try:- precedents = graph.find_similar_decisions(scenario, max_results=max_results)+ min_similarity = float(args.get("min_similarity", 0.05))+ precedents = graph.find_similar_decisions(+ scenario, max_results=max_results, min_similarity=min_similarity)return {"precedents": precedents if isinstance(precedents, list) else list(precedents)}except Exception as exc:return {"error": str(exc), "precedents": []}@@ -281,6 +309,145 @@ def _tool_get_graph_summary(args: dict) -> dict:return {"error": str(exc), "graph_ready": False}+def _tool_update_node(args: dict) -> dict:+ """Update properties of an existing node and persist to SEMANTICA_KG_PATH.++ Common use: mark an action node's status (todo/doing/done) with an+ optional note. The graph is mutated in-memory then saved back to the+ file it was loaded from, so changes survive server restarts.+ """+ node_id = args.get("node_id", "")+ if not node_id:+ return {"error": "node_id is required"}+ properties = args.get("properties", {})+ if not isinstance(properties, dict) or not properties:+ return {"error": "properties (non-empty object) is required"}+ graph = _get_graph()+ try:+ if not graph.find_node(node_id):+ return {"error": f"node '{node_id}' not found"}+ graph.add_node_attribute(node_id, properties)+ # Persist back to disk so the change survives restarts+ kg_path = os.environ.get("SEMANTICA_KG_PATH")+ if kg_path:+ graph.save_to_file(kg_path)+ persisted = True+ else:+ persisted = False+ updated = graph.find_node(node_id)+ return {+ "status": "updated",+ "node_id": node_id,+ "properties": {k: (updated.get("metadata") or {}).get(k) for k in properties},+ "persisted": persisted,+ }+ except Exception as exc:+ return {"error": str(exc)}+++def _tool_delete_node(args: dict) -> dict:+ """Archive a node (soft delete) and persist to SEMANTICA_KG_PATH.++ The node is kept in the graph for history but marked status='archived'.+ Use to retire an action you no longer actively track.+ """+ node_id = args.get("node_id", "")+ if not node_id:+ return {"error": "node_id is required"}+ graph = _get_graph()+ try:+ if not graph.find_node(node_id):+ return {"error": f"node '{node_id}' not found"}+ graph.add_node_attribute(node_id, {"status": "archived"})+ kg_path = os.environ.get("SEMANTICA_KG_PATH")+ if kg_path:+ graph.save_to_file(kg_path)+ return {"status": "archived", "node_id": node_id, "persisted": bool(kg_path)}+ except Exception as exc:+ return {"error": str(exc)}+++def _tool_query_graph(args: dict) -> dict:+ """Query the live knowledge graph: node detail, neighbours, or keyword search.++ mode:+ - "node" : get one node by id (needs node_id)+ - "neighbors": traverse up to `depth` hops from node_id (default depth=1)+ - "search" : keyword search over node id+content (needs query)+ """+ graph = _get_graph()+ mode = args.get("mode", "neighbors")+ try:+ if mode == "node":+ node_id = args.get("node_id", "")+ if not node_id:+ return {"error": "node_id is required"}+ node = graph.find_node(node_id)+ return {"node": node}++ if mode == "neighbors":+ node_id = args.get("node_id", "")+ if not node_id:+ return {"error": "node_id is required"}+ depth = int(args.get("depth", 1))+ rel_types = args.get("relationship_types")+ if isinstance(rel_types, str):+ rel_types = [rel_types]+ rel_set = set(rel_types) if rel_types else None+ limit = args.get("limit")+ limit = int(limit) if limit is not None else None+ depth = min(max(depth, 1), 5)+ # Out-edges (multi-hop) via get_neighbors+ nb = graph.get_neighbors(+ node_id, hops=depth, relationship_types=rel_types, limit=limit,+ )+ out = [+ {"id": n.get("id"), "type": n.get("type"),+ "content": n.get("content"),+ "relationship": n.get("relationship"),+ "direction": "out", "hop": n.get("hop", 1)}+ for n in (nb or [])+ ]+ # In-edges (1-hop): scan edges whose target == node_id+ inb = []+ for e in graph.find_edges():+ if e.get("target") != node_id:+ continue+ if rel_set is not None and e.get("type") not in rel_set:+ continue+ src_id = e.get("source")+ src = graph.find_node(src_id) or {}+ inb.append({"id": src_id, "type": src.get("type"),+ "content": src.get("content"),+ "relationship": e.get("type"),+ "direction": "in", "hop": 1})+ neighbors = out + inb+ if limit:+ neighbors = neighbors[:limit]+ return {"node_id": node_id, "depth": depth, "neighbors": neighbors}++ if mode == "search":+ q = (args.get("query") or "").lower()+ if not q:+ return {"error": "query is required"}+ node_type = args.get("node_type")+ limit = int(args.get("limit", 50))+ nodes = graph.find_nodes(node_type=node_type) if node_type else graph.find_nodes()+ hits = []+ for n in nodes:+ blob = f"{n.get('id','')} {n.get('content','')}".lower()+ if q in blob:+ hits.append({"id": n.get("id"), "type": n.get("type"),+ "content": n.get("content")})+ if len(hits) >= limit:+ break+ return {"query": q, "results": hits, "total": len(hits)}++ return {"error": f"unknown mode '{mode}': use node|neighbors|search"}+ except Exception as exc:+ return {"error": str(exc)}++# ══════════════════════════════════════════════════════════════════════════════# MCP protocol tables# ══════════════════════════════════════════════════════════════════════════════@@ -292,7 +459,11 @@ TOOLS = ["inputSchema": {"type": "object","properties": {- "text": {"type": "string", "description": "Input text to extract entities from"}+ "text": {"type": "string", "description": "Input text to extract entities from"},+ "model": {"type": "string", "description": "spaCy model name, e.g. 'zh_core_web_sm' for Chinese, 'en_core_web_sm' for English. Defaults to English pipeline."},+ "language": {"type": "string", "description": "Language code, e.g. 'zh', 'en'."},+ "method": {"type": "string", "description": "Extraction method: 'ml' (spaCy, default), 'huggingface', 'llm', 'pattern'."},+ "confidence_threshold": {"type": "number", "description": "Minimum confidence 0-1 (default 0.5)."}},"required": ["text"],},@@ -304,7 +475,10 @@ TOOLS = ["inputSchema": {"type": "object","properties": {- "text": {"type": "string", "description": "Input text to extract relations from"}+ "text": {"type": "string", "description": "Input text to extract relations from"},+ "model": {"type": "string", "description": "spaCy model name for dependency parsing, e.g. 'zh_core_web_sm'."},+ "language": {"type": "string", "description": "Language code, e.g. 'zh'."},+ "method": {"type": "string", "description": "Extraction method: 'pattern' (default), 'dependency', 'cooccurrence', 'huggingface', 'llm'."}},"required": ["text"],},@@ -445,6 +619,48 @@ TOOLS = ["inputSchema": {"type": "object", "properties": {}},"_handler": _tool_get_graph_summary,},+ {+ "name": "query_graph",+ "description": "Query the live knowledge graph: get a node, traverse its neighbours (up to 5 hops), or keyword-search nodes by id+content.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "mode": {"type": "string", "description": "node | neighbors | search (default: neighbors)"},+ "node_id": {"type": "string", "description": "Node id (required for node/neighbors mode)"},+ "depth": {"type": "integer", "description": "Hop depth for neighbors (1-5, default 1)"},+ "relationship_types": {"type": "array", "items": {"type": "string"}, "description": "Optional filter by edge type(s)"},+ "query": {"type": "string", "description": "Keyword for search mode (matched against node id+content)"},+ "node_type": {"type": "string", "description": "Optional node_type filter for search mode"},+ "limit": {"type": "integer", "description": "Max results for neighbors/search"}+ },+ },+ "_handler": _tool_query_graph,+ },+ {+ "name": "update_node",+ "description": "Update properties of an existing node (e.g. mark an action todo/doing/done with a note) and persist to SEMANTICA_KG_PATH.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "node_id": {"type": "string", "description": "Node id to update"},+ "properties": {"type": "object", "description": "Property key-values to merge onto the node, e.g. {\"status\":\"done\",\"updated_at\":\"2026-08-13\",\"note\":\"...\"}"}+ },+ "required": ["node_id", "properties"],+ },+ "_handler": _tool_update_node,+ },+ {+ "name": "delete_node",+ "description": "Archive a node (soft delete: marks status='archived', keeps it for history) and persist to SEMANTICA_KG_PATH. Use to retire an action you no longer track.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "node_id": {"type": "string", "description": "Node id to delete"}+ },+ "required": ["node_id"],+ },+ "_handler": _tool_delete_node,+ },]RESOURCES = [