PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Guides> Tools and the Model Context Protocol (MCP)

MCP Transports: stdio vs Streamable HTTP vs SSE (Python)

stdio vs Streamable HTTP vs SSE, shown on the wire with curl, then an MCP server over HTTP in production: Host checks, auth, health checks and scaling.

Level
Intermediate
Reading time
22 min
Published
Oct 10, 2026
Last updated
Oct 24, 2026
Tested with
Promptise 1.9.0
By
Promptise Team
  • Model Context Protocol (MCP)
  • Streaming
  • Deployment
Contents · 10 sections↓
  1. 01MCP stdio vs Streamable HTTP vs SSE: which transport should you use?
  2. 02How the three MCP transport types work
  3. 03What MCP 2026-07-28 changes about transports
  4. 04What you need
  5. 05See each MCP transport on the wire, step by step
  6. 06Run an MCP server over HTTP in production
  7. 07Browser clients and CORS
  8. 08Honest limits
  9. 09Frequently asked questions
  10. 10Where to go next

An MCP transport is the pipe between an MCP client and a server, and MCP has three transport types: stdio, Streamable HTTP, and the older HTTP with SSE. The choice decides more than it looks: who starts the server, how many agents can share it, how you secure it, and how you deploy it. This guide compares them on the wire with curl, including the session-free requests of the 2026-07-28 protocol revision, connects one Python agent over all three, then takes the HTTP version to production with Host checks, API keys, a health check and a plan for restarts and replicas. Every output in it is real, printed by the scripts shown, with Promptise Foundry on the MCP SDK 2.3.0 and gpt-5-mini for the agent steps.

[01]

MCP stdio vs Streamable HTTP vs SSE: which transport should you use?

Use stdio when the client should start the server itself on the same machine, as Claude Desktop, IDEs and local agents do. Use Streamable HTTP when the server runs on its own and several agents connect to it by URL; that's the transport for anything shared, remote or behind authentication. Use SSE only for a client that can't speak Streamable HTTP yet, because the MCP specification replaced it with Streamable HTTP in 2025 and now lists it as deprecated.

The newest revision, 2026-07-28, keeps stdio and Streamable HTTP but takes the sessions out of Streamable HTTP: each request stands alone. Servers and clients built for earlier revisions still work, because both sides can speak both.

In Promptise Foundry the same server code runs on all three transports. Only the last line changes:

Pythoninventory_server.py
    server.run(transport=transport, host=os.environ.get("HOST", "127.0.0.1"), port=port)

transport is "stdio", "http" or "sse". On the agent side you pick the matching spec:

Pythonagent.py
1
2
3
4
5
6
7
8
SPECS = {
    # The agent starts the server as a child process and talks over its stdin/stdout.
    "stdio": StdioServerSpec(command=sys.executable, args=["inventory_server.py"]),
    # The server is already running; the agent connects to its /mcp endpoint.
    "http": HTTPServerSpec(url="http://127.0.0.1:8170/mcp"),
    # The legacy transport: a /sse stream plus a /messages/ endpoint.
    "sse": HTTPServerSpec(url="http://127.0.0.1:8171/sse", transport="sse"),
}

If you've only ever switched server.run() to HTTP, as in How to Connect MCP Servers to Your AI Agent in Python, this guide shows what actually changes underneath, and what that means once real traffic arrives.


[02]

How the three MCP transport types work

All three carry the same JSON-RPC messages. What differs is the pipe:

Rendering diagram…

  • stdio: the client launches the server and writes one JSON message per line to its standard input. Answers come back on standard output. There's no network and no port. When the client closes the pipe, the server exits.

  • Streamable HTTP: the server listens on a single endpoint, /mcp. Every message is its own POST. The server answers each request with an SSE stream scoped to that request, or plain JSON. A client that starts with the initialize handshake gets a session, tracked with an mcp-session-id header. A 2026-07-28 client gets no session at all.

  • SSE: the client opens a long-lived GET /sse stream first. The server tells it where to post messages, and every answer arrives on that one stream, not on the POST that asked for it.

Streamable HTTP was introduced in MCP protocol version 2025-03-26 as the replacement for HTTP with SSE from 2024-11-05, as the 2025-03-26 changelog records. Claude Code's MCP docs call SSE deprecated and recommend HTTP for remote servers.

stdio

Streamable HTTP

SSE (legacy)

Who starts the server

The client, as a child process

You do; it runs on its own

You do; it runs on its own

On the wire

One JSON-RPC message per line on stdin and stdout

Each message is a POST /mcp; replies are an SSE stream or JSON

Replies on a long-lived GET /sse stream; requests to POST /messages/

Sessions

One per process

Handshake clients: mcp-session-id header, held in server memory. 2026-07-28: none

session_id in the message URL, held in server memory

Auth

None on the wire; the server runs as the user

API key or bearer token on every request

API key or bearer token on every request

Scaling

One client per process

Handshake clients: sticky sessions or stateless mode. 2026-07-28: any replica

Same as HTTP handshake clients, plus one open stream per client

Clients

Claude Desktop, Claude Code, Cursor, Promptise

Claude Code (recommended), Cursor, Promptise

Claude Code (deprecated there), Cursor, Promptise

Promptise server

server.run()

server.run(transport="http")

server.run(transport="sse")

Promptise client

StdioServerSpec, MCPClient(transport="stdio")

HTTPServerSpec(url=".../mcp"), MCPClient(url=".../mcp")

HTTPServerSpec(url=".../sse", transport="sse")

Client support is taken from the Claude Code and Cursor docs.


[03]

What MCP 2026-07-28 changes about transports

The 2026-07-28 changelog and the Streamable HTTP page of that revision change four things you'll meet in this guide:

  • No handshake. There is no initialize and no notifications/initialized. Every request carries the protocol version, the client's info and its capabilities in _meta. A client that wants to know what a server speaks calls server/discover.

  • No sessions, no GET stream. The mcp-session-id header and DELETE /mcp are gone, and so is the GET stream for server-initiated messages. On HTTP, every request must also send MCP-Protocol-Version, Mcp-Method and, for a tool call, Mcp-Name headers that match the body, so a load balancer can route on them.

  • No server-to-client requests. A server that needs input from the user answers the tool call with an InputRequiredResult, and the client sends the call again with the answer. The spec calls these multi round-trip requests.

  • No resumable streams. Last-Event-ID is not supported. Closing a request's response stream cancels that request.

stdio keeps its framing, one JSON message per line. HTTP with SSE is still described, as a deprecated transport with a fallback recipe for old servers.

What Promptise Foundry 1.10.0 does with this:

  • The server speaks both eras on one endpoint. On the MCP SDK 2.x, which a fresh install gets, /mcp answers server/discover and 2026-07-28 requests, and gives a handshake client the session this guide describes. On the SDK 1.x (mcp<2) the server speaks revisions up to 2025-11-25 only.

  • The client uses the handshake unless you ask. MCPClient(protocol="auto") asks with server/discover first, uses 2026-07-28 when the server offers it, and falls back to initialize otherwise. It works over HTTP and stdio, not SSE, and needs the SDK 2.x.

  • Agents still use the handshake. build_agent, HTTPServerSpec and the Agent Runtime connect with initialize, so an agent always gets the session behavior described in Steps 3 and 4.


[04]

What you need

  • Python 3.10 or newer, and pip install "promptise>=1.9.0". A fresh virtual environment gets the MCP SDK 2.x with it. The SDK 1.x (mcp<2) works too, without 2026-07-28; where it prints something different, the step says so.

  • curl, to look at the raw traffic.

  • An OpenAI API key for the agent steps. Every other step runs without a model.


[05]

See each MCP transport on the wire, step by step

Step 01

Write one server that runs on any transport

A transport is a deployment decision, not a code decision, so keep it out of your tools. This server reads the transport from the command line:

Pythoninventory_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import os
import sys

from promptise.mcp.server import MCPServer

server = MCPServer("inventory", version="1.0.0")

# A stand-in for your warehouse system.
STOCK = {"SKU-1": 42, "SKU-2": 0, "SKU-3": 7}


@server.tool(read_only_hint=True)
async def check_stock(sku: str) -> dict:
    """Get how many units of a product are in stock.

    Args:
        sku: The product code, for example "SKU-1".
    """
    sku = sku.strip().upper()
    if sku not in STOCK:
        return {"error": f"Unknown product {sku}."}
    return {"sku": sku, "in_stock": STOCK[sku]}


if __name__ == "__main__":
    # python inventory_server.py              -> stdio
    # python inventory_server.py http 8170    -> Streamable HTTP on /mcp
    # python inventory_server.py sse 8171     -> legacy SSE on /sse
    transport = sys.argv[1] if len(sys.argv) > 1 else "stdio"
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 8080
    server.run(transport=transport, host=os.environ.get("HOST", "127.0.0.1"), port=port)

Notice the explicit host. server.run() binds 127.0.0.1 by default, so only the same machine can reach the server, and the HOST variable lets each deployment choose. Step 1 of the production section shows what changes on a public bind.

Step 02

Speak stdio by hand

stdio is the simplest transport, and you can drive it from the shell with a pipe. Send the handshake, then a tool call, one JSON object per line, and keep the pipe open until the answer is back:

>_Terminalstdio_raw.sh
# Talk to the stdio server by hand: three JSON-RPC messages, one per line.
: > answers.txt
{
  printf '%s\n' \
    '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"by-hand","version":"0"}}}' \
    '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
    '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"check_stock","arguments":{"sku":"SKU-1"}}}'
  # Keep stdin open until the answer to id 2 is out. Closing stdin stops the server.
  until grep -q '"id":2,' answers.txt; do sleep 0.1; done
} | python inventory_server.py | tee answers.txt
Output
{"jsonrpc":"2.0","id":1,"result":{"capabilities":{"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}},"protocolVersion":"2025-11-25","serverInfo":{"name":"inventory","version":"1.0.0"}}}
{"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\"sku\": \"SKU-1\", \"in_stock\": 42}","type":"text"}],"isError":false}}

Two answers, one per line, and then the server exited because its input closed. That's the whole stdio lifecycle: the client owns the process. It also explains the one stdio rule that bites people: stdout belongs to the protocol. A stray print() in your server corrupts the stream. Log to stderr instead. Promptise skips its startup banner on stdio for this reason.

The until loop is there because a server whose stdin closes can stop before it answers the last request, so a plain printf ... | python inventory_server.py may print only the first answer. With mcp<2 you'll see the same two answers with an extra "experimental":{} capability and the keys in a different order.

Step 03

Open a Streamable HTTP session with curl

Start the same file over HTTP with python inventory_server.py http 8170. It now listens at http://127.0.0.1:8170/mcp. A client has to accept both JSON and an event stream, so send both in Accept. This is the handshake that 2025-11-25 clients, and Promptise agents, use:

>_Terminalhttp_raw.sh
URL=http://127.0.0.1:8170/mcp
ACCEPT="Accept: application/json, text/event-stream"
JSON="Content-Type: application/json"

echo "### 1. initialize"
curl -si $URL -H "$ACCEPT" -H "$JSON" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' \
  | tee init.txt
SESSION=$(grep -i '^mcp-session-id:' init.txt | cut -d' ' -f2 | tr -d '\r')

echo; echo "### 2. initialized notification"
curl -si $URL -H "$ACCEPT" -H "$JSON" -H "mcp-session-id: $SESSION" \
  -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'

echo; echo "### 3. tools/call in the session"
curl -s $URL -H "$ACCEPT" -H "$JSON" -H "mcp-session-id: $SESSION" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"check_stock","arguments":{"sku":"SKU-3"}}}'
Output
### 1. initialize
HTTP/1.1 200 OK
date: Thu, 22 Oct 2026 20:39:56 GMT
server: uvicorn
cache-control: no-cache, no-transform
connection: keep-alive
content-type: text/event-stream
mcp-session-id: 4b6890d89f2f4b9fa9bba63493f51021
x-accel-buffering: no
transfer-encoding: chunked

event: message
data: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"prompts":{"listChanged":true},"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}},"protocolVersion":"2025-11-25","serverInfo":{"name":"inventory","version":"1.0.0"}}}

### 2. initialized notification
HTTP/1.1 202 Accepted
…
### 3. tools/call in the session
event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\"sku\": \"SKU-3\", \"in_stock\": 7}","type":"text"}],"isError":false}}

Three things to notice:

  • The session ID arrives as a response header. The client must send mcp-session-id back on every later request. That's the "session" in Streamable HTTP before 2026-07-28.

  • Even a single answer comes back as text/event-stream. Promptise runs the SDK's session manager with streaming responses, so a reverse proxy must not buffer them. The x-accel-buffering: no header asks Nginx not to.

  • A notification gets 202 Accepted with an empty body. Only requests get answers.

Step 04

Learn the session rules

Sessions are where Streamable HTTP surprises people, so try the edges. The same script continues:

>_Terminalhttp_raw.sh
echo; echo "### 4. the same call without the session header"
curl -si $URL -H "$ACCEPT" -H "$JSON" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/list"}'
Output
### 4. the same call without the session header
HTTP/1.1 400 Bad Request
…
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Bad Request: Missing session ID"}}
…
### 7. end the session
HTTP/1.1 200 OK
…
### 8. use the ended session
HTTP/1.1 404 Not Found
…
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Session not found"}}

Steps 7 and 8 sent DELETE /mcp with the session header, then tried to keep using it. With mcp<2 you'll see the same status codes, with "id":"server-error" in the error bodies instead of "id":null. What each answer means:

  • Forgot the header? 400 Missing session ID. A request with no MCP-Protocol-Version: 2026-07-28 header is treated as a handshake-era request, and those need a session. If you see this from a real client, a proxy is probably stripping the mcp-session-id header.

  • Session gone? 404 Session not found. The 2025-11-25 specification says a client must then start a new session with a fresh initialize. Keep that rule in mind; it matters again in production.

  • Done? DELETE ends the session cleanly, and Promptise's client sends it for you on shutdown.

A Streamable HTTP session step by step: initialize returns an mcp-session-id header, calls carrying it get 200, a call without it gets 400 Missing session ID, DELETE ends the session, and a call with the ended session gets 404, after which the client starts a new session.
FigureThe rules of a Streamable HTTP session, from initialize to a session that is gone
Step 05

Try the legacy SSE transport

Start the server with python inventory_server.py sse 8171, open the stream in the background, and post to the address it gives you:

>_Terminalsse_raw.sh
BASE=http://127.0.0.1:8171
JSON="Content-Type: application/json"

# 1. Open the event stream and keep it open in the background.
curl -sN $BASE/sse > stream.txt &
STREAM=$!
sleep 1
echo "### the stream's first event"
cat stream.txt
ENDPOINT=$(grep '^data:' stream.txt | head -1 | cut -d' ' -f2 | tr -d '\r')

# 2. Send messages to the endpoint the server named. Each POST only says "Accepted".
echo "### POST initialize"
curl -si "$BASE$ENDPOINT" -H "$JSON" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'
echo
curl -s "$BASE$ENDPOINT" -H "$JSON" -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'; echo
curl -s "$BASE$ENDPOINT" -H "$JSON" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"check_stock","arguments":{"sku":"SKU-2"}}}'; echo
sleep 1

# 3. The answers arrived on the stream, not on the POSTs.
echo; echo "### the stream after the POSTs"
cat stream.txt
kill $STREAM
Output
### the stream's first event
event: endpoint
data: /messages/?session_id=fb651d66ee8d4b7fbb0281f5772fd376

### POST initialize
HTTP/1.1 202 Accepted
date: Thu, 22 Oct 2026 20:39:58 GMT
server: uvicorn
content-length: 8

Accepted
Accepted
Accepted

### the stream after the POSTs
event: endpoint
data: /messages/?session_id=fb651d66ee8d4b7fbb0281f5772fd376

event: message
data: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{…},"protocolVersion":"2024-11-05",…

event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\"sku\": \"SKU-2\", \"in_stock\": 0}","type":"text"}],"isError":false}}

This is why SSE was replaced. Every POST gets a bare 202 Accepted, and the real answers travel down one stream that must stay open for the whole conversation. Each client holds a connection open, the request and its answer take different paths through your proxies, and a dropped stream drops everything in flight. Streamable HTTP keeps one endpoint and lets each request carry its own answer.

Step 06

Send a 2026-07-28 request with curl

Now speak the newest revision to the same HTTP server from Step 3. There is no handshake: each request says which revision it uses, in a header and in _meta, and mirrors its method and tool name into headers:

>_Terminalmodern_raw.sh
# MCP 2026-07-28 by hand: no initialize, no session. Every request names its
# protocol version, method and tool in headers and carries the client's info in _meta.
URL=http://127.0.0.1:8170/mcp
ACCEPT="Accept: application/json, text/event-stream"
JSON="Content-Type: application/json"
V="MCP-Protocol-Version: 2026-07-28"
META='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"0"},"io.modelcontextprotocol/clientCapabilities":{}}'

echo "### 1. server/discover: what does the server speak?"
curl -s $URL -H "$ACCEPT" -H "$JSON" -H "$V" -H "Mcp-Method: server/discover" \
  -d '{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{'"$META"'}}'

echo; echo; echo "### 2. tools/call, on its own"
curl -si $URL -H "$ACCEPT" -H "$JSON" -H "$V" -H "Mcp-Method: tools/call" -H "Mcp-Name: check_stock" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"check_stock","arguments":{"sku":"SKU-3"},'"$META"'}}'

echo; echo; echo "### 3. a header that doesn't match the body"
curl -s $URL -H "$ACCEPT" -H "$JSON" -H "$V" -H "Mcp-Method: tools/call" -H "Mcp-Name: delete_everything" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"check_stock","arguments":{"sku":"SKU-3"},'"$META"'}}'

echo; echo; echo "### 4. a GET stream, as handshake clients open"
curl -si $URL -H "Accept: text/event-stream" -H "$V"
Output
### 1. server/discover: what does the server speak?
{"jsonrpc":"2.0","id":1,"result":{"cacheScope":"private","capabilities":{"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}},"resultType":"complete","supportedVersions":["2026-07-28"],"ttlMs":0,"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"inventory","version":"1.0.0"}}}}

### 2. tools/call, on its own
HTTP/1.1 200 OK
date: Thu, 22 Oct 2026 20:41:40 GMT
server: uvicorn
content-length: 236
content-type: application/json

{"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\"sku\": \"SKU-3\", \"in_stock\": 7}","type":"text"}],"isError":false,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"inventory","version":"1.0.0"}}}}

### 3. a header that doesn't match the body
{"jsonrpc":"2.0","id":3,"error":{"code":-32020,"message":"mcp-name header does not match the request body's 'name' parameter"}}

### 4. a GET stream, as handshake clients open
HTTP/1.1 405 Method Not Allowed
date: Thu, 22 Oct 2026 20:41:40 GMT
server: uvicorn
allow: POST
content-length: 0

Compare this with Step 3:

  • One request, one answer. The tool call got plain JSON with no mcp-session-id, so the next request could go to any copy of the server. Every result now carries a resultType and the server's info in _meta.

  • Headers must match the body. A Mcp-Name that disagrees with the tool in the body is refused with -32020, so a gateway that routes or rate-limits on the header can trust it.

  • No GET stream. At this revision GET /mcp is 405. Change notifications move to a subscriptions/listen request, which this guide doesn't cover.

With mcp<2 the server doesn't know this revision: it answers these requests like Step 4, with 400 Missing session ID.

Step 07

Connect an agent over each transport

Now let an agent use all three. This is the full script whose SPECS you saw at the top:

Pythonagent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import asyncio
import sys

from promptise import build_agent
from promptise.config import HTTPServerSpec, StdioServerSpec

SPECS = {
    # The agent starts the server as a child process and talks over its stdin/stdout.
    "stdio": StdioServerSpec(command=sys.executable, args=["inventory_server.py"]),
    # The server is already running; the agent connects to its /mcp endpoint.
    "http": HTTPServerSpec(url="http://127.0.0.1:8170/mcp"),
    # The legacy transport: a /sse stream plus a /messages/ endpoint.
    "sse": HTTPServerSpec(url="http://127.0.0.1:8171/sse", transport="sse"),
}


async def main(transport: str):
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"inventory": SPECS[transport]},
        instructions="You answer stock questions. Use your tools. Reply in one plain sentence.",
        trace_tools=True,
    )
    try:
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Do we have SKU-3 in stock?"}]}
        )
        print(f"[{transport}]", result["messages"][-1].content)
    finally:
        await agent.shutdown()


asyncio.run(main(sys.argv[1]))
Output
$ python agent.py stdio
→ Invoking tool: check_stock with {'sku': 'SKU-3'}
✔ Tool result from check_stock: {"sku": "SKU-3", "in_stock": 7}
[stdio] Yes — we have 7 units of SKU-3 in stock.
$ python agent.py http
→ Invoking tool: check_stock with {'sku': 'SKU-3'}
✔ Tool result from check_stock: {"sku": "SKU-3", "in_stock": 7}
[http] Yes — there are 7 units of SKU-3 in stock.
$ python agent.py sse
→ Invoking tool: check_stock with {'sku': 'SKU-3'}
✔ Tool result from check_stock: {"sku": "SKU-3", "in_stock": 7}
[sse] Yes — there are 7 units of SKU-3 currently in stock.

Same tool, same arguments, same result; only the model's wording varies. Above the transport, nothing changes, which is exactly why you can start on stdio and move to HTTP later. All three agents connected with the initialize handshake: build_agent has no option for 2026-07-28 (as of Foundry 1.10.0).

HTTPServerSpec accepts transport="http", "streamable-http" or "sse". "http" and "streamable-http" are two names for the same Streamable HTTP client, with MCP SDK 1.x and 2.x alike: the source routes both to the SDK's streamable_http_client, or to streamablehttp_client on older 1.x SDKs that lack the new name, and "sse" to the SDK's sse_client. If you don't need an agent, MCPClient takes the same transport names. This script connects to both running servers and starts a stdio copy:

Pythonthree_clients.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import asyncio
import sys

from promptise.mcp.client import MCPClient

CLIENTS = {
    "stdio": MCPClient(transport="stdio", command=sys.executable, args=["inventory_server.py"]),
    "http": MCPClient(url="http://127.0.0.1:8170/mcp", transport="http"),
    "streamable-http": MCPClient(url="http://127.0.0.1:8170/mcp", transport="streamable-http"),
    "sse": MCPClient(url="http://127.0.0.1:8171/sse", transport="sse"),
}


async def main():
    for name, client in CLIENTS.items():
        async with client:
            tools = [t.name for t in await client.list_tools()]
            result = await client.call_tool("check_stock", {"sku": "SKU-1"})
            print(f"{name:16} tools={tools}  {result.content[0].text}")


asyncio.run(main())
Output
stdio            tools=['check_stock']  {"sku": "SKU-1", "in_stock": 42}
http             tools=['check_stock']  {"sku": "SKU-1", "in_stock": 42}
streamable-http  tools=['check_stock']  {"sku": "SKU-1", "in_stock": 42}
sse              tools=['check_stock']  {"sku": "SKU-1", "in_stock": 42}

All four used the handshake, revision 2025-11-25. To use 2026-07-28, pass protocol="auto". MCPClient.protocol_version then tells you what the client and server agreed on. The last client here talks to the same inventory_server.py, started on port 8179 in a second environment with mcp<2:

Pythonprotocol_auto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import asyncio
import sys

from promptise.mcp.client import MCPClient

CLIENTS = {
    "stdio, auto": MCPClient(
        transport="stdio", command=sys.executable, args=["inventory_server.py"], protocol="auto"
    ),
    "http, auto": MCPClient(url="http://127.0.0.1:8170/mcp", protocol="auto"),
    "http, handshake": MCPClient(url="http://127.0.0.1:8170/mcp"),
    # The same server file, run on the MCP SDK 1.x, which has no server/discover.
    "http, auto, SDK 1.x server": MCPClient(url="http://127.0.0.1:8179/mcp", protocol="auto"),
}


async def main():
    for name, client in CLIENTS.items():
        async with client:
            result = await client.call_tool("check_stock", {"sku": "SKU-1"})
            print(f"{name:28} {client.protocol_version}  {result.content[0].text}")


asyncio.run(main())
Output
stdio, auto                  2026-07-28  {"sku": "SKU-1", "in_stock": 42}
http, auto                   2026-07-28  {"sku": "SKU-1", "in_stock": 42}
http, handshake              2025-11-25  {"sku": "SKU-1", "in_stock": 42}
http, auto, SDK 1.x server   2025-11-25  {"sku": "SKU-1", "in_stock": 42}

With "auto", the client used 2026-07-28 over stdio and HTTP, and fell back to the handshake for the server that has no server/discover. protocol="auto" with transport="sse" raises MCPClientError when you create the client, because the SSE transport only speaks the handshake.

When the client and server disagree about the transport, build_agent stops before the model is ever called. These are the errors from pointing each spec at the wrong place:

Output
Streamable HTTP client, SSE server: MCPConnectionRejectedError: Server 'inventory' rejected the connection: 405 Method Not Allowed.
SSE client, Streamable HTTP server: MCPConnectionRejectedError: Server 'inventory' rejected the connection: 400 Bad Request.
URL without /mcp: MCPConnectionRejectedError: Server 'inventory' rejected the connection: 404 Not Found. Check the URL (http://127.0.0.1:8170); Promptise servers serve MCP at /mcp.

A 405 means you're posting to an SSE server's /sse. A 400 on connect from an SSE client usually means the URL is a Streamable HTTP /mcp. And a 404 on the very first connect means the path is wrong; the error says so: a Streamable HTTP URL ends in /mcp.


[06]

Run an MCP server over HTTP in production

Streamable HTTP is the transport to deploy. These steps take the inventory server from your laptop to something you'd put behind a domain name.

Step 01

Keep the server on loopback, and know what that protects

The MCP specification says servers must validate the Origin header, because of DNS rebinding: a web page in your browser can re-point its own hostname at 127.0.0.1 and talk to a server you thought was private. Promptise checks Host and Origin before any MCP message is parsed, for both protocol eras. On a loopback bind, the checks are on by default. These are steps 5 and 6 of http_raw.sh, against the server from Step 3:

>_Terminalhttp_raw.sh
echo; echo; echo "### 5. a foreign Host header (DNS rebinding)"
curl -si $URL -H "$ACCEPT" -H "$JSON" -H "Host: attacker.example" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'

echo; echo; echo "### 6. a foreign Origin header"
curl -si $URL -H "$ACCEPT" -H "$JSON" -H "Origin: http://attacker.example" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'
Output
### 5. a foreign Host header (DNS rebinding)
HTTP/1.1 421 Misdirected Request
…
Invalid Host header

### 6. a foreign Origin header
HTTP/1.1 403 Forbidden
…
Invalid Origin header

Both refused before a session was created. Requests without an Origin header, which is every non-browser MCP client, pass the Origin check.

Warning

server.run() binds 127.0.0.1 by default. On a non-loopback bind such as 0.0.0.0, Promptise turns the Host check off unless you pass allowed_hosts. The same server bound to 0.0.0.0 with no list answered Host: attacker.example with 200. It does warn at startup, without any logging setup:

Output
MCP server 'inventory' is bound to 0.0.0.0:8176, which is reachable from other machines, and has no AuthMiddleware: anyone who can reach that address can list and call every tool. Add AuthMiddleware (JWTAuth, APIKeyAuth, ...), front the server with an authenticating gateway, or bind host='127.0.0.1' (the default).
Host/Origin validation off for non-loopback bind 0.0.0.0: front the server with a gateway that validates Host and Origin, or pass allowed_hosts/allowed_origins
Step 02

Configure the server from the environment

A production server needs three more things: the public hostname your proxy will forward, an API key on every request, and a readiness check. Keep all of them out of the code:

Pythonprod_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import json
import logging
import os
from pathlib import Path

from promptise.mcp.server import APIKeyAuth, AuthMiddleware, HealthCheck, MCPServer

# INFO shows the Host/Origin policy at startup, so you can check a deployment from its logs.
logging.basicConfig(level=logging.INFO)

STOCK_FILE = Path(os.environ.get("STOCK_FILE", "stock.json"))

server = MCPServer("inventory", version="1.0.0", require_auth=True)
server.add_middleware(AuthMiddleware(APIKeyAuth(keys={os.environ["INVENTORY_API_KEY"]: "agents"})))


@server.tool(read_only_hint=True)
async def check_stock(sku: str) -> dict:
    """Get how many units of a product are in stock.

    Args:
        sku: The product code, for example "SKU-1".
    """
    stock = json.loads(STOCK_FILE.read_text())
    sku = sku.strip().upper()
    if sku not in stock:
        return {"error": f"Unknown product {sku}."}
    return {"sku": sku, "in_stock": stock[sku]}


# Liveness and readiness: GET /health and /health/ready, and the MCP resources
# health://liveness and health://readiness.
health = HealthCheck()
health.add_check("stock_file", STOCK_FILE.is_file, required_for_ready=True)
health.register_resources(server)

if __name__ == "__main__":
    server.run(
        transport="http",
        host=os.environ.get("HOST", "127.0.0.1"),
        port=int(os.environ.get("PORT", "8080")),
        # The public name your proxy forwards as Host, e.g. "mcp.example.com".
        allowed_hosts=os.environ["ALLOWED_HOSTS"].split(","),
    )

With require_auth=True and an AuthMiddleware, Promptise rejects any HTTP request without a valid x-api-key or bearer token before it reaches MCP. Start it with HOST=127.0.0.1 PORT=8174 ALLOWED_HOSTS=mcp.example.com python prod_server.py, and right after the startup banner the log tells you the policy it's enforcing:

Output
INFO:promptise.server:Host/Origin validation on: hosts=['127.0.0.1', '127.0.0.1:*', 'localhost', 'localhost:*', '[::1]', '[::1]:*', 'mcp.example.com'] origins=[…]
INFO:promptise.server:MCP server running on http://127.0.0.1:8174/mcp

Without logging.basicConfig(level=logging.INFO) that line isn't printed, so keep it. Warnings, like the two above for a public bind, are printed either way. Authentication & Security covers JWTs and roles if API keys aren't enough, and MCP server authentication with JWT and OAuth builds both step by step.

Step 03

Put it behind a reverse proxy with TLS

Don't terminate TLS in the MCP server. Put Nginx, Caddy or your cloud's load balancer in front, let it handle certificates, and have it forward the public Host header to the server. What your server accepts then depends on where it listens, and the two common setups behave differently. This script sends the Host header each proxy would forward:

>_Terminalprod_hosts.sh
# Which Host headers does each bind accept? INVENTORY_API_KEY is set in the environment.
#   8174: HOST=127.0.0.1 ALLOWED_HOSTS=mcp.example.com python prod_server.py   (behind a proxy on the same machine)
#   8175: HOST=0.0.0.0   ALLOWED_HOSTS=mcp.example.com python prod_server.py   (in a container)
#   8176: HOST=0.0.0.0   python inventory_server.py http 8176                  (public bind, no allowed_hosts)
INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'

probe() {  # probe <port> <Host header> [extra curl args]
  port=$1; host=$2; shift 2
  code=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$port/mcp \
    -H "Accept: application/json, text/event-stream" -H "Content-Type: application/json" \
    -H "Host: $host" "$@" -d "$INIT")
  printf "%-5s Host: %-22s -> %s\n" "$port" "$host" "$code"
}

KEY=(-H "x-api-key: $INVENTORY_API_KEY")
probe 8174 mcp.example.com "${KEY[@]}"
probe 8174 127.0.0.1:8174 "${KEY[@]}"
probe 8174 attacker.example "${KEY[@]}"
probe 8174 mcp.example.com
echo
probe 8175 mcp.example.com "${KEY[@]}"
probe 8175 127.0.0.1:8175 "${KEY[@]}"
probe 8175 attacker.example "${KEY[@]}"
echo
probe 8176 attacker.example
Output
8174  Host: mcp.example.com        -> 200
8174  Host: 127.0.0.1:8174         -> 200
8174  Host: attacker.example       -> 421
8174  Host: mcp.example.com        -> 401

8175  Host: mcp.example.com        -> 200
8175  Host: 127.0.0.1:8175         -> 421
8175  Host: attacker.example       -> 421

8176  Host: attacker.example       -> 200

Read it row by row:

  • Proxy on the same machine (8174). Bind 127.0.0.1 and list the public name. On a loopback bind the names in allowed_hosts are added to the loopback names, so the proxied traffic and your local checks both work. The wrong host gets 421, a missing key gets 401.

  • In a container (8175). You have to bind 0.0.0.0 so traffic can reach the container. On that bind, allowed_hosts is used exactly as given, so even 127.0.0.1 is refused. Add 127.0.0.1:* if anything inside the container calls the MCP endpoint locally. The health routes in Step 4 skip this check, so a health probe doesn't need it.

  • No list at all (8176). Every Host is accepted, and the server says so in a startup warning. Only do this if a gateway in front validates Host and Origin for you.

Whatever proxy you use, check five settings: forward the original Host header, pass mcp-session-id through untouched, pass the MCP-Protocol-Version, Mcp-Method and Mcp-Name headers that 2026-07-28 requests carry, don't buffer text/event-stream responses, and allow long read timeouts for slow tools. The Deployment docs have an Nginx example. It wasn't run for this guide.

Step 04

Add a health check your orchestrator can run

Kubernetes, Docker and load balancers want to ask "are you ready?" The MCP endpoint can't answer a plain GET /mcp. It's the last step of http_raw.sh:

Output
### 9. a plain GET, like a naive health probe
HTTP/1.1 400 Bad Request
…
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Bad Request: Missing session ID"}}

With mcp<2 you'll see 406 Not Acceptable: Client must accept text/event-stream instead, and a GET that says 2026-07-28 gets 405. None of them is any use as a health check.

Promptise serves two plain HTTP routes next to /mcp for this: GET /health for liveness and GET /health/ready for readiness, which runs the checks of the HealthCheck you registered and answers 503 when a required one fails. Probes carry no credentials and send the pod IP as Host, so both routes skip the API key and the Host check, and they never include a failing check's error text. This script asks both servers from Step 3:

>_Terminalhealth_probe.sh
# Liveness and readiness over plain HTTP: no API key, no MCP session.
for port in 8174 8175; do
  echo "--- $port"
  curl -s -w "  HTTP %{http_code}\n" http://127.0.0.1:$port/health
  curl -s -w "  HTTP %{http_code}\n" http://127.0.0.1:$port/health/ready
done

Here it is with the stock file in place, then with it moved away:

Output
$ bash health_probe.sh
--- 8174
{"status":"alive","uptime_seconds":10.9}  HTTP 200
{"status":"ready","checks":{"stock_file":{"healthy":true}}}  HTTP 200
--- 8175
{"status":"alive","uptime_seconds":11.0}  HTTP 200
{"status":"ready","checks":{"stock_file":{"healthy":true}}}  HTTP 200
$ mv stock.json stock.json.bak
$ bash health_probe.sh
--- 8174
{"status":"alive","uptime_seconds":11.0}  HTTP 200
{"status":"not_ready","checks":{"stock_file":{"healthy":false}}}  HTTP 503
--- 8175
{"status":"alive","uptime_seconds":11.1}  HTTP 200
{"status":"not_ready","checks":{"stock_file":{"healthy":false}}}  HTTP 503

The container-style server on 8175 answers too, with no change to its allowed_hosts. The MCP-level resources health://liveness and health://readiness are still there for clients that want the details, including the error text of a failing check.

Point a Kubernetes httpGet probe at /health for liveness and /health/ready for readiness. In Docker, python:*-slim images don't include curl, so use Python itself: HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=5)" exits 0 when ready and 1 on a 503. In a python:3.11-slim image built around prod_server.py with that line, bound to 0.0.0.0 with ALLOWED_HOSTS=mcp.example.com as on 8175, Docker reports the container healthy. It turns unhealthy once the stock file is moved away inside it, and healthy again when the file is back.

Step 05

Plan for more than one replica

A handshake session lives in the memory of one server process. Run two copies of the server and open a session on one of them:

>_Terminaltwo_replicas.sh
# Open a session on replica A.
SESSION=$(curl -si http://127.0.0.1:8172/mcp -H "$ACCEPT" -H "$JSON" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' \
  | grep -i '^mcp-session-id:' | cut -d' ' -f2 | tr -d '\r')
echo "session from replica A: $SESSION"
curl -s -o /dev/null http://127.0.0.1:8172/mcp -H "$ACCEPT" -H "$JSON" -H "mcp-session-id: $SESSION" \
  -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'

for replica in A:8172 B:8173; do
  echo "--- tools/list on replica ${replica%%:*}"
  curl -s -w "\nHTTP %{http_code}\n" http://127.0.0.1:${replica##*:}/mcp -H "$ACCEPT" -H "$JSON" \
    -H "mcp-session-id: $SESSION" -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | cut -c1-120
done
Output
session from replica A: f98d86d74f9840ada8c9abc95a88061e
--- tools/list on replica A
event: message
data: {"jsonrpc":"2.0","id":2,"result":{"tools":[{"annotations":{"readOnlyHint":true},"description":"Get how many units 


HTTP 200
--- tools/list on replica B
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Session not found"}}
HTTP 404

Replica B has never heard of the session. Behind a round-robin load balancer, half of a handshake client's requests would fail like this. You have three ways out:

  • Sticky sessions (session affinity) on the mcp-session-id header, so every request of one session reaches the same replica.

  • 2026-07-28 clients, which have no session to lose. Each request stands alone, as in the curl requests of "Send a 2026-07-28 request with curl", so any replica can answer it.

  • A stateless app. server.asgi_app(stateless=True) gives you the server as an ASGI app that answers handshake clients without a session too:

Pythonasgi_app.py
from inventory_server import server

app = server.asgi_app(stateless=True)

Run two copies with uvicorn asgi_app:app --port 8172 and --port 8173 (or under gunicorn with -k uvicorn.workers.UvicornWorker), initialize on one and call a tool on the other, with no session header:

Output
--- initialize on replica A
HTTP/1.1 200 OK
--- tools/call on replica B, no session header
event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\"sku\": \"SKU-1\", \"in_stock\": 42}","type":"text"}],"isError":false}}


HTTP 200

initialize returns no mcp-session-id, and replica B answers the tool call on its own.

Step 06

Know what you give up without a session

Two server features depend on where a request lands: per-session state and questions to the user. This server has one tool of each kind. restock asks the user two questions with Elicitor, and add_to_cart keeps a cart in SessionState:

Pythonrestock_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os

from mcp.server.request_state import RequestStateSecurity

from promptise.mcp.server import Depends, Elicitor, MCPServer, SessionState

# Every replica must seal and open request_state with the same key (32+ bytes).
key = os.environ.get("MCP_STATE_KEY")
security = RequestStateSecurity(keys=[key]) if key else None
server = MCPServer("inventory", version="1.0.0", request_state_security=security)


@server.tool()
async def restock(sku: str, units: int, elicit: Elicitor = Depends(Elicitor)) -> dict:
    """Order more units of a product from the supplier, after the user confirms."""
    answer = await elicit.ask(
        f"Order {units} more units of {sku}?",
        schema={"type": "object", "properties": {"confirm": {"type": "boolean"}}, "required": ["confirm"]},
    )
    if not answer or not answer.get("confirm"):
        return {"ordered": False, "reason": elicit.last_failure or "not confirmed"}
    where = await elicit.ask(
        "Which warehouse receives them?",
        schema={"type": "object", "properties": {"warehouse": {"type": "string", "enum": ["Berlin", "Lyon"]}}},
    )
    if not where:
        return {"ordered": False, "reason": elicit.last_failure or "no warehouse"}
    # Place the order here, after both answers: code before ask() runs once per round.
    return {"ordered": True, "sku": sku, "units": units, "warehouse": where["warehouse"]}


@server.tool()
async def add_to_cart(sku: str, session: SessionState = Depends(SessionState)) -> dict:
    """Add a product to this session's cart."""
    cart = session.get("cart", []) + [sku]
    session.set("cart", cart)
    return {"cart": cart}


# STATELESS=1 serves every request without a session, also for handshake clients.
app = server.asgi_app(stateless=os.environ.get("STATELESS") == "1")

On a handshake connection, ask() sends the client an elicitation/create request and waits. On 2026-07-28 it can't, so the tool call ends with an InputRequiredResult that holds the question. The client asks its user and sends the call again with the answer, and the tool runs again from the start. With two questions that's three rounds, and the first answer travels to the third round in the result's request_state. The server encrypts that state and binds it to the tool, its arguments and the server, so a client can only send back state the server made. By default each process makes its own key at startup.

This client calls both tools with each protocol, and answers every question with yes:

Pythonrestock_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import asyncio
import json
import sys

from mcp.types import ElicitResult

from promptise.mcp.client import MCPClient, MCPClientError

CALLS = [("restock", {"sku": "SKU-2", "units": 50}), ("add_to_cart", {"sku": "SKU-1"})]


async def answer(context, params):
    """The client's side of an elicitation: here the 'user' always says yes."""
    print("  the server asks:", params.message)
    if "warehouse" in params.message:
        return ElicitResult(action="accept", content={"warehouse": "Berlin"})
    return ElicitResult(action="accept", content={"confirm": True})


def show(result) -> str:
    data = json.loads(result.content[0].text)
    error = data.get("error")
    return f"{error['code']}: {error['message']}" if error else json.dumps(data)


async def main(url: str):
    for protocol in ("auto", "handshake"):
        try:
            async with MCPClient(url=url, protocol=protocol, elicitation_callback=answer) as client:
                print(f"--- protocol={protocol!r} agreed {client.protocol_version}")
                for name, args in CALLS:
                    print(f"  {name}: {show(await client.call_tool(name, args))}")
        except MCPClientError as exc:
            print(f"  MCPClientError: {exc}")


asyncio.run(main(sys.argv[1]))

The output below comes from uvicorn restock_server:app on two ports behind a round-robin proxy with no sticky sessions. The first block gives each replica its own key, the second shares one MCP_STATE_KEY, and the third adds STATELESS=1. The last block is one replica on its own. The elided 2026-07-28 blocks printed the same as with the shared key:

Output
##### two replicas, round robin: own-keys
--- protocol='auto' agreed 2026-07-28
  the server asks: Order 50 more units of SKU-2?
  the server asks: Which warehouse receives them?
  MCPClientError: Failed to call tool 'restock': Invalid or expired requestState
--- protocol='handshake' agreed 2025-11-25
  MCPClientError: Failed to call tool 'restock': the server at http://127.0.0.1:8180/mcp answered HTTP 404 for a freshly opened MCP session. If it runs as several replicas or workers, route each mcp-session-id to the same one (sticky sessions) or serve it stateless.
##### two replicas, round robin: shared-key
--- protocol='auto' agreed 2026-07-28
  the server asks: Order 50 more units of SKU-2?
  the server asks: Which warehouse receives them?
  restock: {"ordered": true, "sku": "SKU-2", "units": 50, "warehouse": "Berlin"}
  add_to_cart: SESSION_REQUIRED: Tool 'add_to_cart' keeps per-session state, but this request uses MCP protocol 2026-07-28, which has no sessions (each request stands alone). Connect with the initialize handshake to use it (Promptise's MCPClient does by default, protocol='handshake'; the MCP Python SDK client with mode='legacy').
--- protocol='handshake' agreed 2025-11-25
  MCPClientError: Failed to call tool 'restock': the server at http://127.0.0.1:8180/mcp answered HTTP 404 …
##### two replicas, round robin: stateless-shared-key
--- protocol='auto' agreed 2026-07-28
…
--- protocol='handshake' agreed 2025-11-25
  restock: {"ordered": false, "reason": "the elicitation request failed (NoBackChannelError)"}
  add_to_cart: SESSION_REQUIRED: Tool 'add_to_cart' keeps per-session state, but this server is stateless (asgi_app(stateless=True)), so no request has a session. Serve it with sessions to use it.
##### one replica
--- protocol='auto' agreed 2026-07-28
…
--- protocol='handshake' agreed 2025-11-25
  the server asks: Order 50 more units of SKU-2?
  the server asks: Which warehouse receives them?
  restock: {"ordered": true, "sku": "SKU-2", "units": 50, "warehouse": "Berlin"}
  add_to_cart: {"cart": ["SKU-1"]}

What each block teaches:

  • Input rounds need a shared key across replicas. With its own key, the replica that got the third round couldn't open the state the other one sealed: Invalid or expired requestState. With one MCP_STATE_KEY on both, the same call worked on any replica. Keep that key in your secret store, like any signing key.

  • Session state never works at 2026-07-28. add_to_cart refused with SESSION_REQUIRED in every setup, even on one replica, instead of starting an empty cart on every call. If 2026-07-28 clients need the cart, keep it in your own store and return a cart_id the client passes back.

  • A stateless app takes questions away from handshake clients. There is no way back to the client, so ask() returned None, and elicit.last_failure said why.

  • Only one replica gives a handshake client everything. For that, use sticky sessions.

Step 07

Plan for restarts

Restart the server while an agent is connected, which is what every deploy does. This script asks the same question before and after a restart:

Pythonagent_restart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
async def main():
    server = start_server()
    await wait_until_up()
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"inventory": HTTPServerSpec(url="http://127.0.0.1:8172/mcp")},
        instructions="You answer stock questions. Use your tools. Reply in one plain sentence.",
        trace_tools=True,
    )
    try:
        await ask(agent, "before restart")
        server.terminate(); server.wait()
        server = start_server()
        await wait_until_up()
        await ask(agent, "after restart")
    finally:
        await agent.shutdown()
        server.terminate(); server.wait()
Output
→ Invoking tool: check_stock with {'sku': 'SKU-1'}
✔ Tool result from check_stock: {"sku": "SKU-1", "in_stock": 42}
[before restart] There are 42 units of SKU-1 in stock.
→ Invoking tool: check_stock with {'sku': 'SKU-1'}
✔ Tool result from check_stock: {"sku": "SKU-1", "in_stock": 42}
[after restart] We have 42 units of SKU-1 in stock.

The new server process has no sessions, so the agent's session is gone, and the server answers its old session ID with 404. Promptise's client then does what the specification asks: it opens a new session and retries the call once. The server refused that call without running it, so no tool runs twice. A connection that drops in the middle of a call is not retried, because the tool may have run; the next call reconnects. An MCPClient(protocol="auto") has no session to lose: after the same restart, its next call was a single POST that the new process answered.


[07]

Browser clients and CORS

If a web app on another origin calls your server directly, the browser needs CORS headers, and Promptise's Origin check needs to allow that origin too. Configure both:

Pythoncors_server.py
1
2
3
4
5
6
7
8
9
10
11
from promptise.mcp.server import CORSConfig

from inventory_server import server

server.run(
    transport="http",
    host="127.0.0.1",
    port=8178,
    allowed_origins=["https://app.example.com"],
    cors=CORSConfig(allow_origins=["https://app.example.com"]),
)

Since Foundry 1.7.0 the default allow_headers cover both eras: Content-Type, Authorization, x-api-key, mcp-session-id, mcp-protocol-version and last-event-id for handshake clients, plus the Mcp-Method and Mcp-Name headers that every 2026-07-28 request carries. If you replace the list, keep all of them, or the browser refuses the preflight with 400 Disallowed CORS headers. expose_headers defaults to mcp-session-id, and CORSConfig refuses allow_origins=["*"] together with allow_credentials=True, so list your origins. Here are a 2026-07-28 preflight and an initialize, both sent from that origin to the server above:

Output
### preflight for a 2026-07-28 request
HTTP/1.1 200 OK
…
access-control-allow-headers: Accept, Accept-Language, Authorization, Content-Language, Content-Type, last-event-id, mcp-method, mcp-name, mcp-protocol-version, mcp-session-id, x-api-key
access-control-allow-origin: https://app.example.com
…
### initialize from the browser origin
HTTP/1.1 200 OK
…
content-type: text/event-stream
mcp-session-id: 412ca48d8a9040e6b44116a8eb4f0b16
x-accel-buffering: no
access-control-expose-headers: mcp-session-id
access-control-allow-origin: https://app.example.com
vary: Origin

The preflight allows both eras' headers, and access-control-expose-headers: mcp-session-id lets the page read the session ID, so a handshake browser client can carry the session on. With require_auth=True, preflights still pass, since they never carry credentials, and a 401 for a missing key carries the CORS headers, so the page can read it.


[08]

Honest limits

  • Handshake sessions are in memory only. Streamable HTTP runs with sessions and no event store, so every restart ends every handshake session. Scale out with sticky sessions, move clients to 2026-07-28, or serve with asgi_app(stateless=True) and give up elicitation and session state for handshake clients.

  • A call in flight during a restart fails. The client reconnects and retries only a call the server refused with 404, never one that may already have run. At 2026-07-28 the spec has no resumable streams either: a request whose stream breaks is lost, and the client sends it again as a new request.

  • What Foundry 1.10.0 doesn't do yet: build_agent, HTTPServerSpec and the Agent Runtime can't connect with 2026-07-28; protocol="auto" needs the MCP SDK 2.x and doesn't work over SSE; sampling from a server tool returns None on 2026-07-28; and this guide didn't try subscriptions/listen.

  • Not tested here: a real Nginx or Caddy in front. The proxy behavior was reproduced by sending the Host header a proxy forwards, and the round-robin balancer in Step 6 was a small Python proxy. The Docker health check and the stateless app under gunicorn with two uvicorn.workers.UvicornWorker workers were run.


[09]

Frequently asked questions

What is the difference between stdio and Streamable HTTP in MCP?

With stdio, the client starts your server as a child process and they exchange JSON-RPC messages over its standard input and output, one per line. With Streamable HTTP, your server runs on its own and clients send each message as an HTTP POST to one /mcp endpoint. stdio suits a local tool for one user; Streamable HTTP suits anything shared, remote or behind authentication.

Is SSE deprecated in MCP?

Yes. MCP protocol version 2025-03-26 replaced the HTTP with SSE transport from 2024-11-05 with Streamable HTTP, the 2026-07-28 specification classifies it as deprecated, and clients like Claude Code label it deprecated. Promptise still serves and connects over SSE with transport="sse", so you can support older clients, but build new servers on Streamable HTTP.

Does MCP 2026-07-28 remove sessions from Streamable HTTP?

Yes. The 2026-07-28 revision removes the initialize handshake, protocol-level sessions and the mcp-session-id header, so every request carries its protocol version and client info and any server instance can answer it. Servers on the MCP Python SDK 2.x, Promptise Foundry 1.7.0 and later among them, still give clients that start with initialize a session, so older clients keep working. Promptise's MCPClient(protocol="auto") uses 2026-07-28 when a server offers it.

What does "Missing session ID" mean on an MCP server?

Your client sent a handshake-era request to a Streamable HTTP server without the mcp-session-id header it received from initialize, and the server answered 400 Bad Request: Missing session ID. Either the client isn't sending the header back, or a proxy is dropping it. A 404 Session not found is different: the session existed, but the server restarted, ended it, or the request landed on another replica. 2026-07-28 requests have no session and never get either error.

Is "http" the same as "streamable-http" in Promptise?

Yes. In Promptise Foundry 1.10.0, HTTPServerSpec(transport="http") and transport="streamable-http" both use the MCP SDK's Streamable HTTP client, with SDK 1.x and 2.x, and "http" is the default. Use transport="sse" only for legacy SSE servers, with a URL ending in /sse.

How do I deploy an MCP server to production?

Run it with transport="http" and an explicit host, put a reverse proxy or load balancer in front for TLS, and pass the public hostname in allowed_hosts. Require an API key or bearer token, probe /health/ready, and use sticky sessions if handshake clients reach more than one replica. Share one RequestStateSecurity key between replicas if tools ask the user questions. Build a Production MCP Server in Python covers what goes inside the server: validation, roles, rate limits and audit logs.


[10]

Where to go next

  • Deployment: transports, Host and Origin validation, CORS, proxies and the promptise serve command.

  • Server fundamentals: tools, resources and prompts.

  • Server configuration: every option on StdioServerSpec and HTTPServerSpec.

  • MCP client: MCPClient, protocol="auto" and MCPMultiClient without an agent.

  • Resilience patterns: HealthCheck, circuit breakers and more.

  • MCP Streamable HTTP, 2026-07-28 and 2025-11-25 transports: the two revisions this guide uses.

  • What is the Model Context Protocol, if you want the basics of clients, servers and tools first.

  • MCP Security Best Practices: a security checklist for a server other people can reach.

  • How to Connect MCP Servers to Your AI Agent in Python and OpenAPI to MCP: Turn Any REST API into an MCP Server.

  • MCP 2026-07-28 Migration: Make Your MCP Server Stateless: move a server that keeps session state to the 2026-07-28 revision, step by step.

  • Make Your SaaS Agent-Ready: MCP, OpenAPI or Both: what to expose to agents and how to keep it safe.

  • MCP Long-Running Tasks: Background Jobs in Python: jobs that outlive one request, and progress and cancellation on each transport.

  • AI Agent Network Egress: Limit Where Agents Can Connect: control which hosts an agent and its tools can reach.

Contents

  1. 01MCP stdio vs Streamable HTTP vs SSE: which transport should you use?
  2. 02How the three MCP transport types work
  3. 03What MCP 2026-07-28 changes about transports
  4. 04What you need
  5. 05See each MCP transport on the wire, step by step
  6. 06Run an MCP server over HTTP in production
  7. 07Browser clients and CORS
  8. 08Honest limits
  9. 09Frequently asked questions
  10. 10Where to go next

Learning paths

Want more structure? Paths put guides in order, like a short course.

See the paths →

> Tools and the Model Context Protocol (MCP)

Related guides

All guides in this topic →
  • // 01Advanced · 22 minMCP 2026-07-28 Migration: Make Your MCP Server StatelessMigrate an MCP server to the stateless 2026-07-28 spec: what changed, how to replace sessions and elicitation, and a runnable before and after in Python.
  • // 02Intermediate · 15 minOpenAPI to MCP: Turn Any REST API into an MCP ServerTurn an OpenAPI spec into a working MCP server in minutes. Read-only by default, human approval on every write, and tested by a real agent.
  • // 03Intermediate · 18 minMake Your SaaS Agent-Ready: MCP, OpenAPI or BothMake your SaaS agent-ready: when to ship an MCP server, an OpenAPI spec or both, what to expose to agents, how auth works, and a runnable example.
  • // 04Advanced · 20 minMCP Authentication in Python: API Keys, JWT and OAuthMCP authentication in Python on one server: API keys, JWTs and OAuth client credentials with JWKS, plus roles, scopes, 401s and agent token forwarding.
  • // 05Intermediate · 25 minBuild an Authenticated MCP Server for Your AI Agent (Python)An MCP server authentication tutorial in Python: JWT login and roles, an agent that acts for each user, an attack script and a verified audit log.
  • // 06Intermediate · 20 minMCP Security Best Practices: A Checklist for MCP ServersMCP security best practices as a checklist: token audience binding, per-tool scopes, input validation, human approval, rate limits and signed audit logs.

Keep going.

Browse every guide by topic and level, or follow a learning path that puts them in order.

All guidesLearning paths