MemoFSMemoFS
API Reference

@memofs/server API Reference

Complete TypeScript API reference for @memofs/server: runtime assembly, HTTP core, Cloudflare Worker handler, and JSON-RPC dispatch.

The @memofs/server package exports the hosted runtime assembly factory, framework-free HTTP core request handlers, Cloudflare Worker adapters, and JSON-RPC 2.0 protocol dispatchers.

Assembly & Runtime Factories

createHostedRuntime(options: HostedRuntimeOptions): MemoFS

Assembles a unified MemoFS instance using an injected storage adapter and optional intelligence drivers (embedders, rerankers, extractors).

import { createHostedRuntime } from "@memofs/server";

const memofs = createHostedRuntime({
  store: memoryStore,
  projectId: "my-hosted-project",
  embedder: customEmbedder,
});

HostedRuntimeOptions

OptionTypeRequiredDescription
storeMemoryStoreYesBacking storage implementation (NodeFsMemoryStore, RemoteBlobMemoryStore, InMemoryMemoryStore).
projectIdstringYesProject identifier scoping this runtime.
embedderMemoryEmbedderNoText embedder instance for vector indexing.
recallStoreRecallStoreNoVector index store. Auto-wired when embedder is present.
rerankerRerankerNoReranking provider for recall candidates.
extractorExtractorNoEntity and relationship extractor for knowledge graphs.
llmClientLlmClientNoLLM transport for generative intelligence and consolidation.
namestringNoRuntime client name (default: "memofs-server").
versionstringNoRuntime version (default: "0.1.0").

HTTP Core Handlers

handleRuntimeRequest(request: Request, options: RuntimeHttpOptions): Promise<Response>

Framework-agnostic handler that processes HTTP requests containing standard JSON-RPC 2.0 payloads.

import { handleRuntimeRequest } from "@memofs/server";

const response = await handleRuntimeRequest(request, {
  runtime: memofs,
  requireAuth: true,
  bearerToken: process.env.MEMOFS_SERVER_TOKEN,
  allowedOrigins: ["https://app.example.com"],
});

RuntimeHttpOptions

OptionTypeRequiredDescription
runtimeMemoFSYesTarget runtime instance executing memory operations.
concurrencyLayerConcurrencyLayerNoInjected coordinator for gating/serializing mutating requests.
requireAuthbooleanNoRequire a bearer token on POST / (default: false).
bearerTokenstringNoThe expected bearer token when requireAuth is true.
allowedOriginsreadonly string[]NoAllowed browser Origin values for CORS preflight.

createRuntimeFetchHandler(options: RuntimeFetchHandlerOptions)

(Exported from @memofs/server/worker and @memofs/server)

Produces a standard Cloudflare Workers fetch(request, env, ctx) handler.

import { createRuntimeFetchHandler } from "@memofs/server/worker";

export default {
  fetch: createRuntimeFetchHandler({
    createRuntime: async (env, request) => {
      return createHostedRuntime({
        store: getR2Store(env),
        projectId: request.headers.get("x-project-id") ?? "default",
      });
    },
    requireAuth: false,
  }),
};

JSON-RPC 2.0 Protocol Methods

All requests are dispatched as standard JSON-RPC 2.0 objects ({ jsonrpc: "2.0", id: 1, method: "...", params: { ... } }).

Read-Only (Live) Methods

MethodParametersReturn ValueDescription
health{}MemoFSHealthResultLiveness check and component status.
recall{ query: string, limit?: number, filter?: RecallFilter }RecallResultSemantic and lexical retrieval.
contextMemoryContextInputMemoryContextResultFormatted markdown/context briefing.
memory.readCore{}stringContent of memory/core.md.
memory.readNotes{}stringContent of memory/notes.md.
memory.readConversations{ limit?: number }ConversationEntry[]Chronological conversation logs.
memory.listRecent{ limit?: number }RecentMemoryResultChronological log of recent memory events.
memory.validate{ strict?: boolean }ValidateMemoryResultIntegrity and schema validation check.
graph.listNodesListGraphInput{ items: GraphNodeInput[] }Entity nodes in knowledge graph.
graph.listEdgesListGraphInput{ items: GraphEdgeInput[] }Relationship edges in knowledge graph.
graph.neighborsGraphNeighborsInputGraphNeighborsResultRelated entities and connections.
graph.pathGraphPathInputGraphPathResultShortest relation path between entities.
snapshots.list{}SnapshotRecord[]Checkpoints and rollback history.

Mutating (Gated) Methods

Mutating methods require an active concurrencyLayer to serialize concurrent requests. When no concurrency layer is supplied, these methods safely return 503 Service Unavailable with CONCURRENCY_GATE_ERROR_CODE (-32000).

MethodParametersReturn ValueDescription
memory.writeWriteMemoryInputWriteMemoryResultStores a classified memory item.
memory.recordNoteTimestampedNoteInputWriteMemoryResultAppends a timestamped log note.
memory.updateCore{ content: string }voidOverwrites memory/core.md.
memory.appendConversationConversationEntryvoidAppends a conversation record.
graph.upsertNodes{ nodes: GraphNodeInput[] }{ nodes: GraphNodeInput[] }Updates knowledge graph entities.
graph.upsertEdges{ edges: GraphEdgeInput[] }{ edges: GraphEdgeInput[] }Updates knowledge graph relations.
consolidateConsolidateMemoryInputConsolidateMemoryResultMerges/retires overlapping memories.
snapshots.createSnapshotMemoryInputSnapshotMemoryResultTakes a point-in-time checkpoint.
snapshots.restore{ id: string }voidReverts filesystem to checkpoint.

Direct Dispatch Utilities

For custom network transports (WebSockets, IPC, Worker Service Bindings):

import { dispatchRuntimeMessage, dispatchRuntimeText } from "@memofs/server";

// Dispatches parsed JSON-RPC payload across the runtime
const response = await dispatchRuntimeMessage(
  memofs,
  { jsonrpc: "2.0", id: "req-1", method: "recall", params: { query: "auth" } },
  { concurrencyLayer: myMutex }
);

// Dispatches raw string payload
const rawResponseString = await dispatchRuntimeText(
  memofs,
  '{"jsonrpc":"2.0","id":1,"method":"health"}'
);

Protocol Constants

ConstantValue / TypeDescription
RUNTIME_METHODRecord<string, string>Canonical dictionary mapping symbolic keys to JSON-RPC method strings.
LIVE_METHODSReadonlySet<string>Set of live, read-only method names that execute concurrently without locking.
GATED_METHODSReadonlySet<string>Set of mutating method names requiring an injected concurrency layer.
CONCURRENCY_GATE_ERROR_CODE-32000Standard JSON-RPC server error code returned when mutating without concurrency layer.
CONCURRENCY_GATE_HTTP_STATUS503HTTP status code carried in gate failure payload data.
CONCURRENCY_GATE_MESSAGEstring"Concurrent writes require the concurrency layer. This method is read-only until it is injected."
concurrencyGateFailure(id)(id: JsonRpcId) => JsonRpcErrorResponseHelper function constructing the canonical 503 error envelope.

On this page