feat: MCP server v1.2.0 — guide system + read/write guide tools
Adds full guide system to MCP standalone server. System guides (schema, creating-nodes, edges, dimensions, extract) are bundled and immutable. Users can create up to 10 custom guides via rah_write_guide. Syncs guide infrastructure from main repo to OS repo app code. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.5
parent
2465e7562c
commit
be675be4e0
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: Preferences
|
||||
description: Your communication style, workflow rules, and current priorities.
|
||||
---
|
||||
|
||||
# Preferences
|
||||
|
||||
Add your preferences here. The agent will read this guide to understand how you like to work.
|
||||
|
||||
## Examples of what to put here
|
||||
- Communication style (bullet points vs prose, level of detail)
|
||||
- Workflow rules (always ask before creating dimensions, etc.)
|
||||
- Current priorities (what you're focused on this week)
|
||||
- Timezone and locale
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Creating Nodes
|
||||
description: When and how to create nodes. Link field rules. Synthesis patterns.
|
||||
immutable: true
|
||||
---
|
||||
|
||||
# Creating Nodes
|
||||
|
||||
## When to Create
|
||||
|
||||
- User explicitly asks to save/capture something
|
||||
- Extracting insights from existing content (synthesis)
|
||||
- Ingesting external content (YouTube, website, PDF)
|
||||
|
||||
## Link Field Rules
|
||||
|
||||
- **Has link:** Node directly represents external content (YouTube video, website, PDF, article)
|
||||
- **No link:** Node is derived/synthesized from existing content (ideas, insights, summaries, questions)
|
||||
- Never add a link to synthesis or idea nodes
|
||||
|
||||
## Synthesis Pattern
|
||||
|
||||
When creating a node derived from existing content:
|
||||
1. Create the node WITHOUT a link field
|
||||
2. Call `createEdge` to connect it to ALL source nodes
|
||||
3. Each edge needs an explanation ("Insight extracted from...", "Synthesized from...")
|
||||
|
||||
## Dimension Assignment
|
||||
|
||||
- New nodes should be assigned to relevant existing dimensions
|
||||
- Check locked/priority dimensions — these auto-assign
|
||||
- If no existing dimension fits, create a new one (but prefer existing)
|
||||
|
||||
## Description Field
|
||||
|
||||
- AI auto-generates a ~1 sentence description after creation
|
||||
- Description is used for embeddings and search ranking (5x boost)
|
||||
- Format: what is this node about, in plain language
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Dimensions
|
||||
description: Create, lock, describe, organize, clean up dimensions.
|
||||
immutable: true
|
||||
---
|
||||
|
||||
# Dimensions
|
||||
|
||||
Dimensions are how nodes are categorized and organized. Think of them as flexible tags with descriptions.
|
||||
|
||||
## Operations
|
||||
|
||||
- **Create:** `createDimension(name, description, isPriority)`
|
||||
- **Update:** `updateDimension(name, { newName, description, isPriority })`
|
||||
- **Delete:** `deleteDimension(name)` — removes from all nodes
|
||||
- **Query:** Use sqliteQuery to list dimensions and their node counts
|
||||
|
||||
## Locking (Priority)
|
||||
|
||||
- `isPriority = true` (locked) → dimension auto-assigns to new nodes when relevant
|
||||
- `isPriority = false` (unlocked) → manual assignment only
|
||||
- Lock dimensions that represent active areas of focus
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
- Lowercase, concise (e.g., "ai", "philosophy", "ra-h")
|
||||
- Use singular form where natural
|
||||
- Avoid overlapping names (don't have both "ai" and "artificial-intelligence")
|
||||
|
||||
## Description
|
||||
|
||||
Every dimension should have a description explaining its purpose. This helps the AI correctly assign nodes to dimensions.
|
||||
|
||||
## Cleanup
|
||||
|
||||
- Delete dimensions with 0 nodes
|
||||
- Merge overlapping dimensions (update nodes, then delete the redundant one)
|
||||
- Regularly review dimension list for coherence
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
name: Edges
|
||||
description: Edge philosophy. Explanations, direction, types. Connection patterns.
|
||||
immutable: true
|
||||
---
|
||||
|
||||
# Edges
|
||||
|
||||
## Philosophy
|
||||
|
||||
Edges are the most valuable part of the knowledge graph. Individual nodes are useful; the web of connections between them is what makes the graph powerful.
|
||||
|
||||
## Rules
|
||||
|
||||
1. **Every edge needs an explanation** — why does this connection exist? Be specific.
|
||||
2. **Direction matters** — FROM → TO should read like a sentence
|
||||
3. **Types are inferred** — the system infers category/type from your explanation. Don't set types manually.
|
||||
|
||||
## Direction Convention
|
||||
|
||||
Write the explanation so FROM → TO reads naturally:
|
||||
- Episode → Podcast: "Episode of this podcast"
|
||||
- Book → Author: "Written by this author"
|
||||
- Insight → Source: "Extracted from this source"
|
||||
- Idea → Related idea: "Builds on this concept"
|
||||
|
||||
## Edge Context JSON
|
||||
|
||||
```json
|
||||
{
|
||||
"explanation": "Human-readable reason",
|
||||
"category": "inferred (created_by, features, part_of, source_of, related_to)",
|
||||
"type": "inferred specific type",
|
||||
"confidence": 0.0-1.0,
|
||||
"created_via": "chat|mcp|workflow"
|
||||
}
|
||||
```
|
||||
|
||||
## Hub Traversal
|
||||
|
||||
Hub nodes (most-connected) are the user's core themes. To understand context around a topic:
|
||||
1. Find the relevant hub node
|
||||
2. Use `queryEdge` or sqliteQuery to get its connections
|
||||
3. Traverse outward to related nodes
|
||||
|
||||
## When to Create Edges
|
||||
|
||||
- After creating synthesis/idea nodes (connect to sources)
|
||||
- When user mentions a relationship between topics
|
||||
- When running the Connect or Integrate guides
|
||||
- When obvious connections exist that aren't captured
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: Extract
|
||||
description: Extraction pre-check. When to reuse chunks vs re-extract.
|
||||
immutable: true
|
||||
---
|
||||
|
||||
# Content Extraction
|
||||
|
||||
## Pre-Check (REQUIRED)
|
||||
|
||||
Before running any extraction tool, always check the node first:
|
||||
|
||||
1. Call `getNodesById` on the target node
|
||||
2. Check `chunk_status`:
|
||||
- **'chunked'** → content already extracted. Reuse existing chunks. Do NOT re-extract.
|
||||
- **'pending'** or missing → safe to extract
|
||||
- **'failed'** → previous extraction failed, safe to retry
|
||||
|
||||
3. Check if embeddings are available (chunk length > 0)
|
||||
- If available, use `searchContentEmbeddings` instead of re-extracting
|
||||
|
||||
## Extraction Tools
|
||||
|
||||
- **youtubeExtract** — YouTube videos (requires URL with video ID)
|
||||
- **websiteExtract** — Web pages (uses Jina.ai for JS-rendered sites)
|
||||
- **paperExtract** — PDF files (requires direct PDF URL)
|
||||
|
||||
## After Extraction
|
||||
|
||||
- The extracted content goes into `chunk` (full source)
|
||||
- AI generates a `description` (grounding summary)
|
||||
- Embeddings are created automatically
|
||||
- Assign to relevant dimensions
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
name: Schema
|
||||
description: Full database schema, tables, columns, query patterns.
|
||||
immutable: true
|
||||
---
|
||||
|
||||
# Database Schema
|
||||
|
||||
## Tables
|
||||
|
||||
### nodes
|
||||
| Column | Type | Notes |
|
||||
|--------|------|-------|
|
||||
| id | INTEGER | Primary key, auto-increment |
|
||||
| title | TEXT | Required |
|
||||
| description | TEXT | AI-generated grounding context (~1 sentence) |
|
||||
| content | TEXT | User's notes/thoughts (not source content) |
|
||||
| chunk | TEXT | Full verbatim source content |
|
||||
| chunk_status | TEXT | 'pending', 'chunked', 'failed' |
|
||||
| link | TEXT | External URL (only for nodes representing external content) |
|
||||
| type | TEXT | Nullable (reserved for future use) |
|
||||
| metadata | TEXT | JSON blob (map_position, transcript_length, etc.) |
|
||||
| is_pinned | INTEGER | Legacy — use hub node queries instead |
|
||||
| created_at | TEXT | ISO timestamp |
|
||||
| updated_at | TEXT | ISO timestamp |
|
||||
|
||||
### edges
|
||||
| Column | Type | Notes |
|
||||
|--------|------|-------|
|
||||
| id | INTEGER | Primary key |
|
||||
| from_node_id | INTEGER | FK → nodes.id |
|
||||
| to_node_id | INTEGER | FK → nodes.id |
|
||||
| context | TEXT | JSON: `{ explanation, category, type, confidence, created_via }` |
|
||||
| source | TEXT | 'user', 'ai_similarity', or helper name |
|
||||
| explanation | TEXT | Human-readable reason for connection |
|
||||
| created_at | TEXT | ISO timestamp |
|
||||
|
||||
### dimensions
|
||||
| Column | Type | Notes |
|
||||
|--------|------|-------|
|
||||
| id | INTEGER | Primary key |
|
||||
| name | TEXT | Unique, case-insensitive |
|
||||
| description | TEXT | Purpose description |
|
||||
| is_locked | INTEGER | 1 = priority dimension (auto-assigns to new nodes) |
|
||||
|
||||
### node_dimensions (junction)
|
||||
| Column | Type |
|
||||
|--------|------|
|
||||
| node_id | INTEGER FK → nodes.id |
|
||||
| dimension_id | INTEGER FK → dimensions.id |
|
||||
|
||||
### chunks (for semantic search)
|
||||
| Column | Type | Notes |
|
||||
|--------|------|-------|
|
||||
| id | INTEGER | Primary key |
|
||||
| node_id | INTEGER | FK → nodes.id |
|
||||
| chunk_index | INTEGER | Position in sequence |
|
||||
| text | TEXT | Chunk content |
|
||||
| embedding | BLOB | Vector (via sqlite-vec) |
|
||||
|
||||
### FTS Tables
|
||||
- `chunks_fts` — full-text search on chunk text
|
||||
- `nodes_fts` — full-text search on node title + content
|
||||
|
||||
## Common Query Patterns
|
||||
|
||||
**Top connected nodes (hubs):**
|
||||
```sql
|
||||
SELECT n.id, n.title, n.description, COUNT(DISTINCT e.id) AS edge_count
|
||||
FROM nodes n
|
||||
LEFT JOIN edges e ON (e.from_node_id = n.id OR e.to_node_id = n.id)
|
||||
GROUP BY n.id ORDER BY edge_count DESC LIMIT 5
|
||||
```
|
||||
|
||||
**Nodes in a dimension:**
|
||||
```sql
|
||||
SELECT n.* FROM nodes n
|
||||
JOIN node_dimensions nd ON n.id = nd.node_id
|
||||
JOIN dimensions d ON nd.dimension_id = d.id
|
||||
WHERE d.name = ?
|
||||
```
|
||||
|
||||
**Edges for a node (both directions):**
|
||||
```sql
|
||||
SELECT e.*, n1.title as from_title, n2.title as to_title
|
||||
FROM edges e
|
||||
JOIN nodes n1 ON e.from_node_id = n1.id
|
||||
JOIN nodes n2 ON e.to_node_id = n2.id
|
||||
WHERE e.from_node_id = ? OR e.to_node_id = ?
|
||||
```
|
||||
|
||||
**Use sqliteQuery for any read operation not covered by structured tools.**
|
||||
@@ -6,64 +6,110 @@ import matter from 'gray-matter';
|
||||
export interface GuideMeta {
|
||||
name: string;
|
||||
description: string;
|
||||
immutable: boolean;
|
||||
}
|
||||
|
||||
export interface Guide extends GuideMeta {
|
||||
content: string;
|
||||
}
|
||||
|
||||
const MAX_USER_GUIDES = 10;
|
||||
|
||||
const GUIDES_DIR = path.join(
|
||||
os.homedir(),
|
||||
'Library/Application Support/RA-H/guides'
|
||||
);
|
||||
|
||||
const BUNDLED_GUIDES_DIR = path.join(
|
||||
const SYSTEM_GUIDES_DIR = path.join(
|
||||
process.cwd(),
|
||||
'src/config/guides/system'
|
||||
);
|
||||
|
||||
const USER_GUIDES_DIR = path.join(
|
||||
process.cwd(),
|
||||
'src/config/guides'
|
||||
);
|
||||
|
||||
// System guide names (immutable, always re-seeded)
|
||||
const SYSTEM_GUIDE_NAMES = new Set([
|
||||
'schema',
|
||||
'creating-nodes',
|
||||
'edges',
|
||||
'dimensions',
|
||||
'extract',
|
||||
]);
|
||||
|
||||
function ensureGuidesDir(): void {
|
||||
if (!fs.existsSync(GUIDES_DIR)) {
|
||||
fs.mkdirSync(GUIDES_DIR, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function seedDefaultGuides(): void {
|
||||
if (!fs.existsSync(BUNDLED_GUIDES_DIR)) return;
|
||||
/**
|
||||
* Seed system guides — always overwritten on app start to stay current.
|
||||
* User guides are only seeded if they don't already exist.
|
||||
*/
|
||||
function seedGuides(): void {
|
||||
// Always re-seed system guides (immutable, kept up to date)
|
||||
if (fs.existsSync(SYSTEM_GUIDES_DIR)) {
|
||||
const systemFiles = fs.readdirSync(SYSTEM_GUIDES_DIR).filter(f => f.endsWith('.md'));
|
||||
for (const file of systemFiles) {
|
||||
const dest = path.join(GUIDES_DIR, file);
|
||||
fs.copyFileSync(path.join(SYSTEM_GUIDES_DIR, file), dest);
|
||||
}
|
||||
}
|
||||
|
||||
const bundled = fs.readdirSync(BUNDLED_GUIDES_DIR).filter(f => f.endsWith('.md'));
|
||||
for (const file of bundled) {
|
||||
const dest = path.join(GUIDES_DIR, file);
|
||||
if (!fs.existsSync(dest)) {
|
||||
fs.copyFileSync(path.join(BUNDLED_GUIDES_DIR, file), dest);
|
||||
// Seed default user guides only if they don't exist
|
||||
if (fs.existsSync(USER_GUIDES_DIR)) {
|
||||
const userFiles = fs.readdirSync(USER_GUIDES_DIR).filter(f => f.endsWith('.md'));
|
||||
for (const file of userFiles) {
|
||||
const dest = path.join(GUIDES_DIR, file);
|
||||
if (!fs.existsSync(dest)) {
|
||||
fs.copyFileSync(path.join(USER_GUIDES_DIR, file), dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let initialized = false;
|
||||
|
||||
function init(): void {
|
||||
if (initialized) return;
|
||||
ensureGuidesDir();
|
||||
const existing = fs.readdirSync(GUIDES_DIR).filter(f => f.endsWith('.md'));
|
||||
if (existing.length === 0) {
|
||||
seedDefaultGuides();
|
||||
}
|
||||
seedGuides();
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
function isSystemGuide(filename: string): boolean {
|
||||
const name = filename.replace('.md', '');
|
||||
return SYSTEM_GUIDE_NAMES.has(name);
|
||||
}
|
||||
|
||||
export function listGuides(): GuideMeta[] {
|
||||
init();
|
||||
const files = fs.readdirSync(GUIDES_DIR).filter(f => f.endsWith('.md'));
|
||||
return files.map(file => {
|
||||
|
||||
const guides = files.map(file => {
|
||||
const raw = fs.readFileSync(path.join(GUIDES_DIR, file), 'utf-8');
|
||||
const { data } = matter(raw);
|
||||
const immutable = isSystemGuide(file) || data.immutable === true;
|
||||
return {
|
||||
name: data.name || file.replace('.md', ''),
|
||||
description: data.description || '',
|
||||
immutable,
|
||||
};
|
||||
});
|
||||
|
||||
// System guides first, then user guides alphabetically
|
||||
return guides.sort((a, b) => {
|
||||
if (a.immutable && !b.immutable) return -1;
|
||||
if (!a.immutable && b.immutable) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
}
|
||||
|
||||
export function readGuide(name: string): Guide | null {
|
||||
init();
|
||||
// Try exact filename first, then lowercase
|
||||
const candidates = [
|
||||
`${name}.md`,
|
||||
`${name.toLowerCase()}.md`,
|
||||
@@ -74,9 +120,11 @@ export function readGuide(name: string): Guide | null {
|
||||
if (fs.existsSync(filepath)) {
|
||||
const raw = fs.readFileSync(filepath, 'utf-8');
|
||||
const { data, content } = matter(raw);
|
||||
const immutable = isSystemGuide(filename) || data.immutable === true;
|
||||
return {
|
||||
name: data.name || name,
|
||||
description: data.description || '',
|
||||
immutable,
|
||||
content: content.trim(),
|
||||
};
|
||||
}
|
||||
@@ -85,9 +133,64 @@ export function readGuide(name: string): Guide | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function writeGuide(name: string, content: string): void {
|
||||
export function writeGuide(name: string, content: string): { success: boolean; error?: string } {
|
||||
init();
|
||||
const filename = `${name.toLowerCase()}.md`;
|
||||
|
||||
// Reject writes to immutable guides
|
||||
if (isSystemGuide(filename)) {
|
||||
return { success: false, error: `Guide "${name}" is a system guide and cannot be modified.` };
|
||||
}
|
||||
|
||||
// Check user guide cap for new guides
|
||||
const filepath = path.join(GUIDES_DIR, filename);
|
||||
if (!fs.existsSync(filepath)) {
|
||||
const userGuideCount = getUserGuideCount();
|
||||
if (userGuideCount >= MAX_USER_GUIDES) {
|
||||
return { success: false, error: `Maximum of ${MAX_USER_GUIDES} custom guides reached. Delete a guide first.` };
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync(filepath, content, 'utf-8');
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export function deleteGuide(name: string): { success: boolean; error?: string } {
|
||||
init();
|
||||
const candidates = [
|
||||
`${name}.md`,
|
||||
`${name.toLowerCase()}.md`,
|
||||
];
|
||||
|
||||
for (const filename of candidates) {
|
||||
// Reject deletes of immutable guides
|
||||
if (isSystemGuide(filename)) {
|
||||
return { success: false, error: `Guide "${name}" is a system guide and cannot be deleted.` };
|
||||
}
|
||||
|
||||
const filepath = path.join(GUIDES_DIR, filename);
|
||||
if (fs.existsSync(filepath)) {
|
||||
fs.unlinkSync(filepath);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
|
||||
return { success: false, error: `Guide "${name}" not found.` };
|
||||
}
|
||||
|
||||
export function getUserGuideCount(): number {
|
||||
init();
|
||||
const files = fs.readdirSync(GUIDES_DIR).filter(f => f.endsWith('.md'));
|
||||
return files.filter(f => !isSystemGuide(f)).length;
|
||||
}
|
||||
|
||||
export function getGuideStats(): { userGuides: number; maxUserGuides: number; systemGuides: number } {
|
||||
const guides = listGuides();
|
||||
const systemCount = guides.filter(g => g.immutable).length;
|
||||
const userCount = guides.filter(g => !g.immutable).length;
|
||||
return {
|
||||
userGuides: userCount,
|
||||
maxUserGuides: MAX_USER_GUIDES,
|
||||
systemGuides: systemCount,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user