In-Memory Knowledge Structure Validator
This utility manages interconnected data entities within an application's operational memory space. It enforces rigorous structural checks to guarantee data integrity across the knowledge graph. Drawing parallels to operating system resource control, this tool dynamically allocates and tracks relationships, akin to how virtual memory separates logical from physical addresses to enhance system capacity.
Author

evangstav
Quick Info
Actions
Tags
Introduction
This Model Context Protocol (MCP) server operates in volatile memory, focusing on organizing entities, their connections, and associated observations. Effective memory management, like that found in sophisticated operating systems, demands strict validation to prevent inconsistencies as data is created and modified.
Setup
To incorporate this server into a Claude Desktop environment, execute the following command:
mcp install main.py -v MEMORY_FILE_PATH=/path/to/memory.jsonl
Data Validation Rules
The system strictly governs the structure of stored information to maintain a reliable graph.
Entity Names
Entity identifiers must adhere to specific formatting standards:
- Begin with a lowercase alphabetic character.
- Comprise only lowercase letters, numerals, and hyphen characters.
- The length must not exceed one hundred characters.
- Each name must be unique across the entire graph structure.
- Examples of acceptable names are: python-project, meeting-notes-2024, user-john.
Entity Types
This server recognizes several predefined categories for structuring information:
- person: Represents human individuals.
- concept: Denotes abstract notions or foundational principles.
- project: Identifies specific work initiatives or structured tasks.
- document: Covers any form of recorded textual or digital material.
- tool: Refers to software utilities or mechanical apparatuses.
- organization: Designates formal companies or collaborative groups.
- location: Specifies physical or abstract positioning.
- event: Marks occurrences tied to a specific timeline.
Observations
These textual notes attached to entities have constraints: - They must contain textual content; empty strings are disallowed. - Maximum permissible length is five hundred characters. - Each observation must be unique when associated with a single entity. - Statements are expected to be objective records rather than subjective opinions. - It is recommended practice to affix a timestamp when the observation relates to a specific time.
Relations
Connections between two entities are restricted to these defined types:
- knows: Indicates a connection between two individuals.
- contains: Establishes a hierarchical part-to-whole structure.
- uses: Shows one entity employing another entity.
- created: Designates authorship or the origin of an entity.
- belongs-to: Defines membership or ownership association.
- depends-on: Signals a prerequisite relationship between elements.
- related-to: A general-purpose link for less specific connections.
Additional requirements for creating links include: - Both the originating and destination entities must already exist in the graph. - An entity cannot form a relation pointing back to itself. - Cycles or circular dependencies within the relationship structure are prohibited. - Only the listed relation types are permissible for use.
Usage
The server exposes several methods for interacting with the stored knowledge structure:
Get Entity
To retrieve specific entity data, call the tool as shown below:
result = await session.call_tool("get_entity", {
"entity_name": "example"
})
if not result.success:
if result.error_type == "NOT_FOUND":
print(f"Entity not found: {result.error}")
elif result.error_type == "VALIDATION_ERROR":
print(f"Invalid input: {result.error}")
else:
print(f"Error: {result.error}")
else:
entity = result.data
print(f"Found entity: {entity}")
Get Graph
This allows for the extraction of the entire graph structure currently held in memory:
result = await session.call_tool("get_graph", {})
if result.success:
graph = result.data
print(f"Graph data: {graph}")
else:
print(f"Error retrieving graph: {result.error}")
Create Entities
Multiple new entries can be instantiated concurrently, subject to validation checks:
# Valid entity creation
entities = [
Entity(
name="python-project", # Lowercase with hyphens
entityType="project", # Must be a valid type
observations=["Started development on 2024-01-29"]
),
Entity(
name="john-doe",
entityType="person",
observations=["Software engineer", "Joined team in 2024"]
)
]
result = await session.call_tool("create_entities", {
"entities": entities
})
if not result.success:
if result.error_type == "VALIDATION_ERROR":
print(f"Invalid entity data: {result.error}")
else:
print(f"Error creating entities: {result.error}")
Add Observation
New factual statements can be appended to existing data nodes:
# Valid observation
result = await session.call_tool("add_observation", {
"entity": "python-project",
"observation": "Completed initial prototype" # Must be unique for entity
})
if not result.success:
if result.error_type == "NOT_FOUND":
print(f"Entity not found: {result.error}")
elif result.error_type == "VALIDATION_ERROR":
print(f"Invalid observation: {result.error}")
else:
print(f"Error adding observation: {result.error}")
Create Relation
Links between entities are established using this specific tool call:
# Valid relation
result = await session.call_tool("create_relation", {
"from_entity": "john-doe",
"to_entity": "python-project",
"relation_type": "created" # Must be a valid type
})
if not result.success:
if result.error_type == "NOT_FOUND":
print(f"Entity not found: {result.error}")
elif result.error_type == "VALIDATION_ERROR":
print(f"Invalid relation data: {result.error}")
else:
print(f"Error creating relation: {result.error}")
Search Memory
This powerful method supports querying the knowledge base using natural language inputs:
result = await session.call_tool("search_memory", {
"query": "most recent workout" # Supports natural language queries
})
if result.success:
if result.error_type == "NO_RESULTS":
print(f"No results found: {result.error}")
else:
results = result.data
print(f"Search results: {results}")
else:
print(f"Error searching memory: {result.error}")
The search mechanism supports several advanced features for information retrieval: - It handles temporal phrasing like "most recent," "last," or "latest" naturally. - It recognizes queries pertaining to activities such as "workout" or "exercise." - Standard entity name searches are fully supported. - Fuzzy matching is implemented, utilizing an 80% similarity threshold for approximate matches. - Search results are weighted across different data fields for relevance: - Entity names receive the highest weighting (1.0). - Entity types are weighted moderately (0.8). - Observations contribute with a lower weight (0.6).
Delete Entities
Specific nodes and their associated links can be purged from the structure:
result = await session.call_tool("delete_entities", {
"names": ["python-project", "john-doe"]
})
if not result.success:
if result.error_type == "NOT_FOUND":
print(f"Entity not found: {result.error}")
else:
print(f"Error deleting entities: {result.error}")
Delete Relation
To remove a specific directional link between two entities:
result = await session.call_tool("delete_relation", {
"from_entity": "john-doe",
"to_entity": "python-project"
})
if not result.success:
if result.error_type == "NOT_FOUND":
print(f"Entity not found: {result.error}")
else:
print(f"Error deleting relation: {result.error}")
Flush Memory
This operation will clear all stored data from the current operational memory:
result = await session.call_tool("flush_memory", {})
if not result.success:
print(f"Error flushing memory: {result.error}")
Error Types
The system reports operational failures using distinct categorical codes:
NOT_FOUND: Indicates a requested entity or reference point is absent.VALIDATION_ERROR: Signals that provided input failed predefined structural rules.INTERNAL_ERROR: Points to an unexpected issue within the server's execution logic.ALREADY_EXISTS: Occurs when attempting to create an element that is already present.INVALID_RELATION: Specifically flags issues with the connection parameters between nodes.
Response Models
All interaction methods return structured answers conforming to these data schemas:
EntityResponse
class EntityResponse(BaseModel):
success: bool
data: Optional[Dict[str, Any]] = None
error: Optional[str] = None
error_type: Optional[str] = None
GraphResponse
class GraphResponse(BaseModel):
success: bool
data: Optional[Dict[str, Any]] = None
error: Optional[str] = None
error_type: Optional[str] = None
OperationResponse
class OperationResponse(BaseModel):
success: bool
error: Optional[str] = None
error_type: Optional[str] = None
Related Topics
- Dynamic Storage Allocation
- Virtual Memory Systems (Paging and Swapping)
- Application-level Memory Management
- Resource Allocation in Multitasking Environments
- Graph Databases and Data Integrity
Extra Details
While this tool manages data within the immediate runtime memory space, its integrity controls echo the necessity of careful memory handling in large operating systems, such as the Burroughs/Unisys MCP. Automated memory management techniques, unlike manual allocation, rely on robust internal schema enforcement to prevent corruption. The validation rules detailed above are essential for ensuring the application behaves predictably when querying or modifying relationships, optimizing how the knowledge structure is utilized.
Conclusion
By strictly applying these structural constraints on entities and their relations, this utility ensures that the knowledge graph remains a consistent and highly reliable information resource. This disciplined approach to in-memory data maintenance is fundamental for building applications that depend on complex, interconnected facts, similar to how efficient kernel memory managers support stable application execution.
