# SapientDB Skill

Store and retrieve markdown as individually addressable, permissioned blocks — for AI agents and humans working on the same documents.

---

## Overview
- **What it does:**
  Lets an AI agent read, write, search, and manage markdown documents stored as fine-grained blocks in SapientDB. Agents work on individual blocks (paragraphs, headings, code sections) without loading entire documents. Humans edit the same blocks in a rich web editor. Permissions are enforced at the block level via PostgreSQL Row-Level Security.

- **When to use it:**
  When an agent needs persistent, structured document storage — knowledge bases, research notes, collaborative writing, living documentation, or any workflow where agents and humans share content. Use instead of file-based storage when you need block-level access, token-budgeted search, or fine-grained permissions.

- **Requirements:**
  - OS: macOS / Linux / Windows
  - Runtime: Node.js 18+ (MCP server runs via npx)
  - Accounts: SapientDB account with a Service Account key or Personal Access Token

---

## Quick start

### Install

Add the SapientDB MCP server to your MCP client config:

```json
{
  "mcpServers": {
    "sapientdb": {
      "command": "npx",
      "args": ["-y", "@agentopolis/sapientdb-mcp@0.1.8"],
      "env": {
        "SAPIENTDB_TOKEN": "your_service_account_token"
      }
    }
  }
}
```

Where to put this depends on your MCP client:
- **Claude Desktop:** `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows)
- **Claude Code:** `.mcp.json` in your project root or `~/.claude/settings.json`
- **Cursor:** `.cursor/mcp.json` in your project root
- **OpenClaw:** `~/.openclaw/openclaw.json`
- **Other MCP clients:** Refer to the client's documentation for config file location

### Configure

```bash
# Required:
#   SAPIENTDB_TOKEN  — Service Account key or Personal Access Token
#
# Optional:
#   SAPIENTDB_URL    — API endpoint (default: https://sapientdb.com)
#
# Get your token:
#   1. Sign up at https://sapientdb.com
#   2. Create an organization and collection
#   3. Go to Organization > Service Accounts > Create
#   4. Copy the generated token
```

### Verify

```text
List my SapientDB documents
```

**Expected result:**
- The agent calls `list_documents` and returns a list of documents in your collections, confirming the MCP connection and authentication are working.

---

## Core tasks

### Get help and discover tools

```text
Get help with SapientDB tools and explain how to use them
```

The agent calls `get_help` which returns a comprehensive guide to all available tools, the data model, search capabilities, and best practices.

### Create a document and add content

```text
Create a new document called "Meeting Notes - March 2026" in my collection, then add three blocks: an agenda section, a discussion summary, and action items
```

### Search across documents

```text
Search my SapientDB documents for blocks mentioning "deployment pipeline" with a token budget of 2000 tokens
```

The agent uses `search_blocks` with `max_tokens` to return the most relevant blocks that fit within the specified context window budget.

### Read and update specific blocks

```text
Get the action items block from the meeting notes document and add a new item about the API review deadline
```

### Organize with collections and permissions

```text
List all documents in my "Engineering" collection and show me the permissions on the architecture document
```

### Batch import content

```text
Create a document called "Sprint Retrospective" and batch-add these sections: what went well, what didn't, and next steps — each as a separate block
```

### Review agent-written content

```text
Search for all blocks created in the last 24 hours and show me what was added
```

The agent uses `list_blocks` with `created_after` to filter blocks by creation time.

---

## Environment variable contract

| Variable | Purpose | Required | Default |
|---|---|---|---|
| `SAPIENTDB_TOKEN` | Service Account key or PAT for API authentication | Yes | — |
| `SAPIENTDB_URL` | API endpoint URL | No | `https://sapientdb.com` |

---

## Configuration

* **Secrets / credentials required:**
  * `SAPIENTDB_TOKEN` — a Service Account key (for agents) or Personal Access Token (for human API use). Create at https://sapientdb.com under Organization > Service Accounts or Account > Personal Access Tokens.

* **How to reset / re-auth:**
  * Rotate a Service Account key: Organization > Service Accounts > select account > Rotate Key
  * Revoke a PAT: Account > Personal Access Tokens > Revoke
  * Update `SAPIENTDB_TOKEN` in your MCP client config or environment

---

## Security & Guardrails

### Secrets handling
* Never paste tokens into chat — always use environment variables.
* Tokens are Bearer tokens sent over HTTPS only.
* If a token is exposed, rotate it immediately via the SapientDB web UI.

### Confirmations (before risky actions)
* `delete_document` permanently removes a document and ALL its blocks — confirm with the user before calling this.
* `delete_block` is irreversible — confirm before deleting.
* `set_permissions` changes access control — confirm the intended ACL before applying.

### Data minimization
* Use `max_tokens` on `search_blocks` to limit results to what fits in the agent's context window.
* Use `limit` parameters on all list operations to avoid over-fetching.
* Block-level access means agents read only the content they need, not entire documents.

### Permissions / scopes
* Service Accounts are scoped to a specific collection with a fixed role: `read`, `read_write`, or `admin`.
* Read-only service accounts cannot create, update, or delete content.
* Block-level ACLs can further restrict access within a document.
* All permissions are enforced via PostgreSQL Row-Level Security at the database level.

### Network access
* `sapientdb.com` — API endpoint for all MCP tool calls (HTTPS only)
* No other domains are contacted.

### Local storage
* No local files are written. All data is stored server-side in PostgreSQL.
* Authentication is via Bearer token from environment — no local token storage.

### Revoke / rotate
* **Service Account keys:** Organization > Service Accounts > Rotate Key. Old key is invalidated immediately.
* **Personal Access Tokens:** Account > Personal Access Tokens > Revoke. Token stops working immediately.
* After rotation, update `SAPIENTDB_TOKEN` in your MCP client config or environment.

---

## Troubleshooting

* **Error:** `SAPIENTDB_TOKEN is required`
  * Fix: Set the `SAPIENTDB_TOKEN` environment variable in your MCP client config's `env` block, or in your process environment / `.env` file.

* **Error:** `401 Unauthorized`
  * Fix: Verify your token is correct and hasn't been revoked. Try rotating the key and updating the environment variable.

* **Error:** `403 Forbidden`
  * Fix: Your service account doesn't have permission for this operation. Check the account's role (read vs read_write vs admin) and the document/block ACLs.

* **Error:** `Request timed out`
  * Fix: The API request exceeded 30 seconds. Try reducing the scope of your search (add filters, lower `limit`, use `max_tokens`).

* **Problem:** "MCP server not connecting"
  * Fix: Validate your MCP client config has the correct `sapientdb` entry, restart your MCP client, and verify `SAPIENTDB_TOKEN` is set.

---

## Release notes

* v0.1.8:
  * Updated default API URL to `https://sapientdb.com`
  * Updated all documentation links

* v0.1.7:
  * Synced MCP tool schemas with server API
  * Added `get_help` tool with topic-based documentation
  * Added `batch_create_blocks` for bulk content ingestion
  * Added `search_documents` for title-based document search

---

## Links

* Homepage: https://sapientdb.com
* Documentation: https://sapientdb.com/help
* npm package: https://www.npmjs.com/package/@agentopolis/sapientdb-mcp
* GitHub: https://github.com/agentopolis/sapientdb

---

## Publisher

* **Publisher:** @Agentopolis
