GUIDE

Give an AI agent persistent key-value memory

Updated September 09, 2026 By microfn 2 min read
ai agent kv memory

An agent conversation is temporary. A Microfn function can keep small pieces of structured state between calls with @microfn/kv, then expose that function as a reusable MCP tool.

Create the memory function

import kv from "@microfn/kv";

type Input =
  | { action: "remember"; key: string; value: string }
  | { action: "recall"; key: string };

export async function main(input: Input) {
  const key = `agent-memory:${input.key}`;

  if (input.action === "remember") {
    await kv.set(key, input.value);
    return { saved: true, key: input.key };
  }

  const value = await kv.get<string>(key);
  return { key: input.key, value: value ?? null };
}

Deploy the function, run a remember call, then run recall with the same key. Enable Direct MCP Tool under Triggers if you want the connected agent to call it by name.

Example agent conversation
You

Remember that my preferred deployment region is eu-west-1.

Agent

I’ll store that preference in your Microfn memory tool.

fn_agent_memory

{"saved":true,"key":"deployment-region"}

You

Which deployment region do I prefer?

fn_agent_memory

{"key":"deployment-region","value":"eu-west-1"}

Agent

Your stored preference is eu-west-1.

Keep the scope narrow

Use explicit keys and store only data the function needs. This example has no delete or list operation, so it is a small preference store rather than a general database. Do not store API keys, access tokens, or sensitive personal data in KV; use function secrets for credentials.

Related guides

All guides