mirror of
https://github.com/semantica-agi/semantica.git
synced 2026-08-29 04:26:20 +00:00
feat(integrations): add OpenClaw plugin and integration module (#460)
- Add integrations/openclaw/ with OpenClawKGTool (REST) and OpenClawMCPConfig (mcporter.json generator) - Add plugins/.openclaw-plugin/ bundle (plugin.json, marketplace.json, README) with MCP + native tool support - Add OpenClaw badge to README header - Reorganize "Works With Every AI Tool" table into labeled groups: Native Plugin Bundle, MCP Server + Plugin, MCP Server, REST API Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
a1478af9c4
commit
60bf8ec75e
@@ -0,0 +1,137 @@
|
||||
# Semantica × OpenClaw Integration
|
||||
|
||||
Connect [OpenClaw](https://openclaw.ai) — the open-source personal AI agent — to Semantica's full knowledge-graph and decision-intelligence stack.
|
||||
|
||||
Two integration paths are available:
|
||||
|
||||
| Path | When to use |
|
||||
|---|---|
|
||||
| **MCP (recommended)** | OpenClaw Gateway is running; zero extra code needed |
|
||||
| **REST / native tool** | Embedding Semantica directly in a SOUL.md agent config |
|
||||
|
||||
---
|
||||
|
||||
## Path 1 — MCP Server (recommended)
|
||||
|
||||
### 1. Start the Semantica MCP server
|
||||
|
||||
```bash
|
||||
python -m semantica.mcp_server
|
||||
```
|
||||
|
||||
### 2. Add to `mcporter.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"semantica": {
|
||||
"command": "python",
|
||||
"args": ["-m", "semantica.mcp_server"],
|
||||
"transport": "stdio"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Restart the OpenClaw Gateway
|
||||
|
||||
```bash
|
||||
openclaw gateway restart
|
||||
```
|
||||
|
||||
All **12 Semantica tools** are now available to any OpenClaw agent:
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `extract_entities` | Named entity recognition from text |
|
||||
| `extract_relations` | Relation / triplet extraction from text |
|
||||
| `record_decision` | Record a decision with causal links |
|
||||
| `query_decisions` | Search recorded decisions |
|
||||
| `find_precedents` | Find past decisions similar to a query |
|
||||
| `get_causal_chain` | Trace cause-effect chains from a node |
|
||||
| `add_entity` | Add a node to the knowledge graph |
|
||||
| `add_relationship` | Add an edge between two nodes |
|
||||
| `run_reasoning` | Forward-chain rules over facts |
|
||||
| `get_graph_analytics` | Centrality, communities, topology stats |
|
||||
| `export_graph` | Export graph (JSON, RDF, GraphML, …) |
|
||||
| `get_graph_summary` | High-level graph overview |
|
||||
|
||||
**3 resources** are also exposed: `semantica://graph/summary`, `semantica://decisions/list`, `semantica://schema/info`.
|
||||
|
||||
---
|
||||
|
||||
## Path 2 — Native Tool (REST)
|
||||
|
||||
Use `OpenClawKGTool` when you prefer a direct Python integration without the MCP gateway.
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
pip install semantica[openclaw] # pulls in 'requests'
|
||||
```
|
||||
|
||||
### Quick start
|
||||
|
||||
```python
|
||||
from integrations.openclaw import OpenClawKGTool
|
||||
|
||||
tool = OpenClawKGTool(base_url="http://localhost:8000")
|
||||
|
||||
# Extract knowledge from text
|
||||
entities = tool.extract_entities("OpenClaw is an open-source AI agent built in Python.")
|
||||
relations = tool.extract_relations("Alice manages the OpenClaw project at Hawksight.")
|
||||
|
||||
# Record and query decisions
|
||||
tool.record_decision("Deploy model v2 to production", context="latency improved by 40%")
|
||||
precedents = tool.find_precedents("roll back production deployment")
|
||||
|
||||
# Graph analytics
|
||||
summary = tool.get_graph_summary()
|
||||
analytics = tool.get_graph_analytics()
|
||||
|
||||
# Export
|
||||
ttl = tool.export_graph(fmt="ttl")
|
||||
```
|
||||
|
||||
### Generate `mcporter.json` programmatically
|
||||
|
||||
```python
|
||||
from integrations.openclaw import OpenClawMCPConfig
|
||||
|
||||
cfg = OpenClawMCPConfig()
|
||||
print(cfg.to_json()) # → paste into mcporter.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SOUL.md agent snippet
|
||||
|
||||
Add Semantica to any OpenClaw agent by referencing the tool in your `SOUL.md`:
|
||||
|
||||
```markdown
|
||||
## Tools
|
||||
|
||||
- name: semantica_kg
|
||||
description: >
|
||||
Semantica knowledge-graph tool. Supports entity extraction, decision
|
||||
recording, graph querying, causal chain analysis, reasoning, and
|
||||
multi-format export.
|
||||
endpoint: http://localhost:8000
|
||||
auth: none
|
||||
|
||||
## Instructions
|
||||
|
||||
You have access to `semantica_kg`. Use it to:
|
||||
- Extract entities and relations from any text the user provides.
|
||||
- Record important decisions and retrieve precedents before recommending actions.
|
||||
- Run graph analytics and export results when the user asks for a summary.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.8+
|
||||
- `pip install semantica` (core)
|
||||
- `pip install semantica[openclaw]` (adds `requests` for the REST path)
|
||||
- OpenClaw ≥ latest — [openclaw.ai](https://openclaw.ai)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
Semantica × OpenClaw Integration
|
||||
==================================
|
||||
|
||||
First-class integration between the Semantica semantic intelligence stack and
|
||||
`OpenClaw <https://openclaw.ai>`_ — the open-source personal AI agent platform.
|
||||
|
||||
OpenClaw connects to external tools via MCP (Model Context Protocol). This
|
||||
integration exposes the full Semantica MCP surface (12 tools, 3 resources) to
|
||||
any OpenClaw agent and also ships a lightweight ``OpenClawKGTool`` that can be
|
||||
dropped directly into an OpenClaw SOUL.md tool-list as a native tool.
|
||||
|
||||
Public surface
|
||||
--------------
|
||||
OpenClawKGTool — Thin wrapper around the Semantica REST API usable as an
|
||||
OpenClaw native tool (no MCP gateway required)
|
||||
OpenClawMCPConfig — Helper that emits the ``mcporter.json`` snippet needed to
|
||||
wire Semantica's MCP server into an OpenClaw gateway
|
||||
|
||||
Quick start
|
||||
-----------
|
||||
pip install semantica
|
||||
|
||||
>>> from integrations.openclaw import OpenClawKGTool, OpenClawMCPConfig
|
||||
>>> print(OpenClawMCPConfig().to_json()) # paste into mcporter.json
|
||||
>>> tool = OpenClawKGTool(base_url="http://localhost:8000")
|
||||
>>> result = tool.extract("OpenClaw is an open-source AI agent framework.")
|
||||
|
||||
MCP quick start
|
||||
---------------
|
||||
Run the Semantica MCP server once::
|
||||
|
||||
python -m semantica.mcp_server
|
||||
|
||||
Then add the printed config snippet to your OpenClaw ``mcporter.json`` and
|
||||
restart the OpenClaw Gateway::
|
||||
|
||||
openclaw gateway restart
|
||||
|
||||
All 12 Semantica tools are then available as native OpenClaw agent tools.
|
||||
|
||||
Compatibility
|
||||
-------------
|
||||
Requires ``semantica >= 0.3.0``. The MCP path requires ``python >= 3.8`` and
|
||||
a running ``semantica.mcp_server`` instance. The REST path requires a running
|
||||
``semantica.server`` instance (``python -m semantica.server``, port 8000 by
|
||||
default).
|
||||
"""
|
||||
|
||||
from .mcp_tool import OpenClawKGTool, OpenClawMCPConfig
|
||||
|
||||
__all__ = [
|
||||
"OpenClawKGTool",
|
||||
"OpenClawMCPConfig",
|
||||
]
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
OpenClaw ↔ Semantica bridge
|
||||
============================
|
||||
|
||||
Two integration paths:
|
||||
|
||||
1. **MCP (recommended)** — ``OpenClawMCPConfig`` emits the ``mcporter.json``
|
||||
snippet that wires Semantica's MCP server into the OpenClaw Gateway.
|
||||
All 12 Semantica MCP tools become native OpenClaw agent tools with no
|
||||
extra code.
|
||||
|
||||
2. **REST** — ``OpenClawKGTool`` is a plain Python class that calls the
|
||||
Semantica REST API (port 8000) and can be registered as an OpenClaw
|
||||
native tool via SOUL.md ``tools:`` entries.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MCP config helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class OpenClawMCPConfig:
|
||||
"""
|
||||
Generates the ``mcporter.json`` entry needed to connect Semantica's MCP
|
||||
server to the OpenClaw Gateway.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
server_command:
|
||||
Shell command used to launch the Semantica MCP server.
|
||||
Defaults to ``"python -m semantica.mcp_server"``.
|
||||
transport:
|
||||
MCP transport protocol. OpenClaw supports ``"stdio"`` (default)
|
||||
and ``"sse"``.
|
||||
name:
|
||||
Key used in ``mcporter.json``. Defaults to ``"semantica"``.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> cfg = OpenClawMCPConfig()
|
||||
>>> print(cfg.to_json())
|
||||
# → paste into ~/.openclaw/mcporter.json, then:
|
||||
# → openclaw gateway restart
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_command: str = "python -m semantica.mcp_server",
|
||||
transport: str = "stdio",
|
||||
name: str = "semantica",
|
||||
) -> None:
|
||||
self.server_command = server_command
|
||||
self.transport = transport
|
||||
self.name = name
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Return the config as a plain dict."""
|
||||
parts = self.server_command.split()
|
||||
return {
|
||||
"mcpServers": {
|
||||
self.name: {
|
||||
"command": parts[0],
|
||||
"args": parts[1:],
|
||||
"transport": self.transport,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def to_json(self, indent: int = 2) -> str:
|
||||
"""Return the config as a JSON string."""
|
||||
return json.dumps(self.to_dict(), indent=indent)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"OpenClawMCPConfig(name={self.name!r}, transport={self.transport!r})"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# REST-based native tool
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class OpenClawKGTool:
|
||||
"""
|
||||
A Semantica knowledge-graph tool callable from an OpenClaw agent.
|
||||
|
||||
Wraps the Semantica REST API so that an OpenClaw agent configured with
|
||||
this tool (via SOUL.md ``tools:`` entries or programmatic registration)
|
||||
can extract entities, record decisions, query the graph, and more —
|
||||
without requiring the MCP gateway.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
base_url:
|
||||
Base URL of the running Semantica REST server.
|
||||
Defaults to ``"http://localhost:8000"``.
|
||||
timeout:
|
||||
Request timeout in seconds. Defaults to ``30``.
|
||||
|
||||
Notes
|
||||
-----
|
||||
``requests`` is used for HTTP calls. It is listed as an optional
|
||||
dependency under ``semantica[openclaw]``; install it with::
|
||||
|
||||
pip install semantica[openclaw]
|
||||
"""
|
||||
|
||||
TOOL_NAME = "semantica_kg"
|
||||
TOOL_DESCRIPTION = (
|
||||
"Semantica knowledge-graph tool. "
|
||||
"Supports entity extraction, decision recording, graph querying, "
|
||||
"causal chain analysis, reasoning, and multi-format export."
|
||||
)
|
||||
|
||||
def __init__(self, base_url: str = "http://localhost:8000", timeout: int = 30) -> None:
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self._session: Any = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _get_session(self) -> Any:
|
||||
if self._session is None:
|
||||
try:
|
||||
import requests
|
||||
self._session = requests.Session()
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"The 'requests' package is required for OpenClawKGTool. "
|
||||
"Install it with: pip install semantica[openclaw]"
|
||||
) from exc
|
||||
return self._session
|
||||
|
||||
def _post(self, endpoint: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
session = self._get_session()
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
response = session.post(url, json=payload, timeout=self.timeout)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def _get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
session = self._get_session()
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
response = session.get(url, params=params or {}, timeout=self.timeout)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Extraction
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def extract(self, text: str) -> Dict[str, Any]:
|
||||
"""Extract entities and relations from *text*."""
|
||||
return self._post("/extract", {"text": text})
|
||||
|
||||
def extract_entities(self, text: str) -> List[Dict[str, Any]]:
|
||||
"""Return only the entity list from *text*."""
|
||||
result = self.extract(text)
|
||||
return result.get("entities", [])
|
||||
|
||||
def extract_relations(self, text: str) -> List[Dict[str, Any]]:
|
||||
"""Return only the relation list from *text*."""
|
||||
result = self.extract(text)
|
||||
return result.get("relations", [])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Graph mutation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def add_entity(self, label: str, entity_type: str = "Entity", **properties: Any) -> Dict[str, Any]:
|
||||
"""Add a node to the knowledge graph."""
|
||||
return self._post("/entities", {"label": label, "type": entity_type, **properties})
|
||||
|
||||
def add_relationship(
|
||||
self,
|
||||
source: str,
|
||||
target: str,
|
||||
relation_type: str,
|
||||
**properties: Any,
|
||||
) -> Dict[str, Any]:
|
||||
"""Add an edge between *source* and *target*."""
|
||||
return self._post(
|
||||
"/relationships",
|
||||
{"source": source, "target": target, "type": relation_type, **properties},
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Decisions
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def record_decision(
|
||||
self,
|
||||
decision_text: str,
|
||||
context: Optional[str] = None,
|
||||
**metadata: Any,
|
||||
) -> Dict[str, Any]:
|
||||
"""Record a decision in the graph."""
|
||||
payload: Dict[str, Any] = {"decision": decision_text}
|
||||
if context:
|
||||
payload["context"] = context
|
||||
payload.update(metadata)
|
||||
return self._post("/decisions", payload)
|
||||
|
||||
def query_decisions(self, query: str, limit: int = 10) -> List[Dict[str, Any]]:
|
||||
"""Search recorded decisions."""
|
||||
result = self._get("/decisions/search", {"q": query, "limit": limit})
|
||||
return result.get("decisions", [])
|
||||
|
||||
def find_precedents(self, decision_text: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
||||
"""Find past decisions similar to *decision_text*."""
|
||||
result = self._post("/decisions/precedents", {"decision": decision_text, "top_k": top_k})
|
||||
return result.get("precedents", [])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Analytics & reasoning
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_causal_chain(self, node_id: str, depth: int = 3) -> Dict[str, Any]:
|
||||
"""Retrieve the causal chain rooted at *node_id*."""
|
||||
return self._get("/causal-chain", {"node_id": node_id, "depth": depth})
|
||||
|
||||
def run_reasoning(self, rules: List[str], facts: List[str]) -> Dict[str, Any]:
|
||||
"""Run the Semantica forward-chaining reasoner."""
|
||||
return self._post("/reason", {"rules": rules, "facts": facts})
|
||||
|
||||
def get_graph_analytics(self) -> Dict[str, Any]:
|
||||
"""Return graph-level analytics (centrality, communities, etc.)."""
|
||||
return self._get("/analytics")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Export
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def export_graph(self, fmt: str = "json") -> str:
|
||||
"""Export the graph in *fmt* (``json``, ``ttl``, ``graphml``, …)."""
|
||||
result = self._get("/export", {"format": fmt})
|
||||
return result.get("data", "")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Summary
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_graph_summary(self) -> Dict[str, Any]:
|
||||
"""Return a high-level summary of the current graph."""
|
||||
return self._get("/graph/summary")
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"OpenClawKGTool(base_url={self.base_url!r})"
|
||||
Reference in New Issue
Block a user