November 12, 2026
Custom AI Agent with Memory: A Runnable MCP Setup
Build a custom AI agent with memory using readable project files, MCP, scoped writes, and a practical persistence and correction test.
A custom AI agent with memory needs more than a database that survives a restart. It needs a rule for what becomes durable, a scope that prevents one user or project from reading another's facts, and a correction path when yesterday's memory becomes wrong. Without those controls, persistence can make an agent consistently wrong rather than reliably useful.
For project knowledge, a strong default is memory stored as files people can read, edit, version, and self-host. Retrieval indexes can still help, but they should point to a source your team owns. Meshnote provides that source as linked Markdown pages exposed to any compatible agent through MCP.
Start with three memory scopes
Do not put every message into one long-term store. Separate memory by lifetime and authority:
| Scope | What belongs there | Typical storage |
|---|---|---|
| Working | The current task, recent tool output, an unfinished plan | Context window or session state |
| User or agent | Preferences and reusable observations tied to one identity | Scoped records, vector memory, or a managed memory layer |
| Project | Decisions, runbooks, architecture, source-backed research | Readable, versioned pages with explicit write rules |
This boundary is more important than the storage brand. A support agent may use Redis or a framework checkpointer for thread continuity, Mem0 for extracted user preferences, and Markdown for the approved escalation procedure. The systems are complementary when each one has a declared job. The AI agent memory architecture guide explains the broader working, episodic, semantic, procedural, and project-memory model.
Build the loop around MCP
The Model Context Protocol gives a custom harness a standard tool surface instead of a bespoke memory SDK. With Meshnote, the agent can search pages, read the full source, write a new page, and update an existing page with an optimistic-concurrency version token. Hosted connections use a bearer API key; OAuth is available for interactive clients.
The following probe uses version 1.30 of the official Python MCP SDK. It creates one readable page, then reads it in a separate process. That second process is the important part: it proves the knowledge survived outside the model's context and can be inspected independently.
uv init agent-memory-probe
cd agent-memory-probe
uv add "mcp==1.30.0" httpx
export MESHNOTE_API_KEY="mnk_replace_locally"
export MESHNOTE_PROJECT="your-project-slug"
import asyncio
import os
import sys
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
URL = "https://meshnote.io/mcp"
PROJECT = os.environ["MESHNOTE_PROJECT"]
TOKEN = os.environ["MESHNOTE_API_KEY"]
PATH = "wiki/agent-memory-smoke-test.md"
async def main() -> None:
async with httpx.AsyncClient(
headers={"Authorization": f"Bearer {TOKEN}"}, timeout=30
) as http_client:
async with streamable_http_client(
URL, http_client=http_client
) as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize()
if sys.argv[1] == "schema":
result = await session.call_tool("get_schema", {
"project": PROJECT,
})
elif sys.argv[1] == "write":
result = await session.call_tool("write_page", {
"project": PROJECT,
"path": PATH,
"content": """---
title: Agent memory smoke test
kind: note
---
Decision: stage artifacts before stopping production.
Source: deployment incident review, 2026-11-12.
""",
})
elif sys.argv[1] == "read":
result = await session.call_tool("read_page", {
"project": PROJECT,
"path": PATH,
})
else:
raise SystemExit("use: schema, write, or read")
if result.isError:
raise RuntimeError(result.model_dump_json())
print(result.model_dump_json(indent=2))
asyncio.run(main())
The schema mode fetches and prints the project schema; run it before either action. Read those project-specific maintenance rules and apply them to your real agent's prompts and writes. Only continue when the smoke-test path and frontmatter comply with that schema. The fixed smoke-test page below checks transport and persistence only; it is not a replacement for project rules.
Save the script as memory_probe.py. Inspect the schema in a separate step before allowing the write:
uv run memory_probe.py schema
# Review the returned rules. Continue only if this test page complies.
uv run memory_probe.py write
uv run memory_probe.py read
Create the API key in Meshnote and keep it out of source control. The write includes frontmatter because a Meshnote page requires a nonblank title. For updates, first call read_page, merge against its body, and pass the returned version to write_page as base_version. If another agent changed the page first, the server reports a conflict instead of silently overwriting it.
Put memory policy beside the tools
Giving the model a write tool is not a memory strategy. Add a short policy to the agent's system instructions:
- Search project memory before changing architecture or deployment behavior.
- Save only verified facts that will matter in a later session.
- Include scope, date, source, and what would invalidate the claim.
- Update an existing page instead of creating a near-duplicate.
- Never store secrets, raw credentials, or unreviewed personal data.
- Source code, tests, and production configuration win when they conflict with memory.
The last rule prevents memory from becoming a shadow configuration system. The wiki should explain the current decision and link to evidence; it should not pretend to replace the code that enforces it. For a complete promotion, correction, expiry, and recovery lifecycle, see persistent memory for LLM agents.
Run a four-part acceptance test
- Persistence: write a decision, terminate the process, start a new process, and read the exact page.
- Correction: read the page and its version, replace the decision with a newer sourced decision, then verify the old statement is no longer canonical.
- Isolation: use a key scoped to another project and confirm it cannot read or change this page.
- Recovery: update the page, inspect page history, restore the previous version, and confirm the restored content is readable.
A semantic-recall demo tests only whether a nearby chunk can be found. This drill tests whether the memory can remain correct under change. It is the original gap in many tutorials, which focus on stateful chat, vector retrieval, or framework wiring without testing correction and project authority.
Choose the right memory system for the job
| Option | Strong fit | Trade-off to test |
|---|---|---|
| Mem0 | Extracted user and agent facts across interactions | How extraction, correction, deletion, and tenant scope behave in your app |
| Zep / Graphiti | Changing entities, relationships, and temporal questions | Graph operations, extraction quality, and infrastructure complexity |
| Letta | Stateful agents that actively manage memory blocks and archival context | How tightly memory should be coupled to one agent runtime |
| Native ChatGPT or Claude memory | Low-setup personal continuity in one product | Cross-tool access, application control, and portability |
| Readable Markdown over MCP | Shared decisions, runbooks, research, and project truth | Requires deliberate curation; add an index for very large corpora |
Use vectors when fuzzy recall across many observations is the core problem. Use a temporal graph when relationships and point-in-time state are central. Use readable files when humans must understand, review, correct, export, and self-host the durable knowledge. A hybrid design often works best: files are canonical, while BM25, embeddings, or a graph make them easier to find. The Markdown memory guide shows how to keep the index disposable and the source recoverable.
A practical production default
Keep the current run in session state. Retrieve only relevant project pages before consequential work. Let the agent propose low-risk notes, but require stronger review for security policy, customer facts, and operating procedures. Record provenance, use concurrency tokens for updates, and test deletion and restore before calling the system production-ready.
If your custom agent needs durable project knowledge that remains legible outside its runtime, connect it to Meshnote over MCP and run the four-part gate above. Start syncing - $8/mo. Teams that need their own deployment can choose self-hosted for teams from $10/seat/month, with a five-seat minimum.
If your runtime is CrewAI, the CrewAI long-term memory guide shows how to pair its unified memory with a readable MCP authority layer.
Related Reading
Your agent's memory should be files you can read and own
Meshnote is readable, self-hosted memory for AI agents — markdown wikis your agents maintain over MCP. Hosted from $8/month.
Start syncing — $8/mo