Skip to content

MCP Server

The MemoryLayer MCP server (@scitrera/memorylayer-mcp-server) gives LLM agents memory tools to store, recall, synthesize, and manage information across sessions via the Model Context Protocol. It exposes 28 tools in the default cc profile and 40 in the full profile. It wraps the TypeScript SDK and talks to any MemoryLayer server over HTTP.

The same server is used by the Claude Code, Codex, and OpenCode integrations.

Installation

Terminal window
npm install @scitrera/memorylayer-mcp-server

Requires Node.js 18 or later. The package installs a memorylayer-mcp executable. You can also run it on demand with npx @scitrera/memorylayer-mcp-server.

Quick Start

Terminal window
# Set environment variables
export MEMORYLAYER_URL=http://localhost:61001
export MEMORYLAYER_WORKSPACE_ID=my-workspace
# Run the server (stdio transport)
npx memorylayer-mcp

Configuration for Claude Code

Add .mcp.json to your project root:

{
"mcpServers": {
"memorylayer": {
"command": "npx",
"args": ["@scitrera/memorylayer-mcp-server"],
"env": {
"MEMORYLAYER_URL": "http://localhost:61001"
}
}
}
}

Auto-workspace detection: Claude Code starts MCP servers from the project directory, so the server uses your git repo name (or directory name) as the workspace ID. Each project gets its own memory automatically.

Or via CLI:

Terminal window
claude mcp add --transport stdio memorylayer \
--env MEMORYLAYER_URL=http://localhost:61001 \
-- npx @scitrera/memorylayer-mcp-server

For hooks, slash commands, and pre-compaction transcript capture on top of the MCP tools, install the Claude Code plugin instead.

Configuration for Claude Desktop

Add to claude_desktop_config.json (~/Library/Application Support/Claude/ on macOS, %APPDATA%\Claude\ on Windows):

{
"mcpServers": {
"memorylayer": {
"command": "npx",
"args": ["@scitrera/memorylayer-mcp-server"],
"env": {
"MEMORYLAYER_URL": "http://localhost:61001",
"MEMORYLAYER_WORKSPACE_ID": "my-project"
}
}
}
}

Claude Desktop doesn’t start the server in a per-project directory, so set MEMORYLAYER_WORKSPACE_ID explicitly. Otherwise every conversation lands in whichever workspace the launch directory happens to resolve to.

Configuration for Other MCP Clients

Any MCP client that can launch a stdio server works the same way. Clients that use the mcpServers JSON format, such as Cursor (.cursor/mcp.json in the project or ~/.cursor/mcp.json globally), take the same block as Claude Desktop. Set MEMORYLAYER_WORKSPACE_ID whenever the client doesn’t launch the server from your project directory.

Environment Variables

VariableDescriptionDefault
MEMORYLAYER_URLBase URL for the MemoryLayer APIhttp://localhost:61001
MEMORYLAYER_API_KEYAPI key for authentication—
MEMORYLAYER_WORKSPACE_IDWorkspace ID (overrides auto-detection)auto-detected
MEMORYLAYER_AUTO_WORKSPACESet to false to turn off auto-detection. If no workspace ID is set either, the server uses defaulttrue
MEMORYLAYER_TOOL_PROFILETool profile: cc, full, or minimal. Unknown values fall back to cccc
MEMORYLAYER_AUTO_START_SESSIONSet to false (or 0) to stop the server from starting a session automatically when it launchestrue

Tool Profiles

Three tool profiles control which tools the LLM sees. Set the profile with the MEMORYLAYER_TOOL_PROFILE environment variable.

ProfileToolsIntended use
cc (default)28Coding agents: core memory, sessions and context packs, context sandbox, chat threads, read-only skills
full40Everything: adds graph, audit/statistics, destructive chat tools, skills_save, and the MCP-server registry
minimal2memory_remember and memory_recall only

cc — Coding Agents (Default)

The recommended profile for Claude Code, Codex, and OpenCode. Provides 28 tools:

  • Core memory: memory_remember, memory_recall, memory_reflect, memory_forget
  • Utility: memory_briefing
  • Sessions: memory_session_start, memory_session_end, memory_session_commit, memory_session_status, memory_session_checkpoint
  • Context packs: memory_context_pack, memory_context_delta
  • Context environment: all 8 memory_context_* sandbox tools
  • Chat history: chat_thread_create, chat_thread_append, chat_thread_get, chat_thread_list
  • Skills (read): skills_list, skills_get, skills_get_file, skills_search

To keep the tool list short, cc leaves out the advanced tools (memory_associate, memory_statistics, memory_graph_query, memory_audit), the destructive chat tools (chat_thread_decompose, chat_thread_delete), skills_save, and the mcp_servers_* registry tools.

full — All Tools

Enables all 40 tools. Use it for power-user work, debugging, or graph-based memory. On top of cc it adds:

  • memory_associate: graph building
  • memory_statistics: workspace analytics (placeholder that currently returns zero values)
  • memory_graph_query: multi-hop graph traversal
  • memory_audit: contradiction detection (placeholder that currently performs no audit)
  • chat_thread_decompose: memory extraction from threads
  • chat_thread_delete: thread deletion
  • skills_save: create or update skills
  • mcp_servers_list, mcp_servers_get, mcp_servers_save, mcp_servers_delete, mcp_servers_import: the MCP server registry

minimal — Essentials Only

Just 2 tools: memory_remember and memory_recall. Use it for testing or very constrained environments.

Complete Tool Reference

Core Memory Tools

memory_remember

Store a new memory for later recall. Use it for facts, preferences, decisions, or events worth remembering.

ParameterTypeRequiredDefaultDescription
contentstringYes—The memory content to store
typestringNo—Memory type: episodic (events), semantic (facts), procedural (how-to), working (current context)
importancenumberNo0.5Importance from 0 to 1. Higher values are kept longer and rank higher in recall
tagsstring[]No—Tags for categorization (e.g., ["python", "bug-fix"])
subtypestringNo—Domain classification: solution, problem, code_pattern, fix, error, workflow, preference, decision, directive
metadataobjectNo—Arbitrary memory metadata
relationsobject[]No—Explicit typed entity relations evidenced by this memory. Each item needs relationship. Optional fields: source_entity_id/source_entity_name, target_entity_id/target_entity_name, and confidence (0-1)
{
"content": "User prefers TypeScript for new projects",
"type": "semantic",
"importance": 0.8,
"tags": ["preference", "typescript"],
"subtype": "preference"
}

memory_recall

Search memories by semantic query. Returns relevant memories ranked by relevance.

ParameterTypeRequiredDefaultDescription
querystringYes—Natural language query (e.g., “How do I fix authentication errors?”)
typesstring[]No—Filter by memory types: episodic, semantic, procedural, working
limitintegerNo10Max memories to return (1-100)
min_relevancenumberNoserver defaultMin relevance score (0-1)
tagsstring[]No—Filter by tags (AND logic)
budget_tokensintegerNo—Hard cap on the estimated tokens of returned memory content
include_confidencebooleanNotrueInclude deterministic retrieval-confidence metadata
include_relationsbooleanNotrueAllow bounded typed-relation retrieval when the server enables it
{
"query": "What are the user's coding preferences?",
"limit": 10,
"min_relevance": 0.5,
"types": ["semantic"],
"tags": ["preference"]
}

memory_reflect

Synthesize and summarize memories that match a query. Use it when you need insight across many memories rather than individual results.

ParameterTypeRequiredDefaultDescription
querystringYes—What to reflect on
detail_levelstringNoserver defaultLevel of detail: abstract (brief), overview (medium), full (detailed)
include_sourcesbooleanNotrueInclude source memory IDs in response
depthintegerNo2Association traversal depth, how many hops to follow (1-5)
{
"query": "What patterns have we seen with database performance?",
"detail_level": "overview",
"include_sources": true,
"depth": 2
}

memory_forget

Delete or decay a memory that is outdated or incorrect. Use it sparingly, because old memories are still useful history.

ParameterTypeRequiredDefaultDescription
memory_idstringYes—ID of memory to forget
reasonstringNo—Why this memory should be forgotten (for audit trail)
hardbooleanNofalseHard delete (permanent) vs soft delete (recoverable)

memory_associate

Link two memories with a typed relationship. The links build a knowledge graph for traversal and causal reasoning.

Profile: full only

ParameterTypeRequiredDefaultDescription
source_idstringYes—Source memory ID
target_idstringYes—Target memory ID
relationshipstringYes—Relationship type (e.g., causes, solves, similar_to, part_of, related_to). See Relationships for the full ontology.
strengthnumberNo0.8Strength of association (0-1)
{
"source_id": "mem_problem",
"target_id": "mem_solution",
"relationship": "solves",
"strength": 0.9
}

memory_briefing

Get a session briefing that summarizes recent activity and context. It returns workspace stats and recent memory content at a configurable detail level. Use it at session start or after compaction to regain context.

ParameterTypeRequiredDefaultDescription
time_window_minutesnumberNo60Time window in minutes for recent memories
detail_levelstringNoabstractLevel of detail: abstract (summaries), overview (more detail), full (complete content)
limitnumberNo10Maximum number of recent memories to include (max: 50)
include_memoriesbooleanNotrueWhether to include recent memory content
include_contradictionsbooleanNotrueFlag contradicting memories in briefing

memory_statistics

Get memory statistics and analytics for the workspace. This is currently a placeholder that returns zero values.

Profile: full only

ParameterTypeRequiredDefaultDescription
include_breakdownbooleanNotrueInclude breakdown by type/subtype

memory_graph_query

Traverse the memory graph across multiple hops to find related memories. Use it to discover causal chains or knowledge paths.

Profile: full only

ParameterTypeRequiredDefaultDescription
start_memory_idstringYes—Starting memory ID
relationship_typesstring[]No—Filter by relationship types (e.g., ["causes", "triggers"])
max_depthintegerNo3Maximum traversal depth (1-5)
directionstringNobothTraversal direction: outgoing, incoming, both
max_pathsintegerNo50Maximum paths to return
{
"start_memory_id": "mem_abc123",
"relationship_types": ["causes", "triggers"],
"max_depth": 3,
"direction": "both"
}

memory_audit

Audit memories for contradictions and inconsistencies. This is currently a placeholder that performs no audit.

Profile: full only

ParameterTypeRequiredDefaultDescription
memory_idstringNo—Specific memory to audit (omit to audit entire workspace)
auto_resolvebooleanNofalseAutomatically mark newer contradicting memories as preferred

Session Management Tools

See Sessions & Working Memory for the underlying model.

memory_session_start

Start a new session for working memory. The server starts one automatically when it launches (unless MEMORYLAYER_AUTO_START_SESSION=false), and the Claude Code SessionStart hook starts one too, but you can also call it manually. After context compaction, call memory_context_inspect to see the sandbox state that is still on the server.

ParameterTypeRequiredDefaultDescription
metadataobjectNo—Optional metadata to attach to the session

memory_session_end

End the current session and optionally commit working memory to long-term storage.

ParameterTypeRequiredDefaultDescription
commitbooleanNotrueWhether to commit working memory to long-term storage
importance_thresholdnumberNo0.5Minimum importance for extracted memories (0-1)

memory_session_commit

Commit working memory to long-term storage without ending the session. Use it for checkpoints during long sessions or before likely interruptions. The session stays active after the commit.

ParameterTypeRequiredDefaultDescription
importance_thresholdnumberNo0.5Minimum importance for extracted memories (0-1)
clear_after_commitbooleanNofalseClear working memory after commit (session stays active)

memory_session_status

Get the current session status, including a working memory summary. Use it to check whether a session is active. No parameters.

memory_session_checkpoint

Durably capture a raw transcript segment, typically right before compaction. The raw capture is stored first; derived indexing and enrichment never block it. The Claude Code and OpenCode plugins call this automatically before compaction.

ParameterTypeRequiredDefaultDescription
transcript_segmentstringYes—Exact raw transcript segment to preserve
content_hashstringYes—Lowercase SHA-256 hex digest of the UTF-8 segment
idempotency_keystringYes—Stable key for safe retry
source_kindstringNotranscriptLabel for the transcript source
source_sequenceintegerNo—Optional source sequence number (≥ 0)
source_boundaryintegerNo—Optional source offset/boundary (≥ 0)

memory_context_pack

Build one deterministic, hard-budgeted payload for resuming a session. It covers directives, working memory, recent activity, contradictions, a sandbox summary, and checkpoint recovery. The response includes a signed cursor that you can pass to memory_context_delta.

ParameterTypeRequiredDefaultDescription
topicstringNo—Optional topic focus
entity_idsstring[]No—Focus on these entity IDs
entity_namesstring[]No—Focus on these entity names
budget_tokensintegerNo2048Hard token budget (min 32)
section_limitsobjectNo—Per-section item caps
include_directivesbooleanNotrueInclude directives
include_working_memorybooleanNotrueInclude working memory
include_recent_activitybooleanNotrueInclude recent activity
include_contradictionsbooleanNotrueInclude contradictions
include_sandbox_summarybooleanNotrueInclude a sandbox summary
include_checkpoint_recoverybooleanNotrueInclude recovery from raw checkpoints

memory_context_delta

Return the context changes and tombstones since a signed context-pack cursor, collapsed and kept within a hard token budget.

ParameterTypeRequiredDefaultDescription
cursorstringYes—Cursor from a context pack or a prior delta
budget_tokensintegerNo2048Hard token budget (min 32)

Context Environment Tools

These tools give the agent a persistent Python execution environment on the server. Sandbox state survives context compaction, so call memory_context_inspect after compaction to see what is still there. See Context Environment.

memory_context_exec

Run Python code in the server-side sandbox. Variables from earlier exec calls are still available. Use it to transform, analyze, and compute over loaded memories.

ParameterTypeRequiredDefaultDescription
codestringYes—Python code to execute. Variables from prior exec calls are available.
result_varstringNo—Store the expression result in this variable name
return_resultbooleanNotrueReturn execution output to caller. Set false for large intermediate results.
max_return_charsintegerNo10000Maximum characters to return. Output beyond this is truncated.

memory_context_inspect

Inspect variables in the server-side sandbox. Omit the variable name for an overview of all variables, or name one for a detailed view. Call it after context compaction or when continuing a session to see the current sandbox state.

ParameterTypeRequiredDefaultDescription
variablestringNo—Inspect a specific variable. Omit for overview of all variables.
preview_charsintegerNo200Characters to include in value previews

memory_context_load

Load memories from the store into a sandbox variable with a semantic search. The loaded memories are then available to the exec, query, and RLM tools.

ParameterTypeRequiredDefaultDescription
varstringYes—Variable name to store loaded memories
querystringYes—Semantic search query
limitintegerNo50Maximum memories to load
typesstring[]No—Filter by memory types
tagsstring[]No—Filter by tags
min_relevancenumberNo—Minimum relevance score (0-1)
include_embeddingsbooleanNofalseInclude embedding vectors (large)

memory_context_inject

Store a value in the server-side sandbox as a named variable. Use it to pass data from the client into the execution environment.

ParameterTypeRequiredDefaultDescription
keystringYes—Variable name in sandbox
valuestringYes—Value to store (string, JSON string, or code snippet)
parse_jsonbooleanNofalseParse value as JSON before storing (creates dict/list, not string)

memory_context_query

Ask the server-side LLM a question, with sandbox variables as context. The LLM reads the variable data and answers your prompt.

ParameterTypeRequiredDefaultDescription
promptstringYes—Question or instruction for the server LLM
variablesstring[]Yes—Variable names to include as context
max_context_charsintegerNoserver defaultMax chars of variable data to send to LLM
result_varstringNo—Store LLM response in this variable

memory_context_rlm

Run a Recursive Language Model (RLM) loop. The server LLM reasons over sandbox data and memories in repeated passes toward a goal, then returns a synthesis of its findings.

ParameterTypeRequiredDefaultDescription
goalstringYes—Natural language goal for the RLM loop
memory_querystringNo—Semantic query to pre-load memories before the loop starts
memory_limitintegerNo100Max memories to pre-load
max_iterationsintegerNo10Maximum RLM loop iterations (1-50)
variablesstring[]No—Existing sandbox variables to include as context
result_varstringNo—Store the final synthesis in this variable
detail_levelstringNostandardDetail level: brief, standard, detailed

memory_context_status

Get the status of the server-side context environment: sandbox state, active variables, and resource usage. Use it after context compaction to check whether a sandbox environment still exists. No parameters.

memory_context_checkpoint

Checkpoint the sandbox state for persistence. This fires persistence hooks so that deployments with durable sandbox storage, such as MemoryLayer Enterprise, can save the state. It does nothing on default in-memory deployments. No parameters.

Chat History Tools

chat_thread_create

Create a new chat thread for storing conversation history. Threads keep their messages over time and can be automatically decomposed into memories.

ParameterTypeRequiredDefaultDescription
thread_idstringNoauto-generatedClient-provided thread ID
user_idstringNo—User who owns this conversation
observer_idstringNo—Observer entity ID (typically the AI agent)
subject_idstringNo—Subject entity ID (typically the human user)
titlestringNo—Optional display title
metadataobjectNo—Arbitrary metadata

chat_thread_append

Append messages to a chat thread. Messages are stored persistently and are decomposed into memories once a threshold is reached.

ParameterTypeRequiredDefaultDescription
thread_idstringYes—Thread to append to
messagesobject[]Yes—Messages to append. Each message has role (required: user/assistant/system/tool), content (required, string or structured blocks), and optional metadata.

chat_thread_get

Get a chat thread with its messages. Returns the thread metadata and a page of messages.

ParameterTypeRequiredDefaultDescription
thread_idstringYes—Thread ID to retrieve
limitintegerNo100Max messages to return
offsetintegerNo0Message pagination offset
orderstringNoascMessage order: asc or desc

chat_thread_list

List chat threads in the workspace, optionally filtered by user.

ParameterTypeRequiredDefaultDescription
user_idstringNo—Filter by user ID
limitintegerNo50Max threads to return
offsetintegerNo0Pagination offset

chat_thread_decompose

Trigger memory decomposition for a thread’s unprocessed messages, extracting memories from the chat history.

Profile: full only

ParameterTypeRequiredDefaultDescription
thread_idstringYes—Thread to decompose

chat_thread_delete

Delete a chat thread and all its messages.

Profile: full only

ParameterTypeRequiredDefaultDescription
thread_idstringYes—Thread to delete

Skills Tools

Skills are reusable agent knowledge units (SKILL.md plus optional bundle files) stored in MemoryLayer. See Skills & MCP Servers.

skills_list

List available agent skills. Returns the name, description, version, and scope of each skill.

ParameterTypeRequiredDefaultDescription
namestringNo—Filter by exact skill name
enabledbooleanNoonly enabledFilter by enabled status
include_shadowedbooleanNo—Include skills shadowed by a higher-scope skill with the same name
limitintegerNo100Maximum skills to return (1-500)
offsetintegerNo0Pagination offset

skills_get

Fetch the full SKILL.md for a skill: its frontmatter plus the instruction markdown. Provide either skill_id or name.

ParameterTypeRequiredDefaultDescription
skill_idstringNo—Skill ID (skl_...)
namestringNo—Skill name, resolved by the server if skill_id is not provided

skills_get_file

Fetch a single file (script, reference, or asset) from a skill’s bundle. Returns text content or base64-encoded binary.

ParameterTypeRequiredDefaultDescription
skill_idstringYes—Skill ID (skl_...)
pathstringYes—Relative path within the bundle (e.g. scripts/extract.py)

Search for skills by intent or description with vector recall.

ParameterTypeRequiredDefaultDescription
querystringYes—Natural language description of the capability you need
limitintegerNo10Maximum candidate skills to return (1-50)

skills_save

Create or update a skill. Every agent that shares the workspace can then use it.

Profile: full only

ParameterTypeRequiredDefaultDescription
namestringYes—Skill name (1-64 chars, lowercase letters/digits/hyphens)
descriptionstringYes—Skill description (1-1024 chars)
bodystringNo—SKILL.md body markdown
versionstringNo0.1.0Skill version
licensestringNo—License identifier (e.g. MIT)
compatibilitystringNo—Compatibility notes (max 500 chars)
allowed_toolsstringNo—Space-separated tool allowlist (experimental)
source_modestringNoserverWhere canonical storage lives: server, filesystem, mirrored
metadataobjectNo—Arbitrary metadata
filesobject[]No—Optional bundle files (scripts, references, assets)

MCP Server Registry Tools

Store and share MCP server definitions in MemoryLayer. All five tools are available in the full profile only.

ToolRequired parametersDescription
mcp_servers_list—List registered MCP servers. Optional filters: transport (stdio, http, sse, streamable-http), enabled, name, limit (default 100), offset
mcp_servers_getserver_id or nameFetch a single server record
mcp_servers_savename, transportCreate or update a server by name. Optional: command, args, env, url, headers, description, enabled (default true), metadata. env and headers values are stored as secrets
mcp_servers_deleteserver_idDelete a server record
mcp_servers_importmcpServersBulk import from an mcpServers object (the .mcp.json / claude_desktop_config.json format). Returns imported, updated, and error counts

Workspace Detection

The server picks your workspace in this order:

  1. MEMORYLAYER_WORKSPACE_ID environment variable (explicit override)
  2. Git remote origin: the repo name from the remote URL
  3. Git root directory: the name of the root folder
  4. Current directory: the name of the current working directory

Steps 2-4 run only while MEMORYLAYER_AUTO_WORKSPACE is not false.

Programmatic Usage

import { MemoryLayerClient, createServer } from "@scitrera/memorylayer-mcp-server";
const client = new MemoryLayerClient({
baseUrl: "http://localhost:61001",
workspaceId: "my-workspace",
apiKey: "optional-api-key",
});
const server = await createServer(client, { toolProfile: "full" });
await server.run();

MEMORYLAYER_TOOL_PROFILE, when set, overrides the toolProfile option.