Run a Complete MCP 2026 Stateless Demo – Beginner‑Friendly Guide

This guide walks through the new MCP 2026 update—showing how to build a stateless FastAPI server and a TypeScript client, run curl calls, and highlights benefits such as session‑free requests, cacheable tool lists, easy load‑balancing, and optional OAuth2 protection.

liandk
liandk
liandk
Run a Complete MCP 2026 Stateless Demo – Beginner‑Friendly Guide

Core Changes in the New MCP (2026‑07‑28)

Stateless HTTP single request, no longer dependent on session, pure REST style.

Python MCP Stateless Server (FastAPI)

Install Dependencies

pip install fastapi uvicorn pydantic

main.py

from fastapi import FastAPI
from pydantic import BaseModel
import os

app = FastAPI(title="New MCP 2026 Stateless Server")

# Request schema (MCP new standard input)
class MCPRequest(BaseModel):
    tool_name: str
    params: dict

# Tool registry
tools_def = {
    "file_read": "读取本地文本文件",
    "calc": "简单四则运算 a op b"
}

@app.get("/mcp/tools")
def list_tools():
    """新版支持缓存工具列表,GET 拉取"""
    return {"tools": tools_def}

@app.post("/mcp/call")
def tool_call(req: MCPRequest):
    """无状态单次调用,不存任何会话"""
    if req.tool_name == "file_read":
        path = req.params.get("path")
        try:
            with open(path, "r", encoding="utf-8") as f:
                content = f.read()
            return {"success": True, "data": content}
        except Exception as e:
            return {"success": False, "error": str(e)}
    elif req.tool_name == "calc":
        a = req.params.get("a")
        b = req.params.get("b")
        op = req.params.get("op")
        expr = f"{a}{op}{b}"
        res = eval(expr)
        return {"success": True, "result": res}
    else:
        return {"success": False, "error": "unknown tool"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000)

Run the Server

python main.py

Access the tool list:

http://127.0.0.1:8000/mcp/tools

Curl Call Examples (Simulating AI Requests)

# Calculator
curl -X POST http://127.0.0.1:8000/mcp/call \
-H "Content-Type: application/json" \
-d '{"tool_name":"calc","params":{"a":100,"op":"*","b":20}}'

# Read file
curl -X POST http://127.0.0.1:8000/mcp/call \
-H "Content-Type: application/json" \
-d '{"tool_name":"file_read","params":{"path":"test.txt"}}'

Advantages of the New MCP

Completely stateless; each request is independent, no sessionId required.

Tool list can be cached via GET, reducing duplicate requests.

Load balancers can forward any request directly, enabling effortless horizontal scaling.

OAuth2 authentication headers can be added at the gateway layer for enterprise access control.

TypeScript Client Demo (Simulating Claude Host)

Install

npm i axios

mcp-client.ts

import axios from "axios";

const BASE_URL = "http://127.0.0.1:8000/mcp";

// Fetch tool list (cacheable)
async function getTools() {
  const res = await axios.get(`${BASE_URL}/tools`);
  return res.data;
}

// Call MCP tool
async function callTool(toolName: string, params: Record<string, any>) {
  const res = await axios.post(`${BASE_URL}/call`, {
    tool_name: toolName,
    params
  });
  return res.data;
}

// Test run
(async () => {
  console.log("Available tools:", await getTools());

  // Call calculator
  const calcResult = await callTool("calc", { a: 99, op: "+", b: 1 });
  console.log("Calculation result:", calcResult);

  // Call file read (uncomment to use)
  // const fileResult = await callTool("file_read", { path: "./test.txt" });
  // console.log("File content:", fileResult);
})();

Run the Client

ts-node mcp-client.ts

Real‑World Business Integration Tips

Replace file_read with MySQL/PostgreSQL queries.

Replace calc with calls to DingTalk messaging, CRM order queries, or Excel reads.

Front‑end or AI agents only need to call the unified /mcp/call endpoint.

Add an OAuth2 middleware layer to make the new MCP architecture enterprise‑ready.

One‑Sentence Comparison: Old vs. New MCP

Old MCP required maintaining long connections, session storage, and handshake negotiation, leading to extensive state management code.

New MCP (2026‑07‑28) is a plain HTTP interface, stateless, identical to typical backend CRUD APIs, dramatically reducing operational, scaling, and development complexity.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptMCPOAuth2RESTfastapistateless HTTP
liandk
Written by

liandk

Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.