Metadata-Version: 2.4
Name: cks-mcp
Version: 1.13.2
Summary: CKS MCP Server — Canonical Knowledge Structure for LLMs
Author: Vladyslav Hruznov
License: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cks-runtime>=1.21.0
Requires-Dist: cks-core>=1.13.1
Requires-Dist: requests>=2.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Dynamic: license-file

# CKS MCP Server

> Model Context Protocol server for Canonical Knowledge Structure.

![Python](https://img.shields.io/badge/python-3.12%2B-blue)
![License](https://img.shields.io/badge/license-MIT-green)
![Tests](https://img.shields.io/badge/tests-110%20passing-brightgreen)
[![PyPI](https://img.shields.io/pypi/v/cks-mcp)](https://pypi.org/project/cks-mcp/)

`cks-mcp` is an MCP (Model Context Protocol) server that gives LLMs
a **canonical knowledge backbone**. It exposes the tools listed under
*Available Tools* below, backed by the deterministic,
immutable semantics of `cks-core` and the operational management of
`cks-runtime`.

Every tool call creates a **Runtime Session** and **Transaction**,
producing an immutable **Version** and collecting **Diagnostics**.
This guarantees full auditability and reproducibility.

---

# Ecosystem

CKS Core is the semantic foundation of the CKS ecosystem.
Other projects build upon it:

| Project | Description | Repository |
|---------|-------------|------------|
| **cks-core** | Canonical semantic engine | [Deus-corp/cks-core](https://github.com/Deus-corp/cks-core) |
| **cks-runtime** | Operational environment – sessions, transactions, persistence | [Deus-corp/cks-runtime](https://github.com/Deus-corp/cks-runtime) |
| **cks-mcp** | MCP server – exposes CKS to LLMs (this repository) | [Deus-corp/cks-mcp](https://github.com/Deus-corp/cks-mcp) |

---

# Quick Start

1. Install and connect to Claude Desktop (see [Installation](#installation)).
2. (Optional) For semantic search, set your Hugging Face token: `export HF_TOKEN=hf_...`
3. In the chat, start your message with **"Use cks-mcp to…"**.
4. Claude automatically picks the right tool from the 22 available — validation, evolution, branching, merging, source verification, contradiction detection, semantic search, subgraph queries, sandboxing, and more.
5. Every operation is logged, versioned, and stored in a persistent SQLite database.

**Just type "Use cks-mcp to..." and Claude does the rest. That's it.**
**No programming, no command line — just a conversation!**

![CKS Demo](https://github.com/Deus-corp/cks-mcp/releases/download/v1.10.2/demo.gif)

*In the video above, Claude creates a validated knowledge graph about the water cycle from a single sentence, using `validate_knowledge` and `explain_knowledge`. Twenty-two tools are ready for you: branching, merging, versioning, source verification, contradiction detection, subgraph queries, sandboxing, and more — all triggered by plain English.*

---

# Why cks-mcp?

LLMs generate plausible but unverified statements. `cks-mcp` gives them
a **canonical knowledge backbone**: every piece of information must be
explicitly structured, validated against formal constraints, and
traceable to its origin.

- **Eliminate citation hallucinations** — optional extensions like
  `embedding_projection` mechanically detect references to non-existent
  sources.
- **Ensure verification integrity** — the `verify_source` tool performs
  a real HTTP check and cryptographically signs the result. Any
  `VerificationRecord` without a valid signature is automatically
  rejected, even if the model fails to request the check.
- **Semantic search with real embeddings** — the `search_semantic` tool uses HuggingFace models to find relevant nodes by meaning, not just keywords. A query for "how to train AI models" returns "Gradient Descent" and "Neural Network", not "Banana".
- **Graph-based RAG** — combine semantic search with `query_subgraph` to retrieve a full neighbourhood around the found concepts, giving the LLM the context it needs without hallucinating connections.
- **Full audit trail** — every operation is captured in an immutable
  version history, providing complete accountability for AI-generated
  knowledge.
- **Time-travel debugging** — `list_versions`, `revert_version`, and `compare_versions` give LLMs a full version-control system for knowledge, enabling safe rollbacks and change inspection.
- **Contradiction detection** — `detect_contradictions` flags mutual exclusions (e.g., both `supports` and `contradicts` between the same pair) and functional relation violations (e.g., a planet orbiting two different stars).
- **Hypothesis sandboxing** — `fork_sandbox` creates an isolated branch, optionally applies a hypothesis, and reports the diff from the fork point — all without touching the parent session. Safe to discard or promote.

---

# Installation

```bash
pip install cks-mcp
```

The server requires `cks-runtime` (which includes `cks-core`) as a dependency.

For semantic search, you also need a Hugging Face token:
```bash
export HF_TOKEN=hf_...
```

---

# Connect to Claude Desktop

1. Install all three packages into a single virtual environment:
   ```bash
   python3 -m venv cks-env
   source cks-env/bin/activate
   pip install cks-core cks-runtime cks-mcp
   ```

2. Open Claude Desktop, go to **Settings → Developer → Edit Config**.
   The configuration file (`claude_desktop_config.json`) will open.
   Add the following block (adjust the path to your `cks-mcp` executable):
   ```json
   {
     "mcpServers": {
       "cks-mcp": {
         "command": "/absolute/path/to/cks-env/bin/cks-mcp"
       }
     }
   }
   ```

3. Save the file and fully restart Claude Desktop (Cmd+Q, then reopen).
   After restart, a connector icon will appear – `cks-mcp` with twenty-two tools is ready to use.

---

# Available Tools

| Tool | Description |
|------|-------------|
| `validate_knowledge` | Validate a Knowledge Structure and return diagnostics. Supports opt‑in extensions (`embedding_projection`, `verification_record`). Provenance of `VerificationRecord` objects is checked automatically. |
| `serialize_knowledge` | Serialize a Knowledge Structure into canonical JSON. |
| `explain_knowledge` | Produce a semantic explanation of a Knowledge Structure. |
| `evolve_knowledge` | Apply Genesis/Decay operators to evolve a structure. |
| `verify_source` | Perform a real HTTP request to check a URL's availability and create a cryptographically signed `VerificationRecord`. |
| `list_versions` | List all available versions of a session's history. |
| `compare_versions` | Compute the structural difference between the current state of a session and a target version. |
| `revert_version` | Revert a session's Knowledge Structure to a specific previous version. |
| `merge_knowledge` | Three-way merge of knowledge structures with conflict detection. |
| `create_branch` | Fork a new session from an existing one, optionally from a specific historical version. |
| `merge_branch` | Session-aware three-way merge: merge a branch session into a target session, resolving the merge base automatically from the branch's recorded fork point. |
| `close_session` | Close a session, releasing it from the runtime (e.g. a branch already merged in). |
| `query_subgraph` | Extract a local k‑hop neighbourhood from a session's Knowledge Structure, with filters, optional budget, and compact mode. |
| `search_semantic` | **Real embedding-based semantic search.** Uses HuggingFace models to find relevant objects by meaning. Query "virtual machines" returns EC2, not S3. |
| `get_metrics` | Return runtime metrics: invocation counts and average execution times per operation type. |
| `visualize_graph` | Export a session's Knowledge Structure or a subgraph as a Mermaid diagram for native rendering in Claude Desktop. |
| `explain_diff` | Produce a natural-language explanation of changes between two versions, complementing `compare_versions`. |
| `suggest_evolution` | Inspect the current state of a session and receive guidance for constructing valid evolution operations. |
| `export_knowledge` | Export a session's Knowledge Structure to JSON-LD, Turtle, or RDF/XML for use with Protégé, Neo4j, or triple stores. |
| `detect_contradictions` | Detect logical contradictions (mutual exclusion, functional relation violations) using the new contradiction constraints. |
| `fork_sandbox` | Create an isolated branch, optionally apply a hypothesis, and show a diff from the fork point — safe to discard or promote. |
| `ingest_document` | Fetch a public URL and build a Knowledge Structure from its metadata and keywords. |

---

# Usage Examples

## Semantic search (no seed IDs required!)

```json
{
  "method": "tools/call",
  "params": {
    "name": "search_semantic",
    "arguments": {
      "session_id": "...",
      "query": "virtual machines in the cloud"
    }
  }
}
```

Response:

```json
{
  "status": "success",
  "matched_seeds": ["ec2", "compute-service", "aws"],
  "subgraph": "...",
  "meta": { ... }
}
```

## Compact subgraph query

```json
{
  "method": "tools/call",
  "params": {
    "name": "query_subgraph",
    "arguments": {
      "session_id": "...",
      "seed_ids": ["earth", "mars"],
      "depth": 2,
      "compact_mode": true
    }
  }
}
```

Response (compact, token-efficient):

```json
{
  "nodes": [
    {"id": "earth", "type": "Planet", "name": "Earth", "props": {...}},
    {"id": "mars", "type": "Planet", "name": "Mars", "props": {...}}
  ],
  "edges": [
    {"source": "earth", "target": "sun", "type": "orbits"}
  ]
}
```

## Validate a structure with citation-hallucination detection

Pass `"extensions": ["embedding_projection"]` to `validate_knowledge`.
This activates an extra constraint that checks every `EmbeddingProjection`
object for a valid `represents` relation to an existing source object.
A projection that references a non‑existent source (a fabricated citation)
is mechanically flagged.

## Validate a structure with verification integrity

When you use `verify_source` to check a URL, the resulting
`VerificationRecord` is cryptographically signed. Any
`VerificationRecord` found in a structure without a valid signature
is automatically rejected, **even if the model does not explicitly
request the verification extension**. This prevents LLMs from
bypassing the check by simply omitting a parameter.

## Basic validation

```json
{
  "method": "tools/call",
  "params": {
    "name": "validate_knowledge",
    "arguments": {
      "json_data": "{\"objects\":[{\"identity\":{\"id\":\"obj-1\",\"type\":\"Definition\",\"name\":\"Test\"},\"structure\":{}}]}"
    }
  }
}
```

Response (with version and session information):

```json
{
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"valid\": true, \"version_id\": \"...\", \"session_id\": \"...\", \"diagnostics\": [], ...}"
      }
    ]
  }
}
```

## Compare two versions

```json
{
  "method": "tools/call",
  "params": {
    "name": "compare_versions",
    "arguments": {
      "session_id": "...",
      "target_version_id": "..."
    }
  }
}
```

Response:

```json
{
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"session_id\": \"...\", \"target_version_id\": \"...\", \"changes\": [...]}"
      }
    ]
  }
}
```

## Branch, evolve independently, and merge back

Fork a session, evolve the branch and its parent independently, then
merge the branch back in:

```json
{"method": "tools/call", "params": {"name": "create_branch",
  "arguments": {"session_id": "trunk-session-id"}}}
```

```json
{"method": "tools/call", "params": {"name": "evolve_knowledge",
  "arguments": {"session_id": "branch-session-id", "operations": [...]}}}
```

```json
{"method": "tools/call", "params": {"name": "merge_branch",
  "arguments": {"target_session_id": "trunk-session-id",
                "source_session_id": "branch-session-id"}}}
```

A successful merge commits a new version of the target session and
returns its `serialized` structure and `version_id`. A conflicting
merge instead returns `"merged": false` with a `conflicts` list
(`object_id`, `base_state`, `target_state`, `source_state`) — resolve
each one on the target session with `evolve_knowledge`, then
`close_session` the branch once it's fully integrated.

---

## Query a subgraph

```json
{
  "method": "tools/call",
  "params": {
    "name": "query_subgraph",
    "arguments": {
      "session_id": "...",
      "seed_ids": ["obj-1"],
      "depth": 2,
      "max_objects": 10
    }
  }
}
```

Response (truncated example):

```json
{
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"subgraph\": \"...\", \"total_found_nodes\": 15, \"returned_nodes\": 10, \"is_truncated\": true, \"suggested_next_seed\": \"obj-7\"}"
      }
    ]
  }
}
```

## Visualize a knowledge graph

```json
{
  "method": "tools/call",
  "params": {
    "name": "visualize_graph",
    "arguments": {
      "session_id": "..."
    }
  }
}
```

Response (Mermaid diagram):

````markdown
```mermaid
graph TD
    earth((Earth))
    sun((Sun))
    earth -->|orbits| sun
```
````

## Explain the difference between two versions

```json
{
  "method": "tools/call",
  "params": {
    "name": "explain_diff",
    "arguments": {
      "session_id": "...",
      "base_version_id": "...",
      "target_version_id": "..."
    }
  }
}
```

Response:

```json
{
  "summary": "Added 2 objects and 1 relation. Modified 1 object.",
  "changes": [
    "Added object 'Pluto' (type: Planet)",
    "Added object 'Charon' (type: Moon)",
    "Added relation 'orbits' from 'Pluto' to 'Charon'",
    "Modified object 'Earth': changed 'status' from 'active' to 'inactive'"
  ]
}
```

## Get AI assistance with evolution

```json
{
  "method": "tools/call",
  "params": {
    "name": "suggest_evolution",
    "arguments": {
      "session_id": "...",
      "description": "Add a new planet Neptune that orbits the Sun"
    }
  }
}
```

Response:

```json
{
  "current_objects": [
    {"id": "sun", "type": "Star", "name": "Sun"},
    {"id": "earth", "type": "Planet", "name": "Earth"},
    {"id": "moon", "type": "Moon", "name": "Moon"}
  ],
  "current_relations": [
    {"type": "orbits", "from": "earth", "to": "sun"},
    {"type": "orbits", "from": "moon", "to": "earth"}
  ],
  "guidance": "To add a new planet Neptune: use add_object with identity {id: 'neptune', type: 'Planet', name: 'Neptune'} and add_relation with participants ['neptune', 'sun'] and relation_type 'orbits'."
}
```

## Export to RDF/JSON-LD

```json
{
  "method": "tools/call",
  "params": {
    "name": "export_knowledge",
    "arguments": {
      "session_id": "...",
      "format": "turtle"
    }
  }
}
```

Response:

```turtle
@prefix cks: <http://cks.org/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://cks.org/sun> rdf:type <http://cks.org/Star> ;
    rdfs:label "Sun" .

<http://cks.org/earth> rdf:type <http://cks.org/Planet> ;
    rdfs:label "Earth" ;
    <http://cks.org/orbits> <http://cks.org/sun> .
```

## Detect contradictions

```json
{
  "method": "tools/call",
  "params": {
    "name": "detect_contradictions",
    "arguments": {
      "session_id": "..."
    }
  }
}
```

Response:

```json
{
  "contradiction_count": 1,
  "contradictions": [
    {
      "code": "CKS-EXT-MUTUAL-EXCLUSION",
      "severity": "error",
      "source": "core",
      "message": "Relation 'rel-1' (type 'supports') and relation 'rel-2' (type 'contradicts') both connect 'a' to 'b', but a MutualExclusionRule declares these relation_types mutually exclusive."
    }
  ]
}
```

## Detect contradictions

`detect_contradictions` uses `MutualExclusionRule` and `FunctionalRelationRule`
objects to find logical conflicts. For mutual exclusion, both conflicting
relations must connect the **same ordered pair** (same source and same target).

Example of a MutualExclusionRule:
```json
{"identity": {"id": "rule-1", "type": "MutualExclusionRule", "name": "no-support-and-refute"},
 "structure": {"relation_type_a": "confirms", "relation_type_b": "refutes"}}
 ```

Example of a FunctionalRelationRule:

```json
{"identity": {"id": "rule-2", "type": "FunctionalRelationRule", "name": "single-orbit"},
 "structure": {"relation_type": "orbits"}}
```

## Fork a sandbox and test a hypothesis

```json
{
  "method": "tools/call",
  "params": {
    "name": "fork_sandbox",
    "arguments": {
      "session_id": "...",
      "hypothesis": "Add Neptune as a planet orbiting the Sun",
      "operations": [
        {"type": "add_object", "identity": {"id": "neptune", "type": "Planet", "name": "Neptune"}},
        {"type": "add_relation", "identity": {"id": "rel-nep", "type": "Relation", "name": "orbits"}, "participants": ["neptune", "sun"], "relation_type": "orbits"}
      ]
    }
  }
}
```

Response:

```json
{
  "sandbox_session_id": "...",
  "parent_session_id": "...",
  "operations_applied": 2,
  "diff_from_fork_point": {
    "summary": {"added_objects": 1, "added_relations": 1, "removed_objects": 0, "removed_relations": 0},
    "operations": [...]
  },
  "message": "Sandbox session '...' is an isolated fork of '...'; nothing here affects the parent. Keep exploring it with evolve_knowledge, promote it with merge_branch once satisfied, or discard it with close_session -- there is no obligation to merge."
}
```

## Ingest a document

```json
{
  "method": "tools/call",
  "params": {
    "name": "ingest_document",
    "arguments": {
      "url": "https://example.com/article"
    }
  }
}
```

Response:

```json
{
  "url": "https://example.com/article",
  "title": "Example Article",
  "keywords": ["example", "article", "knowledge", "graph"],
  "knowledge_structure": "{...}",
  "object_count": 5,
  "relation_count": 4
}
```

---

# Security and Provenance

`verify_source` includes built-in protections:
- **SSRF prevention**: URLs are validated against a strict allowlist;
  private, loopback, and cloud metadata IPs are blocked. DNS rebinding
  attacks are neutralised by pinning the connection to the IP address
  resolved during the safety check.
- **Cryptographic signing**: every verification record is signed with a
  process-local HMAC. `validate_knowledge` unconditionally verifies this
  signature, so a hand‑written `VerificationRecord` can never pass as
  genuine.

---

# Testing

```bash
python -m pytest -v
```

110+ tests, all passing.

---

# License

MIT
