공개 미리보기에 새로 추가된 기능 – PostgreSQL 지원 그리고 TiDB Cloud 파일 시스템
Blog - Feature (2)

핵심 요약

  • The 2026-07-28 MCP spec removed protocol sessions, so cross-call state now lives in your backend behind explicit handles.
  • Transport continuity and durable application state are separate problems, and each needs its own answer in your design.
  • In-memory stores fail the first time a deploy restarts a pod or a load balancer picks another instance.
  • SQLite fits local single-process servers; shared state across replicas needs a transactional database with retention rules.
  • A state handle names a resource and proves nothing about the caller, so authorize every request that presents one.

MCP server persistence is the practice of storing session continuity, tool outputs, event history, and agent state outside process memory, so an MCP server keeps working through reconnects, restarts, and scale events. Without it, one routine redeploy wipes the handles clients are holding, the results of tools that have already run, and the context an agent needs to finish its task.

The stakes went up in 2026. The 2026-07-28 MCP specification removed protocol-level sessions, the Mcp-Session-Id header, and SSE stream resumability. Your application is still stateful, so anything that must survive between tool calls now lives in a backend you choose. That puts the database decision at the start of MCP server design. This guide covers what to store, which backend fits which deployment, and how to design the schema.

What Does MCP Server Persistence Actually Mean?

The term covers two different problems, and search results split between them. Teams that merge the two tend to solve one and assume they solved both.

Connection persistence is about keeping a client attached to the right session. Under revisions 2025-03-26 through 2025-11-25, a Streamable HTTP server could optionally issue an Mcp-Session-Id during initialization, and load balancers often pinned that ID to one instance. Example: a client reconnects after a network drop and expects the server to recognize it.

Data persistence is about keeping the work. Tool outputs, memory records, task progress, and audit metadata need to exist after the process that created them is gone. Example: an agent ran a 20-minute data export yesterday and today needs the file location and row count without running the export again.

Connection Persistence Is Not the Same as Data Persistence

A session ID identifies the client-server session established during initialization. The ID itself holds no data. If the server keeps that session’s data in a dictionary keyed by the ID, the data dies with the process while the client still holds an ID that looks valid. The 2026-07-28 revision makes the split explicit. The protocol carries no session, and servers that need cross-call state mint a handle, return it from a tool, and accept it as an ordinary argument on later calls.

MCP Servers Need Both Session Continuity and Durable State

Continuity still matters after the spec change. It moved from the transport into the application. A handle such as workspace_id or task_id works only if every instance behind your load balancer can resolve it to the same record. Many teams also keep accepting older protocol versions for a while, so they carry session IDs for some clients and handles for others. Both paths lead to the same requirement: a shared, durable store that any instance can read.

Why In-Memory MCP Server State Fails in Production

Quickstart code keeps state in memory because it keeps the example short. That holds up on a laptop and breaks in production.

Restarts Erase Local Event History

Streamable HTTP servers on revisions 2025-03-26 through 2025-11-25 could attach event IDs to SSE messages. When a client reconnected with Last-Event-ID, the server could optionally replay what it missed on that stream. Replay only worked if the event history still existed. An in-memory event store is empty after a restart, so the client resumes into a gap: progress notifications are gone and long-running calls look hung.

The current revision removed stream resumability. When a response stream breaks, the client must re-issue the request with a new request ID. If the server already finished half the work, it needs a durable record of that work, or the retry runs the tool a second time. For a tool that sends email or writes to a ledger, that is a duplicate side effect.

Multi-Worker Routing Breaks Single-Process Session Memory

Put two replicas behind a round-robin load balancer and in-memory state becomes a coin flip. Under the older session model, teams patched this with sticky routing keyed on the session ID. That ties each client to the instance it hit first, and the session disappears when a deploy replaces that instance. The stateless revision lets any instance serve any request, which only holds if the handle-keyed state lives somewhere every instance can reach.

Serverless Deployments Make State Leakage Obvious

Serverless functions and containers with ephemeral filesystems remove any illusion that the local state is durable. A function instance can disappear between two tool calls, and a SQLite file written to /tmp disappears with it. On these platforms, an external store is the only place cross-call state can live.

What an MCP Server Should Store in a Database

Not every byte an MCP server touches needs durability. The useful split is between records the system must not lose and records that can expire on a schedule.

Transactional durability belongs to anything that changes what happens next: handle ownership, task status, invocation records, and long-term memory. TTL policies fit data whose value drops quickly, such as replay buffers and raw payloads the server has already summarized.

Data typeWhy it must persistTypical retentionFailure if lost
Session IDs and state handlesAny instance must resolve a handle to its owner and stateHours to days, expiring on inactivityClients hit “not found” mid-workflow and start over
Tool invocation logMakes retries idempotent and records what ran30 to 90 days, then archiveRetried calls repeat writes, charges, or messages
Tool outputs and intermediate resultsLater steps and later sessions read themDays to weeks, or until summarizedExpensive tools rerun and the agent loses evidence for past decisions
Task progress and event historyShows clients and operators where long tasks standMinutes to hoursLong-running calls look stuck after a disconnect
Context and memory recordsAgent behavior depends on prior facts and preferencesLong-lived, with explicit deletionThe agent forgets users and repeats work
Audit metadataRecords who called which tool, with what input, under which identitySet by compliance policyNo way to reconstruct or explain an agent action

Retention values are illustrative starting points. Set your own based on workload and policy.

Session State and Session IDs

Store the handle or session ID with the authenticated principal it belongs to, the tenant ID, creation time, last-activity time, and status. The principal binding matters most. It lets the server reject a valid handle presented by the wrong user.

Tool Outputs and Intermediate Results

Store the summary and the raw payload separately. Large payloads can go to object storage with a pointer row in the database. Keep a request key or input hash on each invocation, so a retry returns the stored result instead of calling the downstream system again.

Event Streams and Replay History

Servers that offer stream replay to clients on revisions 2025-03-26 through 2025-11-25 need an event store with per-stream ordering and a short retention window. Under the current spec, the equivalent is task progress: when both client and server support the optional Tasks extension, the client polls a task handle with tasks/get, which only works when task state lives outside the request that created it. For the broader architecture argument, see why agent state belongs outside the harness.

How MCP Server Persistence Works Across Sessions

In plain terms, the lifecycle runs like this. A client sends a request. The server authenticates it, runs a tool, writes the result and any new state to the database, and returns a handle for anything the model will need again.

The client disconnects, or a deploy replaces the instance that served it. Later, the same client, or another agent acting for the same user, sends a request carrying that handle. A different instance loads the record, checks that the caller may use it, and continues.

Durable Stores Make Replay Possible

Replay means returning what a client missed without redoing the work. With a durable store, the server can answer a retried request from its invocation log, report a task’s current status from the task table, or resend events after the last ID an older client saw. Without one, the only recovery path is to run everything again.

Recovery Depends on What the Server Saved

A server can only recover what it wrote down. If it stored the final tool result but not the steps, a crash mid-task means starting the task over. If it stored step-level checkpoints, it resumes at the last completed step. Choose checkpoint granularity per tool, based on how expensive each step is and whether it has side effects.

Stateful Tools Need More Than Reconnect Logic

Reconnect logic restores a channel. It does not restore a browser session, a coding workspace, or a half-built report. Tools that hold state need that state modeled as rows: what exists, who owns it, and which step it reached. The same records support handoff packs, where one agent finishes and passes a structured summary plus pointers to another agent or a later session.

SQLite, Redis, and SQL Backends Solve Different MCP Problems

SQLite fits one local process, Redis fits short-lived shared state, and a relational database is the durable system of record for production. The deciding questions are how many instances need the same data and how long it must last.

BackendDeployment fitDurabilitySharing across replicasWhere it breaks
SQLiteLocal development, desktop or stdio servers, one processDurable on local diskNone; the file lives on one machine and allows one writer at a timeMultiple replicas, serverless, ephemeral disks
RedisShared short-lived state such as counters, locks, and buffersDepends on snapshot and append-only file settingsShared by all instancesLong-lived records, relational queries, audit history
Relational SQL databaseProduction servers with many replicas or tenantsTransactionalShared, with ACID transactionsSingle-primary systems eventually need a bigger node or manual sharding

SQLite Is a Starting Point, Not the Finish Line

SQLite is a good choice for a stdio server on a developer’s machine. It needs no network, ships with most languages, and survives restarts. It stops working as shared persistence when a second instance needs the same data, because the file sits on one disk. Serverless platforms rarely give you a disk that lasts between invocations. For more on when local storage is no longer enough, see our article on when AI agent memory outgrows SQLite.

Redis Helps With Shared Ephemeral State

Redis gives every instance a fast shared view of short-lived data like rate-limit counters, locks, and recent-event buffers. It is a weaker fit as the system of record for memory or audit data. Durability depends on configuration, and a question like “which tools did this tenant call last week” needs queries Redis does not handle well.

A Relational Database Is the Durable System of Record

Once the state has to survive restarts, serve every replica, and answer audit questions, you need transactions, indexes, and SQL. PostgreSQL and MySQL cover many single-region workloads. The next question is what happens when tenant count, write volume, or table size outgrows one primary node.

What Good MCP Server Database Design Looks Like

A practical schema has a small number of tables, each with one job. Every table carries a tenant_id, every query filters on it, and each table has its own retention rule.

TableKey columnsIndexing and retention
handleshandle_id, tenant_id, principal_id, kind, status, created_at, last_used_atPrimary key on handle_id; TTL on last_used_at
tool_invocationsinvocation_id, tenant_id, handle_id, tool_name, request_key, input_hash, status, started_atAUTO_RANDOM primary key on invocation_id; unique index on (tenant_id, request_key) for idempotent retries
tool_outputsinvocation_id, tenant_id, summary, created_atSame retention as the invocation log
tool_payloadsinvocation_id, tenant_id, payload_ref, size_bytes, created_atTTL on created_at; bucket lifecycle rule for the files, set slightly longer than the TTL so no row points to a deleted file
task_progresstask_id, tenant_id, step, state, updated_at, completed_atIndex on (tenant_id, task_id); TTL on completed_at, which stays NULL until the task finishes
memorymemory_id, tenant_id, principal_id, content, embedding, source_invocation_idVector index for recall; delete only on explicit request
audit_logevent_id, tenant_id, principal_id, tool_name, input_hash, outcome, created_atAUTO_RANDOM primary key on event_id; append-only; retention set by compliance policy

These choices get harder to retrofit as usage grows. Without a tenant key, a deletion request becomes a forensic exercise. Without an index on the invocation log, every idempotency check becomes a table scan.

Checklist: Signs Your MCP Server Persistence Model Is Too Fragile

  • State lives in a process-level dictionary, map, or in-memory store.
  • Running two replicas requires sticky routing.
  • A redeploy forces users to restart tasks.
  • Retried tool calls can repeat side effects because nothing records the first attempt.
  • Handles or session IDs are not tied to an authenticated user.
  • No single query answers “who called this tool, with what input, and when.”
  • Event buffers and raw payloads never expire.
  • Memory and tool logs sit in different systems with no shared tenant key.

Security and Compliance Concerns in MCP Persistence

Persistence turns every stored handle and record into something an attacker can target, so security belongs in the schema design. The core rules: bind IDs to users, verify every request, record every tool call, and keep secrets out of storage.

Persistent Sessions Create Persistent Risk

The longer a handle stays valid, the longer a stolen one is useful. MCP’s security guidance names session hijacking as a threat, and the 2026-07-28 version describes the same attack against state handles: someone obtains or guesses an ID and uses it on another user’s state. The defenses are consistent across revisions. Generate IDs from a secure random source, bind them to the authenticated user, expire them, and verify authorization on every request. Holding an ID never counts as authentication.

Decide early what the server should never store. Raw OAuth tokens, credentials passed in tool arguments, and full payloads from sensitive systems rarely belong in a tool output table. Store a reference or a redacted summary instead.

Audit Trails and Scoped Access Are Part of the Design

An audit table that records principal, tool, input hash, outcome, and timestamp answers most incident questions with one query. Scope database credentials so the MCP server’s runtime role writes to its own tables and reads only what its tools need. Plan deletion as a query you can run and verify: with a tenant or user key on every table, an erasure request becomes a set of DELETE statements across known tables.

Where TiDB Fits in MCP Server Persistence

The category requirement is a durable, shared, transactional store that handles small, frequent writes, supports retention policies, and grows with tenant count. TiDB is a distributed SQL database built for that workload shape. Four properties matter most for MCP servers:

  • MySQL compatibility. MCP servers written in Python, TypeScript, or Go connect with standard MySQL drivers and ORMs, so the persistence layer needs no custom client code.
  • Strong consistency. Insert the invocation record first and let the unique index on (tenant_id, request_key) reject duplicates, since a SELECT before INSERT lets two concurrent retries both pass. ACID transactions keep the related database writes together, even across nodes; side effects in external systems still need their own retry protection. Keep each transaction to one step: TiDB Cloud Starter caps transactions at 30 minutes, so never hold one open across a long-running tool call.
  • Horizontal scaling. TiDB splits data into key ranges across TiKV nodes automatically, so the application never implements sharding logic.
  • Built-in retention. A table-level TTL attribute removes expired rows in the background, which covers handles, completed progress records, and rows in a separate tool_payloads table. Files in object storage need their own bucket lifecycle rule, set slightly longer than the TTL so no row points to a deleted file. On TiDB Cloud Starter, TTL jobs run every 15 minutes, so check expiry in queries when it has to be exact.

Vector search (public preview on TiDB Cloud Starter) runs in the same database, so memory recall and tenant filters live in one SQL statement. For per-tenant recall, filter by tenant and recency first, then rank by distance. That skips the vector index but returns the true nearest matches within each tenant’s data. Ranking in a subquery first keeps the index in use and suits filters that match a large share of rows. If you are comparing databases for this workload, see our guide to the best database for AI agents.

TiDB Can Back Sessions, Events, and Tool State in One System

Here is an illustrative architecture. An MCP server gives coding agents a persistent workspace and runs as stateless containers behind a load balancer. A create_workspace tool inserts a row into handles and returns the workspace_id. Each tool call writes to tool_invocations in the same transaction that updates task_progress.

Memory records with embeddings sit in a memory table with a vector index, and short-lived tables use TTL. Every container reads and writes the same cluster, so any container can serve the next request.

Why Distributed SQL Matters When MCP Moves Past Local Prototypes

Tool logs grow with every call from every agent, and stateless MCP servers scale out easily, which multiplies concurrent writers. With a single primary, the options are a larger instance or application-level sharding by tenant. TiDB spreads data and write load across nodes without changes to application queries, so the persistence layer scales on the same axis as the stateless servers in front of it. One schema choice still matters: AUTO_INCREMENT or time-ordered keys concentrate writes in high-write tables like tool_invocations and audit_log, so use AUTO_RANDOM or randomized keys there.

For prototypes, TiDB Cloud Zero (public preview) provisions a temporary MySQL-compatible instance with one API call. It lasts 30 days unless claimed into a persistent TiDB Cloud Starter instance. For production, teams can run TiDB Cloud Starter for MCP servers with usage-based scaling, or TiDB Cloud Dedicated for isolated infrastructure. Feature support varies by plan: vector search and full-text search are in public preview on Starter and not yet available on Dedicated, so check the features page before choosing.

For a working example of TiDB behind MCP, see how to set up the TiDB MCP Server in Claude Desktop. That walkthrough predates the 2026-07-28 spec, so treat it as a database integration example rather than a transport reference.

To test the pattern, point your server’s state tables at a TiDB Cloud Zero instance and run your retry and failover cases. SDKs, templates, and sample code are in the TiDB Developer Hub.

How TiDB Supports Production MCP Servers Without More Sprawl

A common path to production adds one system per problem: Redis for sessions, a vector store for memory, a relational database for task state, and a log pipeline for audit. Each extra system adds a consistency boundary, a separate retention policy, and one more place a deletion request has to reach.

For most MCP servers, the persistence surfaces in this guide fit in one transactional SQL database with a tenant key on every table. Keep Redis where sub-millisecond counters matter, and put the system of record in one place. PingCAP built TiDB for that role as tenant count and write volume grow, from a 30-day prototype instance to dedicated clusters, with the same MySQL-compatible drivers throughout, though feature support varies by plan.

The takeaway: once an MCP server runs on more than one instance, its state belongs in one shared, transactional database. When you are ready to plan for production, explore TiDB as a distributed SQL database for AI agents.

MCP Server Persistence FAQs

What should persist in an MCP server?

  • State handles or session IDs, bound to the user who owns them.
  • Tool invocation records and outputs that retries or later steps depend on.
  • Task progress for long-running tools.
  • Agent memory and audit metadata, each with explicit retention and deletion rules.

Can SQLite handle MCP server persistence?

  • Yes, for local development and single-process stdio servers.
  • It survives restarts as long as the disk does.
  • It cannot share state across replicas or serverless instances.
  • Move to a networked transactional database before running a second instance.

Do MCP servers need a database?

  • Not for a tool that keeps nothing between calls.
  • Yes, once state must survive restarts or reach every replica.
  • Yes, once you need to query tool results, memory, or audit records later.

How do MCP sessions survive reconnects?

  • Under the 2026-07-28 spec, state survives as server-minted handles stored in a shared database.
  • Clients re-issue broken requests, so servers check invocation records to avoid duplicate work.
  • Revisions 2025-03-26 through 2025-11-25 allowed servers to assign a session ID and optionally replay missed events when a client reconnected with Last-Event-ID.
  • In every version, recovery after a restart, or on a different instance, works only if the state lives outside process memory.

What is the best database for MCP server persistence?

  • SQLite for local, single-process servers.
  • Redis for short-lived shared counters and buffers, not as the system of record.
  • A transactional SQL database for production state, memory, and audit data.
  • Distributed SQL such as TiDB once tenant count or write volume outgrows a single primary node.

Book a Demo


Experience modern data infrastructure firsthand.

무료로 시작하세요

Have questions? Let us know how we can help.

문의하기

TiDB Cloud 전용

예측 가능한 워크로드를 위한 완전 관리형 클라우드 DBaaS

TiDB Cloud 스타터

워크로드 자동 확장을 위한 완전 관리형 클라우드 DBaaS