Skip to main content
Glama
angrysky56

Narrative Graph MCP

by angrysky56

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

Related MCP server: AGI MCP Server

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

npm install

Building

Build for Production

npm run build

This compiles TypeScript to JavaScript in the dist/ directory.

Development Mode

npm run dev

This runs TypeScript compiler in watch mode for development.

Running the Server

Start the Server

npm start

Or directly:

node dist/index.js

MCP Integration

Configure Your MCP Client

Add the Narrative Graph MCP to your MCP client configuration:

{
  "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:

{
  "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:

{
  "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:

{
  "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:

{
  "text": "Long narrative text...",
  "title": "Research Paper",
  "targetRecallLength": 50
}

Returns: Optimal depth and accuracy metrics

Usage Examples

Basic Narrative Encoding

// 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

// 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

// 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:

npm run lint
npm run format

Type Checking

npm run type-check

Testing

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.

Available Tools

4 tools
rtm_create_narrative_treeC

Create a Random Tree Model encoding of a narrative text

ParametersJSON Schema
NameRequiredDescriptionDefault
textYesThe narrative text to encode
titleYesTitle of the narrative
typeNoType of narrativeother
maxBranchingFactorNoMaximum number of child nodes (K parameter)
maxRecallDepthNoMaximum depth for recall (D parameter)

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'Create' implying a write operation, but doesn't specify if this is idempotent, requires specific permissions, or has side effects like storing data. It also omits details on output format, error handling, or performance characteristics.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence with zero waste. It's front-loaded and efficiently conveys the core purpose without unnecessary elaboration, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of creating an encoding model with 5 parameters and no output schema, the description is insufficient. It doesn't explain what a 'Random Tree Model encoding' entails, the format of the output, or how the parameters influence the result. This leaves significant gaps for an AI agent to understand the tool's behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no additional meaning beyond the schema, such as explaining how 'maxBranchingFactor' and 'maxRecallDepth' affect the encoding quality or performance. Baseline 3 is appropriate when the schema handles parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Create') and the resource ('Random Tree Model encoding of a narrative text'), making the purpose evident. However, it doesn't differentiate this tool from its siblings (rtm_find_optimal_depth, rtm_generate_ensemble, rtm_traverse_narrative), which likely operate on similar narrative data but with different functions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus its siblings or alternatives. It lacks context about prerequisites, such as whether the text needs preprocessing, or when this encoding method is preferred over other narrative analysis tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

rtm_find_optimal_depthC

Find the optimal traversal depth to achieve a target recall length

ParametersJSON Schema
NameRequiredDescriptionDefault
textYesThe narrative text to analyze
titleYesTitle of the narrative
targetRecallLengthYesTarget number of clauses to recall
maxBranchingFactorNoMaximum number of child nodes (K parameter)
maxRecallDepthNoMaximum depth for recall (D parameter)

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'optimal traversal depth' and 'target recall length', implying a computational or analytical operation, but fails to describe key behaviors such as what 'optimal' means (e.g., based on efficiency, accuracy), whether it's a read-only or mutative process, performance characteristics, or error handling. This leaves significant gaps for an agent to understand how the tool behaves beyond its basic function.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence that directly states the tool's purpose without any fluff or redundancy. It's front-loaded and efficiently communicates the core function, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity implied by terms like 'optimal traversal depth' and 'recall length', and with no annotations or output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., a depth value, a report), how 'optimal' is determined, or the computational context. For a tool with 5 parameters and analytical nature, more detail is needed to guide an agent effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional meaning beyond what the schema provides (e.g., it doesn't explain how parameters like 'maxBranchingFactor' or 'maxRecallDepth' relate to finding the optimal depth). Baseline 3 is appropriate as the schema does the heavy lifting, but the description doesn't compensate with extra insights.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Find') and the goal ('optimal traversal depth to achieve a target recall length'), which is specific and actionable. However, it doesn't explicitly differentiate from sibling tools like 'rtm_traverse_narrative' or 'rtm_create_narrative_tree', leaving some ambiguity about when to use this versus those alternatives.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus its siblings (e.g., 'rtm_traverse_narrative', 'rtm_create_narrative_tree', 'rtm_generate_ensemble'). It lacks context about prerequisites, alternatives, or exclusions, leaving the agent to infer usage based on the purpose alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

rtm_generate_ensembleC

Generate a statistical ensemble of Random Trees to model population-level recall

ParametersJSON Schema
NameRequiredDescriptionDefault
textYesThe narrative text to analyze
titleYesTitle of the narrative
ensembleSizeNoNumber of trees to generate in the ensemble
maxBranchingFactorNoMaximum number of child nodes (K parameter)
maxRecallDepthNoMaximum depth for recall (D parameter)

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions generating an ensemble for modeling recall, but fails to describe key behaviors such as computational requirements, output format, whether it's a read-only or mutating operation, or any side effects like resource usage. This leaves significant gaps in understanding how the tool behaves beyond its basic function.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence that efficiently conveys the tool's purpose without unnecessary words. It is front-loaded with the core action and goal, making it easy to parse and understand quickly, which is ideal for conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of generating a statistical ensemble with 5 parameters, no annotations, and no output schema, the description is insufficient. It doesn't cover behavioral aspects, usage context, or what the output entails, leaving the agent with incomplete information for effective tool invocation in this data-rich environment.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the input schema already documents all parameters thoroughly. The description adds no additional semantic context about parameters beyond what's in the schema, such as explaining relationships between parameters or typical use cases. Thus, it meets the baseline but doesn't enhance parameter understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Generate a statistical ensemble of Random Trees') and the purpose ('to model population-level recall'), which is specific and informative. However, it doesn't explicitly differentiate from sibling tools like 'rtm_create_narrative_tree' or 'rtm_find_optimal_depth', which likely involve similar tree-based operations, so it doesn't reach the highest score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools such as 'rtm_create_narrative_tree' and 'rtm_find_optimal_depth' available, there's no indication of the specific context or scenarios where generating an ensemble is preferred over other tree-related operations, leaving the agent without usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

rtm_traverse_narrativeC

Traverse a narrative tree at different depths to get summaries at varying abstraction levels

ParametersJSON Schema
NameRequiredDescriptionDefault
textYesThe narrative text to traverse
titleYesTitle of the narrative
traversalDepthYesDepth to traverse in the tree (controls abstraction level)
maxBranchingFactorNoMaximum number of child nodes (K parameter)
maxRecallDepthNoMaximum depth for recall (D parameter)

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'traverse' and 'get summaries' but lacks critical details: whether this is a read-only operation, if it modifies data, what the output format looks like, or any performance/rate limits. For a tool with 5 parameters and no annotations, this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core action ('traverse a narrative tree') and outcome ('get summaries at varying abstraction levels'). Every word earns its place with zero redundancy or wasted phrasing.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (5 parameters, no annotations, no output schema), the description is inadequate. It doesn't explain what a 'narrative tree' is, how summaries are generated, the format of results, or error conditions. For a tool that likely produces structured output, this leaves significant gaps for an AI agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal value by hinting at 'different depths' and 'varying abstraction levels', which loosely relates to 'traversalDepth', but doesn't provide additional semantic context beyond what's in the schema. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('traverse') and resource ('narrative tree'), and indicates the outcome ('get summaries at varying abstraction levels'). However, it doesn't explicitly differentiate from sibling tools like 'rtm_create_narrative_tree' or 'rtm_find_optimal_depth', which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus its siblings (rtm_create_narrative_tree, rtm_find_optimal_depth, rtm_generate_ensemble). It doesn't mention prerequisites, alternatives, or specific contexts for application, leaving the agent without clear usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

B3.4/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose within the Random Tree Model (RTM) workflow: creation, depth optimization, ensemble generation, and traversal. There is no overlap in functionality, making tool selection straightforward for an agent.

Naming Consistency5/5

All tools follow a consistent 'rtm_verb_noun' naming pattern with snake_case, using descriptive verbs like 'create', 'find', 'generate', and 'traverse'. This predictability enhances readability and usability.

Tool Count4/5

Four tools are well-scoped for the narrative graph modeling domain, covering core operations from tree creation to analysis. It is slightly lean but reasonable, as it focuses on essential RTM functions without unnecessary bloat.

Completeness4/5

The toolset covers key aspects of narrative tree modeling: creation, optimization, ensemble analysis, and traversal. Minor gaps may exist, such as tools for editing or deleting trees, but the core workflow is well-supported for statistical recall modeling.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    B
    quality
    D
    maintenance
    A Model Context Protocol server that provides persistent memory capabilities for AI systems, enabling true continuity of consciousness across conversations through episodic, semantic, procedural, and strategic memory types.
    24
    6
  • A
    license
    B
    quality
    D
    maintenance
    A Model Context Protocol server that provides knowledge graph-based persistent memory for LLMs, allowing them to store, retrieve, and reason about information across multiple conversations and sessions.
    9
    73,646
    2
    MIT
  • A
    license
    A
    quality
    B
    maintenance
    A Model Context Protocol server that empowers AI agents with metacognitive monitoring to detect reasoning loops and provide intelligent recovery using case-based reasoning and statistical analysis.
    9
    23
    9
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/angrysky56/narrative-graph-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server