SQLite
Covers FrontMCP 1.12.2 as of
@FrontMcp({ sqlite }) keeps the state a server holds between requests (sessions of clients before MCP 2026-07-28, background tasks, job runs and questions waiting for an answer) in a SQLite file instead of the process's memory, so it survives a restart. It needs no server of its own, only a disk that lasts. It's for one machine: a server on a laptop or a VM, a local daemon, a desktop client's server. Several machines share state through Redis instead.
@FrontMcp({ sqlite: { path?, encryption?: { secret }, walMode?, ttlCleanupIntervalMs?, busyTimeoutMs? } })
Reference
sqlite
npm install @frontmcp/storage-sqliteimport "reflect-metadata";
import { FrontMcp } from "@frontmcp/sdk";
import { HelpDesk } from "./help-desk.app";
@FrontMcp({
info: { name: "help-desk", version: "1.0.0" },
apps: [HelpDesk],
sqlite: { path: "./data/desk.sqlite" },
})
export default class Server {}@frontmcp/storage-sqlite uses better-sqlite3, a native module, by default. The stores also accept a custom driver, which avoids loading it. better-sqlite3 downloads or compiles its binary when it's installed, so install it on the platform it runs on: npm ci inside the Docker image, not on your laptop.
Options
| Option | Type | Default | What it does |
|---|---|---|---|
path | string | See where the file goes | The database file. Its folder is created if it's missing. FRONTMCP_SQLITE_PATH overrides it. |
encryption | { secret: string } | none | Encrypt every stored value with AES-256-GCM, with a key derived from secret. Keys stay readable. |
walMode | boolean | true | SQLite's write-ahead log: the file gets -wal and -shm companions. |
ttlCleanupIntervalMs | number | 60000 | How often expired entries are deleted. |
busyTimeoutMs | number | 5000 | How long a write waits for a lock another process holds before it fails (SQLite's busy_timeout, set before anything else touches the file). Since 1.9. |
With another process holding a write lock for 3 seconds, an initialize waited for it and its session was stored; with busyTimeoutMs: 1000 it gave up after a second, and the log said Failed to persist session to SQLite { …, error: 'database is locked' }. The option is also in transport.persistence.sqlite, tasks.sqlite and auth.tokenStorage.sqlite. Changed in 1.9: before, @FrontMcp({ sqlite }) dropped busyTimeoutMs, and the wait was always 5 seconds.
Where the file goes
| When | Without path |
|---|---|
Outside production, started with node or frontmcp dev | <project>/dist/sessions.sqlite |
| In production | ~/.<info.name>/sessions.sqlite, like ~/.help-desk/sessions.sqlite |
FRONTMCP_SQLITE_PATH beats both, and path too: with FRONTMCP_SQLITE_PATH=./other/override.sqlite the file was created there and ./data/desk.sqlite wasn't. The server logs the path it chose: No `sqlite.path` set — using default { path: '…' }. In a container, ~ is the home folder of the user the process runs as, inside the container: mount a volume there, or set path to one, or the file is lost with the container.
What's stored
With sqlite set, the server logs sqlite session store will be initialized for transport persistence, Created SQLite task store, and with elicitation on, Created elicitation store { type: 'sqlite' }. The session, task and job stores use these tables:
| Table | Holds |
|---|---|
kv (key, value, expires_at) | Sessions, as mcp:transport:<session id>, pending questions, under mcp:elicit:, and job runs, as mcp:jobs:run:<run id>. Each value is JSON, or iv:tag:ciphertext in base64url with encryption. |
mcp_tasks | Background tasks, one row each. |
A session expires an hour after it's written, as in Redis; transport.persistence.defaultTtlMs changes that. Clients on MCP 2026-07-28 have no sessions, but their calls can still write task state, job and workflow runs or persistent questions.
Jobs keep their runs in the top-level sqlite unless jobs.store names a backend or a top-level redis that isn't Vercel KV is set; jobs.store: false keeps them in memory. New in 1.11.0: before, jobs had no SQLite store, and only jobs.store.redis kept their runs.
sqlite isn't used by auth.tokenStorage or throttle.storage, which have their own options (Local auth, Guard options).
Caveats
- One machine. Two processes can share a file on the same disk, and one serves the other's sessions. Two that opened it at the same moment both started, in three tries; a write waits up to
busyTimeoutMswhen the other process holds the lock, and only after that fails withdatabase is locked: the session isn't stored, the log saysFailed to persist session to SQLite { …, error: 'database is locked' }(it saidRedisin 1.8.7), and the call itself is served. Changed in 1.8.7: before, the second process failed straight away withFailed to create session store - session persistence disabled { error: 'database is locked' }and kept sessions in memory. - A lost
encryption.secretloses the data, and a changed one breaks it: a client whose session was stored with the old secret gets500 Internal Server Error, and the log saysSqliteDecryptionError: SqliteKvStore: failed to decrypt a stored value. The encryption secret differs from the one the database was written with (or the value is corrupted). Restore the original secret, or delete the database file to start empty., with the codeSQLITE_DECRYPTION_FAILED. New sessions work. There's no way to re-encrypt. - The generated Cloudflare build refuses
sqliteand creates no Durable Object. A hand-written Durable Object can use its own SQLite database through the driver below. On Vercel and Lambda each instance has its own disk, so a file does not share state. - The Playground has no SQLite, so nothing here runs on this page. It was run with FrontMCP 1.9.2,
@frontmcp/storage-sqlite1.9.2 andbetter-sqlite312.11, on macOS, and the tables are whatbetter-sqlite3read back from the file: stored sessions across a restart, a second process on the same file serving a session, a write held up by another process's lock, with and withoutbusyTimeoutMs,FRONTMCP_SQLITE_PATH, a changedencryption.secret, and the default path in development. Two processes opening the file at the same moment and the production path were last run with 1.8.7, and the container steps with 1.8.4.
Custom drivers and Durable Objects
New in 1.12.1. @frontmcp/storage-sqlite opens every store's database with better-sqlite3 unless a driver is set:
| API | Type or return | Description |
|---|---|---|
useSqliteDriver(driver) | (SqliteDriver | undefined) => void | Sets the driver every database is opened with from now on, for the whole process or isolate; undefined goes back to better-sqlite3. With a driver set, no folder is created and better-sqlite3 isn't loaded. |
currentSqliteDriver() | SqliteDriver | undefined | The driver that is set. On an edge runtime the SDK opens a sqlite store only when there is one. |
durableObjectSqlite(storage) | SqliteDriver | A driver for a Cloudflare Durable Object's own SQLite database. |
SqliteDriver | (path: string) => SqliteDatabase | Opens the database a store asks for. Each call returns a database of its own. |
SqliteDatabase | interface | The part of better-sqlite3's Database the stores call: open, exec, prepare, pragma, transaction and close. |
SqliteStatement | interface | get, all and run; run returns { changes }. |
DurableObjectStorageLike | interface | The members of a Durable Object's ctx.storage the driver uses: sql.exec() and transactionSync(). The package doesn't depend on @cloudflare/workers-types. |
openDatabase(), SqliteConnection#db and the stores' getDatabase() keep their better-sqlite3 types. With a driver set they return the driver's database, which has the members of SqliteDatabase only.
In a Cloudflare Durable Object
A Durable Object with SQLite storage has a database of its own, and FrontMCP's stores run on it. Hand the SDK the package from the Worker's bundle, and set the driver in the Durable Object's constructor, before the server is created:
import { DurableObject } from "cloudflare:workers";
import { FrontMcpInstance, registerOptionalModule } from "@frontmcp/sdk";
import * as storageSqlite from "@frontmcp/storage-sqlite";
import { HelpDeskApp } from "./help-desk.app";
registerOptionalModule("@frontmcp/storage-sqlite", storageSqlite);
export class HelpDeskServer extends DurableObject {
private readonly handler: ReturnType<typeof FrontMcpInstance.createFetchHandler>;
constructor(ctx: DurableObjectState, env: unknown) {
super(ctx, env);
storageSqlite.useSqliteDriver(storageSqlite.durableObjectSqlite(ctx.storage));
this.handler = FrontMcpInstance.createFetchHandler({
info: { name: "help-desk", version: "1.0.0" },
apps: [HelpDeskApp],
events: { store: { sqlite: { path: "help-desk.sqlite" } } }, // needs MCP_EVENTS_SECRET, as on Node
});
}
async fetch(request: Request): Promise<Response> {
return (await this.handler)(request, this.ctx, this.env);
}
}export { HelpDeskServer } from "./server";
export default {
// One instance: every request goes to the object named "main".
fetch: (request: Request, env: { HELP_DESK: DurableObjectNamespace }) => env.HELP_DESK.get(env.HELP_DESK.idFromName("main")).fetch(request),
};[[durable_objects.bindings]]
name = "HELP_DESK"
class_name = "HelpDeskServer"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["HelpDeskServer"]registerOptionalModule(name, module)gives the SDK the bundled package: on Workers,require()can't reach a bundled module. Every factory that loads@frontmcp/storage-sqlitereads it: storage, token storage, sessions, tasks, elicitation and the transport's event store. It's exported by@frontmcp/sdkand by@frontmcp/utils, which also hasrequireOptionalModule(name, load): the registered module, or whatload()returns.- The constructor is early enough for the driver:
createFetchHandler()builds the server on its first request. Each instance of the Durable Object opens its own connection. Changed in 1.12.1: before, a connection was reused while it was open, whoever opened it, so the next instance in the same isolate got the one an ended instance had opened, and every request answered503SERVER_START_FAILEDuntil the isolate went away. - One instance per isolate. The driver is set for the whole isolate, so use it in a class with one instance, one id like
idFromName("main"). Instances with other ids can share the isolate: the storage set last then opens every instance's stores, Cloudflare refuses the I/O (Cannot perform I/O on behalf of a different Durable Object), and the other instances' servers don't start. - Every
pathis the same database, the object's own: the option only names it, and no file or folder is created. - What a Durable Object refuses is answered by the driver. Writes run in
ctx.storage.transactionSync(), sinceBEGINis refused, andwalModeandbusyTimeoutMsdo nothing: there is one connection, and both pragmas are refused. The key search sends noLIKEpattern, which a Durable Object refuses over 50 bytes. - Tasks, elicitation and persistent questions open a
sqlitestore on an edge runtime when a driver is set: see Where tasks can't run and elicitation's stores. Persistent questions needpersistent.storage: { type: "sqlite", … }; ones that would use the top-levelsqliteare refused there. frontmcp build --target cloudflarewrites a Worker without a Durable Object, and still refusessqlite: write the Worker yourself, as above.
Key search
keys(pattern) of SqliteKvStore and SqliteStorageAdapter use the pattern's fixed text to narrow the search to a range on the primary key when possible, and match the rest of the pattern themselves. Otherwise they scan all unexpired keys:
- Letter case matters.
keys("session:*")returnssession:abut notSession:1, as the memory and Redis storages do. Changed in 1.12.1: before, SQLite'sLIKEignored ASCII case. An application that relied on that searches for each spelling. - Key order isn't guaranteed. Sort the returned array when order matters.
- An adapter's pattern uses glob escapes.
*matches any sequence and?one character; a backslash makes the next character literal. A trailing lone backslash matches a backslash.escapeGlob()from@frontmcp/utilsescapes a key's literal text:user:${escapeGlob("a*b")}:*findsuser:a*b:1in SQLite, memory and Redis. Changed in 1.12.2: before, SQLite matched a backslash as itself. A pattern containinga\bnow findsab; writea\\bto find a key containing a backslash, or useescapeGlob().
With SqliteEventStore({ encryption: { secret } }), the transport's stored messages are encrypted at rest, with AES-256-GCM. A message that doesn't decrypt, one stored before the secret was set or under another secret, is left out of a replay.
createGlobMatcher(pattern: string) from @frontmcp/utils returns (key: string) => boolean for repeated key checks. It uses the same *, ? and backslash escapes as matchesPattern(key, pattern) without a backtracking regular expression.
The following Node script checks a literal * in a key on both backends. It also checks a namespace whose name contains *: namespace(name, id?) prefixes keys with the literal namespace text, and keys(pattern = "*") and count(pattern = "*") apply glob syntax only to the pattern you pass. Changed in 1.12.2: before, *, ? or a backslash in the namespace prefix was read as glob syntax too, so a namespace could list or count another namespace's keys.
import { strict as assert } from "node:assert";
import { createStorage, escapeGlob } from "@frontmcp/utils";
for (const type of ["memory", "sqlite"] as const) {
const storage = await createStorage({ type, sqlite: { path: ":memory:" }, fallback: "error" });
try {
await storage.set("user:a*b:1", "ticket");
await storage.set("user:a\\xb:1", "other");
assert.deepEqual(await storage.keys(`user:${escapeGlob("a*b")}:*`), ["user:a*b:1"]);
const tickets = storage.namespace("a*b");
await tickets.set("T-1", "open");
await storage.namespace("axxb").set("T-2", "closed");
assert.deepEqual(await tickets.keys("*"), ["T-1"]);
assert.equal(await tickets.count(), 1);
console.log(`${type}: literal key and namespace matched`);
} finally {
await storage.disconnect();
}
}Storage for application data
createStorage({ type: "sqlite", sqlite: { path } }) from @frontmcp/utils returns a SQLite-backed RootStorage. For dependency injection, register sqliteStorageProvider({ path, prefix?, provide? }) from @frontmcp/sdk and read it with this.get(SqliteStorageToken) (or your provide token). The GLOBAL provider connects at startup and disconnects at shutdown; a manifest build opens no file.
sqliteStorageProvider() accepts these options:
| Option | Type | Default | Description |
|---|---|---|---|
path | string | required | Database file; its directory is created when missing. |
prefix | string | none | Prefix for every storage key. |
provide | Token<RootStorage> | SqliteStorageToken | Injection token, for registering more than one store. |
walMode | boolean | true | Use write-ahead logging on a local file system. |
busyTimeoutMs | number | 5000 | Lock-wait limit in milliseconds. |
ttlCleanupIntervalMs | number | 60000 | Expiry sweep interval; 0 disables it. |
encryption | { secret: string } | none | Encrypt values at rest. |
Stores on the same file share one connection within a process when opened by the same driver. Changed in 1.12.1: before, different drivers could share a connection. A different driver now opens its own connection; a new Durable Object instance no longer inherits a previous instance's handle. Atomic ifNotExists, increments, compare-and-delete, compare-and-expire and setIfEquals work across processes. Waiting for a lock uses an asynchronous queue, so timers keep running. disconnect() drains queued work before releasing the connection; it closes when the last store releases it. Do not close getDatabase() directly: other stores share that handle.
expire() on an expired key returns false. TTLs for expire() and expireIfEquals() must be positive whole seconds (StorageTTLError otherwise). Incrementing a non-integer throws StorageOperationError.
import { sqliteStorageProvider, SqliteStorageToken } from "@frontmcp/sdk";
export const providers = [sqliteStorageProvider({ path: "./data/desk.sqlite", prefix: "desk:" })];
// In a tool: const storage = this.get(SqliteStorageToken);Following changes across processes
createChangeFeed(storage, options?) from @frontmcp/utils provides publish(topic), subscribe(topic, listener) (returns an unsubscribe function), and async close() without disconnecting storage. Its options are:
| Option | Type | Default | Description |
|---|---|---|---|
pollIntervalMs | number | 250 | Milliseconds between SQLite checks for another process's write. |
coalesceMs | number | 50 | Milliseconds in which changes produce one announcement. |
onError | (error: unknown) => void | none | Receives failed polls or subscriptions and listener errors. |
Its kind is "pubsub" for a backend with pub/sub, "poll" for SQLite, or "local" otherwise. SQLite polls dataVersion() and reads topic counters only after another process writes the file; Redis notifies followed topics after reconnect so readers reload missed changes. Listeners read the current value; the feed carries no data payload. This is what materialized resources use.
Usage
Keeping sessions across restarts
With the configuration at the top of the page, start the server with MCP_SESSION_SECRET set, and let a client on MCP 2025-06-18 initialize. Its session is a row in the file:
node -e "const D = require('better-sqlite3'); console.log(new D('./data/desk.sqlite', { readonly: true }).prepare('select key, expires_at from kv').all())"[ { key: 'mcp:transport:<session id>', expires_at: 1790000000000 } ]
Stop the server and start it again with the same secret: the client's next tools/call with the same Mcp-Session-Id succeeds, and the server logs Recreating transport from stored session. Without sqlite, it would get 404 session not initialized. Without the secret, outside production, the restarted server can't read the old id and answers 404 invalid session id, sqlite or not: see Redis.
Encrypting what's stored
Read the secret from the environment, and keep it where you keep the server's other secrets:
@FrontMcp({
info: { name: "help-desk", version: "1.0.0" },
apps: [HelpDesk],
sqlite: {
path: "./data/desk.sqlite",
encryption: process.env.DESK_DB_SECRET ? { secret: process.env.DESK_DB_SECRET } : undefined,
},
})
export default class Server {}The row's value is then <iv>:<tag>:<ciphertext>, three base64url parts, instead of JSON. The keys, and so the session ids, stay readable: they're how rows are found.
Keeping the file in a container
Put it on a volume, at a path you choose:
sqlite: { path: "/data/desk.sqlite" },
A new Docker volume takes the owner of the folder it's mounted on, and a folder that isn't in the image belongs to root, so a server that runs as node can't write there. Create it in the image, in the Dockerfile, before USER node:
RUN mkdir -p /data && chown node:node /data
USER nodedocker run --init -v desk-data:/data -e MCP_SESSION_SECRET="$(openssl rand -hex 32)" help-deskA session then survives docker restart. The image needs better-sqlite3 built for its own platform: install dependencies in the image, as that Dockerfile does, rather than copying node_modules from another machine.
Troubleshooting
Error: Cannot find module 'better-sqlite3'
The server has sqlite set, and the package isn't installed. It logs Failed to create session store - session persistence disabled and then exits. npm install @frontmcp/storage-sqlite, which installs better-sqlite3 too.
failed to open database at "/data/desk.sqlite": unable to open database file
The process can't create or write the file, most often a container user without write access to a mounted volume. The server exits, with SqliteTaskStore: failed to open database at …. Give the user the folder, as in keeping the file in a container.
Failed to persist session to SQLite { error: 'database is locked' }
Another process held a write lock on the file for longer than a write waits, busyTimeoutMs, 5 seconds by default. The session isn't stored, though the request is served. Find the process that holds the file, raise busyTimeoutMs, give each process its own path, or move to Redis for several. In 1.8.7 the line said Failed to persist session to Redis, though the store was SQLite. (Before 1.8.7 the second process failed to open the file at all, with Failed to create session store - session persistence disabled { error: 'database is locked' }.)
500 Internal Server Error, and SqliteDecryptionError in the log
The stored value was encrypted with another encryption.secret. Put the old secret back, or delete the file and let clients start new sessions. (Before 1.8.7 the log said Unsupported state or unable to authenticate data.)
[--target cloudflare] config incompatible with Cloudflare Workers: … sqlite storage is not supported
Workers have no file system for SQLite. Remove sqlite from the Worker's configuration. See Cloudflare Workers.
The file is somewhere unexpected
Without path, the file is in dist/ in development and in ~/.<info.name>/ in production, unless FRONTMCP_SQLITE_PATH is set. The startup log says which. Set path to be sure.