MemoFSMemoFS
Adapters

Vercel AI SDK Adapter

Vercel AI SDK adapter for MemoFS runtime bridging, tool definitions, and memory context builders.

The @memofs/adapter-ai-sdk adapter bridges MemoFS memory into Vercel AI SDK applications (ai package).

It provides ready-to-use tool definitions, progressive prompt context builders, and multi-tenant scoping policies (project, user, conversation) for generateText, streamText, and AI agent loops.

Installation

npm install @memofs/adapter-ai-sdk ai @ai-sdk/openai zod

Requires Node.js >= 22 and ai >= 5.0.0 < 7.0.0.

Usage

Create an AI SDK runtime bridge with createAiSdkRuntimeFromMemoFS() and inject memory tools into generateText:

import { createNodeMemoFs } from "@memofs/core/node-fs";
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";
import {
  createAiSdkRuntimeFromMemoFS,
  buildRuntimeMemoryToolDefinition,
  buildRuntimeMemoryContext,
} from "@memofs/adapter-ai-sdk";

// 1. Initialize MemoFS and bridge to AI SDK runtime
const memo = createNodeMemoFs({ rootDir: "." });
const runtime = createAiSdkRuntimeFromMemoFS(memo);

// 2. Build initial prompt context (core memory + relevant recall)
const memoryContext = await buildRuntimeMemoryContext({
  runtime,
  query: "What are our database choices?",
  includeCoreMemory: true,
  includeRecall: true,
});

// 3. Build Vercel AI SDK tool definition
const memoryTool = buildRuntimeMemoryToolDefinition({
  runtime,
  access: {
    projectId: "app-prod",
    userId: "usr_alice",
  },
  allowWrites: true,
  allowCoreUpdates: false,
});

// 4. Run AI generation with memory tool support
const response = await generateText({
  model: openai("gpt-4o"),
  system: `You are an AI assistant. Project Memory:\n${memoryContext.text}`,
  tools: {
    memory: memoryTool,
  },
  prompt: "Save a decision that we use Cloudflare D1 for our relational store.",
});

console.log(response.text);
import { createNodeMemoFs } from "@memofs/core/node-fs";
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
import {
  createAiSdkRuntimeFromMemoFS,
  buildRuntimeMemoryToolDefinition,
} from "@memofs/adapter-ai-sdk";

const memo = createNodeMemoFs({ rootDir: "." });
const runtime = createAiSdkRuntimeFromMemoFS(memo);

const result = streamText({
  model: openai("gpt-4o"),
  tools: {
    memory: buildRuntimeMemoryToolDefinition({
      runtime,
      allowWrites: true,
    }),
  },
  prompt: "What decisions have we recorded about API rate limits?",
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}

Supported Tool Commands

The tool generated by buildRuntimeMemoryToolDefinition exposes a Zod schema (runtimeMemoryToolInputSchema) supporting 7 unified commands:

CommandActionKey Parameters
read_core_memoryReads the root rules.md / core memory.None
update_core_memoryUpdates core rules (requires allowCoreUpdates: true).content
rememberStores a classified note in notes.md with tenant scoping.content, title?, kind?, tags?, scope?, metadata?
list_notesLists notes filtered by tenant access permissions.limit?, kind?, tag?
recallPerforms hybrid vector/keyword search with scope filters.query, topK?, strategy?, rerank?
build_contextAssembles formatted markdown context for prompt injection.query?, maxChars?, includeCoreMemory?, includeRecall?
indexTriggers asynchronous embedding index regeneration.mode?, force?

Multi-Tenant Scoping & Security Policies

@memofs/adapter-ai-sdk enforces tenant isolation and safety guardrails:

interface AccessContext {
  projectId: string;
  userId?: string;
  conversationId?: string;
  role?: "system" | "admin" | "user" | "guest";
}
  1. Scope Boundaries: Memories can be written at "project", "user", or "conversation" scope. Reads and recall queries automatically filter out records that belong to different users or conversations.
  2. Secret Guardrails: The tool scans content against private key and token regex patterns (assertSafeContent) before writing, rejecting accidental credential leaks unless allowSecrets: true is explicitly configured.
  3. Write Discipline: Scoped notes are saved with source: "ai-sdk" and carry structured provenance metadata.

Tool Configuration Options (RuntimeMemoryToolOptions)

OptionTypeDefaultDescription
runtimeMemoFSMemoryRuntime— (Required)Initialized runtime bridge from createAiSdkRuntimeFromMemoFS().
accessAccessContextMulti-tenant user and session identity metadata.
allowWritesbooleantrueWhether the model can write memories via the remember command.
allowCoreUpdatesbooleanfalseWhether the model is permitted to mutate rules.md.
allowIndexingbooleanfalseWhether to allow on-demand indexing commands.
allowSecretsbooleanfalseBypass secret scanning (for dedicated credential workflows only).
maxContentCharsnumber50000Maximum character length allowed for written memory notes.

Core Functions Reference

createAiSdkRuntimeFromMemoFS(memo)

Wraps any MemoFS client into a MemoFSMemoryRuntime adapter.

buildRuntimeMemoryToolDefinition(options)

Generates an AI SDK compatible tool definition with full Zod input schemas and execution handlers.

buildRuntimeMemoryContext(options)

Assembles a unified markdown prompt block combining core rules, relevant notes, and semantic recall results.

buildAgentSessionInstructions(options)

Generates system prompt instructions for agents executing inside AgentFS virtual workspace sessions.

See Also

On this page