README.md•8.46 kB
# Narrative Graph MCP
A Model Context Protocol (MCP) server implementing the Random Tree Model (RTM) for hierarchical narrative memory in AI systems.
## Overview
The Narrative Graph MCP provides a scientifically-grounded implementation of the Random Tree Model, a cognitive architecture for organizing and recalling narrative information. Based on research in statistical physics and cognitive science, it models how humans encode, compress, and recall meaningful information across different levels of abstraction.
### Key Features
- **Hierarchical Memory Encoding**: Recursively partitions narratives into tree structures
- **Working Memory Constraints**: Models cognitive limits with configurable K (branching) and D (depth) parameters
- **Statistical Ensembles**: Generates multiple tree instances to capture population-level variance
- **Compression Analysis**: Calculates compression ratios and scaling properties
- **Flexible Traversal**: Access summaries at different abstraction levels
- **Scale Invariance**: Identifies universal scaling laws in long narratives
## Architecture
The project follows a clean, modular TypeScript architecture:
```
narrative-graph-mcp/
├── src/
│ ├── core/ # Core RTM implementation
│ │ ├── rtm-math.ts # Mathematical utilities
│ │ ├── rtm-builder.ts # Tree construction
│ │ ├── rtm-traversal.ts # Tree navigation
│ │ └── rtm-ensemble.ts # Statistical ensembles
│ ├── types/ # TypeScript type definitions
│ │ └── rtm.ts # RTM data structures
│ ├── tools/ # MCP tool implementations
│ │ ├── createNarrativeTree.ts
│ │ ├── generateEnsemble.ts
│ │ ├── traverseNarrative.ts
│ │ └── findOptimalDepth.ts
│ └── index.ts # MCP server entry point
├── dist/ # Compiled JavaScript
├── tsconfig.json # TypeScript configuration
└── package.json # Project dependencies
```
## Installation
### Prerequisites
- Node.js 18+
- npm or yarn package manager
### Install Dependencies
```bash
npm install
```
## Building
### Build for Production
```bash
npm run build
```
This compiles TypeScript to JavaScript in the `dist/` directory.
### Development Mode
```bash
npm run dev
```
This runs TypeScript compiler in watch mode for development.
## Running the Server
### Start the Server
```bash
npm start
```
Or directly:
```bash
node dist/index.js
```
## MCP Integration
### Configure Your MCP Client
Add the Narrative Graph MCP to your MCP client configuration:
```json
{
"mcpServers": {
"narrative-graph-mcp": {
"command": "node",
"args": ["/path/to/narrative-graph-mcp/dist/index.js"],
"env": {}
}
}
}
```
### Available Tools
#### 1. `rtm_create_narrative_tree`
Creates a single Random Tree encoding of a narrative.
**Parameters:**
- `text` (string, required): The narrative text to encode
- `title` (string, required): Title of the narrative
- `type` (string, optional): Type of narrative - 'story', 'article', 'dialogue', 'technical', 'other' (default: 'other')
- `maxBranchingFactor` (number, optional): Maximum child nodes per parent, K parameter (default: 4)
- `maxRecallDepth` (number, optional): Maximum traversal depth, D parameter (default: 6)
**Example:**
```json
{
"text": "Once upon a time, in a distant kingdom...",
"title": "The Lost Kingdom",
"type": "story"
}
```
**Returns:** Tree ID, statistics, and encoding metadata
#### 2. `rtm_generate_ensemble`
Generates a statistical ensemble of Random Trees to model population-level recall variance.
**Parameters:**
- `text` (string, required): The narrative text to analyze
- `title` (string, required): Title of the narrative
- `ensembleSize` (number, optional): Number of trees to generate (default: 100)
- `maxBranchingFactor` (number, optional): K parameter (default: 4)
- `maxRecallDepth` (number, optional): D parameter (default: 6)
**Example:**
```json
{
"text": "Once upon a time, in a distant kingdom...",
"title": "The Lost Kingdom",
"ensembleSize": 200
}
```
**Returns:** Ensemble statistics, variance analysis, and scale invariance properties
#### 3. `rtm_traverse_narrative`
Traverses a narrative tree at specified depths to retrieve summaries at different abstraction levels.
**Parameters:**
- `text` (string, required): The narrative text to traverse
- `title` (string, required): Title of the narrative
- `traversalDepth` (number, required): Depth to traverse, 1-10 (controls abstraction level)
- `maxBranchingFactor` (number, optional): K parameter (default: 4)
- `maxRecallDepth` (number, optional): D parameter (default: 6)
**Example:**
```json
{
"text": "Long narrative text...",
"title": "Research Paper",
"traversalDepth": 3
}
```
**Returns:** Summaries at the specified depth, compression ratios, and recall sequence
#### 4. `rtm_find_optimal_depth`
Finds the optimal traversal depth to achieve a target recall length.
**Parameters:**
- `text` (string, required): The narrative text to analyze
- `title` (string, required): Title of the narrative
- `targetRecallLength` (number, required): Target number of clauses to recall
- `maxBranchingFactor` (number, optional): K parameter (default: 4)
- `maxRecallDepth` (number, optional): D parameter (default: 6)
**Example:**
```json
{
"text": "Long narrative text...",
"title": "Research Paper",
"targetRecallLength": 50
}
```
**Returns:** Optimal depth and accuracy metrics
## Usage Examples
### Basic Narrative Encoding
```typescript
// Encode a story into a hierarchical tree
const result = await tools.call('rtm_create_narrative_tree', {
text: "Once upon a time, in a distant kingdom, there lived a wise king...",
title: "The Lost Kingdom",
type: "story"
});
```
### Generate Population Model
```typescript
// Generate ensemble to model how different people might recall the story
const ensemble = await tools.call('rtm_generate_ensemble', {
text: "Once upon a time, in a distant kingdom...",
title: "The Lost Kingdom",
ensembleSize: 200
});
```
### Get Different Summary Levels
```typescript
// Get high-level summary (depth 1)
const abstract = await tools.call('rtm_traverse_narrative', {
text: "Long narrative text...",
title: "Research Paper",
traversalDepth: 1
});
// Get detailed summary (depth 4)
const detailed = await tools.call('rtm_traverse_narrative', {
text: "Long narrative text...",
title: "Research Paper",
traversalDepth: 4
});
```
## Troubleshooting
### Server Startup Issues
If the server disconnects immediately after starting:
1. Check that all dependencies are installed: `npm install`
2. Ensure the build is complete: `npm run build`
3. Check for TypeScript errors: `npm run type-check`
4. Run with debug output: `DEBUG=* node dist/index.js`
### Common Errors
- **"Tool not found"**: Ensure the tool name is spelled correctly
- **"Invalid parameters"**: Check that required parameters are provided
- **"Build errors"**: Run `npm run clean && npm run build`
## Development
### Code Style
The project uses ESLint and Prettier for code formatting:
```bash
npm run lint
npm run format
```
### Type Checking
```bash
npm run type-check
```
### Testing
```bash
npm test
npm run test:watch
npm run test:coverage
```
## Theory and Background
The Random Tree Model is based on research showing that human memory for narratives follows specific mathematical patterns:
1. **Hierarchical Organization**: Stories are mentally organized into nested levels of abstraction
2. **Working Memory Constraints**: Limited capacity (K~4) constrains how much can be held in mind
3. **Compression**: Longer narratives are increasingly summarized, following predictable ratios
4. **Scale Invariance**: Very long narratives exhibit universal scaling properties
For more details, see the foundational paper: "Random Tree Model of Meaningful Memory" by Zhong et al.
## Contributing
Contributions are welcome! Please ensure:
1. All code is TypeScript with proper type annotations
2. Functions include JSDoc comments
3. New features include corresponding tests
4. Code passes linting and type checks
## License
MIT
## Acknowledgments
This implementation is based on the Random Tree Model theoretical framework from cognitive science and statistical physics research.