Skip to content
← Notebook

Agent Architecture & MCP

Stateless MCP and the Tasks Extension: Scaling AI Agents in Production without Sticky Sessions

How the new Model Context Protocol specification removes server-bound sessions, fixes the load balancer bottleneck and lets heavy tools run as durable tasks.

Date
Oct 8, 2026
Reading time
8 min
Result
0 Sticky Sessions • Transparent Header-Based Routing • Zero Dropped Connections • $0 Local Cost

Translated from the Spanish original. The code, data and READMEs on GitHub are in Spanish.

In the last months of 2026, the Model Context Protocol (MCP) has established itself as the de facto standard for connecting language models to external tools and data sources. With more than 240 million monthly downloads of its SDKs and tens of thousands of servers built by the community and big tech, the protocol has proved its conceptual power.

However, as soon as an engineering team tries to move an MCP prototype into distributed production, it usually crashes into an invisible wall: the stateful connection trap (Stateful Transport).

The protocol’s original design relied on a mandatory initialisation exchange (initialize), fixed session identifiers (Mcp-Session-Id) and persistent open connections via HTTP+SSE. In a real environment with Kubernetes, Docker containers and standard load balancers, this design wreaked havoc:

  1. Consecutive requests sent through a round-robin load balancer ended up on different pods, throwing immediate Session Not Found errors.
  2. Forcing session affinity (sticky sessions) concentrated traffic on specific nodes, breaking autoscaling and saturating the infrastructure.
  3. Slow tools (scrapers, report generation, ETL processing or code compilation) kept HTTP sockets open for minutes, causing cascading timeouts and file descriptor leaks.

The protocol’s architectural revision (a specification finalised under the stewardship of the Linux Foundation’s Agentic AI Foundation) tackles all three problems at the root. In this article from the trenches at YesWeLab (@Yeswelab_OU) we look at how the new Stateless MCP architecture works, how to implement the Tasks extension for long-running asynchronous operations and how to structure our Dual Track strategy to run agents at scale.


1. From the Sticky Session Trap to the Self-Contained Request

In early versions of MCP, communication between the agent’s client and the remote server simulated a fixed terminal session:

[ LEGACY ARCHITECTURE: SESSION-DEPENDENT ]
Agent client ──────► Load balancer (round-robin)
                            │
               ┌────────────┴────────────┐
               ▼ (Req 1: initialize)     ▼ (Req 2: tools/call)
          [ MCP Pod A ]             [ MCP Pod B ]
      (Registers session_id: 123)  (ERROR: session 123 doesn't exist)

To work around this, teams configured sticky sessions (affinity by cookie or client IP). That created a serious bottleneck: if an intensive agent ran hundreds of tool calls, a single pod absorbed the whole load while the other servers sat idle. It also made it impossible to deploy MCP servers on serverless platforms (AWS Lambda, Cloudflare Workers) or at the edge.

The Solution: A Fully Stateless Wire Protocol

The new specification removes the prior initialize handshake and the Mcp-Session-Id identifiers entirely. Every incoming HTTP request is 100% self-contained.

[ STATELESS ARCHITECTURE: ANY POD CAN ANSWER ]
Agent client ──────► Load balancer (Nginx / Traefik / Envoy)
                            │ (pure round-robin)
               ┌────────────┼────────────┐
               ▼            ▼            ▼
          [ MCP Pod 1 ] [ MCP Pod 2 ] [ MCP Pod 3 ]
        (Handles req) (Handles req) (Handles req)

To make this viable without losing efficiency, the protocol introduces two key transport-level mechanisms:

  1. Standard HTTP headers for inspection and routing:
    • Mcp-Method: Specifies the JSON-RPC method (for example, tools/call or tools/list).
    • Mcp-Name: Specifies the specific tool or resource (for example, ejecutar_consulta_sql). This lets API gateways, reverse proxies and load balancers apply rate limiting, per-user quotas or path-based routing without having to deserialise the request’s JSON body.
  2. Deterministic tool catalogue caching: tools/list calls carry time-to-live (TTL) headers and cache scopes. Clients don’t need to fetch the catalogue on every reconnection, which reduces start-up latency and preserves the cached blocks in the LLM prompt (prompt cache).

2. The Tasks Extension: Decoupling Long-Running Tools

One of the biggest headaches when building autonomous agents happens when a tool takes more than a couple of seconds to respond:

  • An agent asks to clone a repository and analyse 2,000 files.
  • An n8n pipeline launches a heavy OCR document ingestion.
  • A video generator or 3D renderer processes a complex clip.

Keeping the HTTP connection open while the server works is extremely fragile: intermediate proxies cut idle connections after 60 seconds, network restarts cause state loss and server workers block waiting on I/O operations.

The Asynchronous Tasks Pattern

The official Tasks extension turns long-running tools into non-blocking asynchronous operations:

[ ASYNCHRONOUS FLOW WITH THE TASKS EXTENSION ]

Agent client                         MCP server (stateless)
      │                                         │
      ├─── tools/call (scraping_complejo) ─────►│
      │                                         │ [Starts a background job]
      │◄── 202 Accepted (task_handle: t_948a) ──┤
      │                                         │
      │    [The agent doesn't hold the socket]  │
      │                                         │
      ├─── tasks/get (task_handle: t_948a) ────►│
      │◄── Status: "running", progress: 65% ────┤
      │                                         │
      ├─── tasks/get (task_handle: t_948a) ────►│
      │◄── Status: "completed", data: [...] ────┤

The task’s state doesn’t live in the HTTP connection or in the execution thread’s memory: it lives in a shared persistent store behind a durable identifier (task_handle). Any replica of the MCP server can answer the tasks/get status check.


3. Implementation from the Trenches: A FastMCP Server with Async Tasks and SQLite WAL

Below is a real implementation pattern in Python using decoupled FastMCP, where heavy tasks are persisted in a local SQLite database in WAL (Write-Ahead Logging) mode, ensuring zero collisions and full compatibility with round-robin load balancers.

import sqlite3
import uuid
import threading
import time
from typing import Dict, Any
from mcp.server.fastmcp import FastMCP

# Stateless MCP server instance
mcp = FastMCP("lab-data-tasks-service")

DB_PATH = "/tmp/mcp_tasks.db"

def init_db():
    conn = sqlite3.connect(DB_PATH)
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("""
    CREATE TABLE IF NOT EXISTS tasks (
        id TEXT PRIMARY KEY,
        tool_name TEXT,
        status TEXT, -- 'queued', 'running', 'completed', 'failed'
        progress INTEGER,
        result TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    """)
    conn.commit()
    conn.close()

init_db()

def worker_ejecucion_pesada(task_id: str, query: str):
    """Simulates an intensive background task."""
    conn = sqlite3.connect(DB_PATH)
    conn.execute("UPDATE tasks SET status='running', progress=20 WHERE id=?", (task_id,))
    conn.commit()
    
    # Real processing (e.g. extraction, indexing, scraping)
    time.sleep(3)
    
    resultado = f"Dataset processed successfully for: {query}"
    conn.execute("""
        UPDATE tasks 
        SET status='completed', progress=100, result=? 
        WHERE id=?
    """, (resultado, task_id))
    conn.commit()
    conn.close()

@mcp.tool(name="iniciar_analisis_dataset")
def iniciar_analisis_dataset(query: str) -> Dict[str, Any]:
    """Starts a heavy task and returns a task_handle immediately."""
    task_id = f"task_{uuid.uuid4().hex[:10]}"
    
    conn = sqlite3.connect(DB_PATH)
    conn.execute("""
        INSERT INTO tasks (id, tool_name, status, progress) 
        VALUES (?, 'iniciar_analisis_dataset', 'queued', 0)
    """, (task_id,))
    conn.commit()
    conn.close()
    
    # Fire off decoupled execution
    threading.Thread(target=worker_ejecucion_pesada, args=(task_id, query), daemon=True).start()
    
    return {
        "status": "accepted",
        "task_handle": task_id,
        "poll_endpoint": f"tasks/get?id={task_id}",
        "message": "Operation started. Check its status with the task_handle."
    }

@mcp.tool(name="consultar_estado_tarea")
def consultar_estado_tarea(task_handle: str) -> Dict[str, Any]:
    """Checks the progress or result of a durable task."""
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    cur.execute("SELECT status, progress, result FROM tasks WHERE id=?", (task_handle,))
    row = cur.fetchone()
    conn.close()
    
    if not row:
        return {"error": "Task not found"}
        
    return {
        "task_handle": task_handle,
        "status": row[0],
        "progress_percent": row[1],
        "result": row[2] if row[0] == "completed" else None
    }

4. The Dual Track Philosophy at YesWeLab

At YesWeLab we apply the “Show, Don’t Sell” principle: we test real architectures in battle before recommending them to the community. With this new standard, we lay out two paths depending on the project’s needs:

Track A: DIY / Open Source / Self-Hosted ($0 Cost)

  • Stack: FastMCP servers (Python or Node.js) packaged in Docker Compose + a Traefik or Nginx reverse proxy with round-robin balancing.
  • Task Persistence: SQLite in WAL mode mounted on a persistent volume, or local Redis (valkey).
  • Advantages: Zero dependence on external providers, full privacy for tool data, no recurring per-connection costs or API gateway licences.

Track B: Fast-Track SaaS / Cloud Enterprise

  • Stack: MCP endpoints deployed on Cloudflare Workers or AWS API Gateway + Serverless Redis (Upstash) + federated OIDC authentication (Okta / Microsoft Entra ID).
  • Scalability: Zero server maintenance, tolerance for massive spikes in multi-agent calls and security compliance with the Enterprise-Managed Authorization extension.
  • Advantages: Global deployment in minutes, guaranteed high availability and centralised access control over enterprise tools.

5. A Checklist from the Trenches for Agent Architects

Before deploying an MCP server in production under high demand, check these key points:

  1. [ ] Zero transport-level state: Make sure your servers don’t keep session variables in local memory that depend on the client’s previous requests.
  2. [ ] Remove session affinity from load balancers: Configure your Nginx, Traefik or Ingress Controller with a standard round-robin or least connections algorithm; don’t configure sticky sessions.
  3. [ ] Isolate long-running tasks: Any tool that exceeds 5 seconds must return a durable task_handle and run in the background (Tasks pattern).
  4. [ ] WAL mode for local persistence: If you use SQLite to record tasks or intermediate states, always turn on PRAGMA journal_mode=WAL; to avoid concurrency locks between threads and workers.
  5. [ ] Safe header-based routing: Use the Mcp-Method and Mcp-Name headers in your API gateway to apply specific rate-limiting policies to the most expensive tools.
#Model Context Protocol SDK#FastMCP#Docker#Traefik#SQLite WAL#Redis#n8n v1.88+#Python