esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

AI engineering / Advanced / 03.03

MCP data and transport layers

What MCP messages say and how they travel: JSON-RPC messages on the inside, stdio or HTTP on the outside, and why the split helps.

13 min readFree

What is said, and how it travels

The last lesson, on MCP hosts, clients and servers, ended with a promise: next, MCP's data and transport layers, what is said and how it travels. Here it is.

Think of a letter. There is what you write inside, and there is how it gets to the other person: a postbox, a courier, a hand-delivery. You can change the delivery without rewriting the letter. MCP is built the same way, in two layers.

By the end you will know what each layer does, the four kinds of message, the two standard ways to carry them, and how a remote server checks who is calling. You will run a small program that writes, checks and reads back real-looking MCP messages.

Key words

Layer
One part of a design that does one job and leaves the other jobs to the part next to it.
Data layer
The inner layer of MCP: what the messages look like and what they mean.
Transport layer
The outer layer of MCP: how the messages physically get from one program to the other.
JSON-RPC
A simple format for asking another program to run something and getting the answer back. JSON is plain text with labelled values.
Framing
Marking where one message ends and the next begins, so a stream of text can be cut back into messages.
stdio
Short for standard input and output: the plain text channels every program already has. Two programs on one computer can talk through them.
OAuth
A common way for a program to prove it has your permission, by showing a token instead of your password.

Two layers, one idea

The official architecture page puts it in one line: "MCP consists of two layers". It describes them like this.

  • Data layer

    Defines "the JSON-RPC based protocol for client-server communication", including capability and version discovery, and core primitives such as tools, resources, prompts and notifications.

  • Transport layer

    Defines "the communication mechanisms and channels" that carry data between clients and servers, including connection set-up, message framing and authorization.

  • How they sit

    The page says "Conceptually the data layer is the inner layer, while the transport layer is the outer layer." The letter is the inner layer. The courier is the outer one.

This lesson uses the specification revision dated 2026-07-28, which the site publishes as "latest". The older 2025-11-25 revision, which the MCP lesson showed, differs in a few places. We will point out where.

Why split them?

The Transports page says: "Protocol semantics are identical on every transport." It adds that a transport "defines how messages are framed and delivered" but "does not define what the messages mean". The architecture page says the transport layer "abstracts communication details from the protocol layer, enabling the same JSON-RPC 2.0 message format across all transport mechanisms".

In daily life: a phone call, a video call and a voicemail can all carry the sentence "Meet me at six." The sentence does not change with the line it travels on.

For you as a builder this is good news. You write a tool once. The same tool can run as a program on your own laptop or as a service on the internet, and the messages stay the same. Only the way you plug it in changes.

The data layer: four kinds of message

The Base protocol page says: "All messages between MCP clients and servers MUST follow the JSON-RPC 2.0 specification." JSON-RPC itself, in its own words, is transport agnostic: the ideas "can be used within the same process, over sockets, over http, or in many various message passing environments". That is why it fits the two-layer plan so well.

There are four shapes. Each one has strict rules, which is what lets two programs written by different people understand each other.

  1. 1

    Request

    Sent to start an operation. It has "jsonrpc" set to "2.0", an "id", a "method" (the name of the action) and optional "params". The spec says requests "MUST include a string or integer ID" and, unlike base JSON-RPC, "the ID MUST NOT be null".

  2. 2

    Response with a result

    Sent when the work succeeded. It must carry the same id as the request and a "result". In revision 2026-07-28 the result must also include a "resultType" field, and "complete" means the request finished with its final content.

  3. 3

    Response with an error

    Sent when the work failed. It has the same id and an "error" with an integer "code" and a text "message". JSON-RPC lists code -32601 as "Method not found".

  4. 4

    Notification

    A one-way message. The spec says notifications "MUST NOT include an ID" and that "The receiver MUST NOT send a response." Think of dropping a postcard: no reply is expected.

The id is a ticket number. You hand it over with your question, and the answer comes back with the same number, so you can match them even when several questions are in flight.

Tip

A response has a result or an error, never both. JSON-RPC states that the result member "MUST NOT exist if there was an error invoking the method".

Primitives, patterns and versions

Above the message shapes sits what MCP is actually for. The architecture page calls the data layer the part that defines how servers share context with clients. Its core building blocks are tools, resources and prompts, the same three the MCP lesson introduced.

The Base protocol page lists three message patterns: request and response; multi round-trip requests, where a server needs extra input from the client to finish a request; and subscribe and notify, where a client asks for a stream of updates that arrive as they happen.

Version handling is where the two revisions differ most. The 2025-11-25 revision and earlier open every connection with an initialize handshake. The 2026-07-28 revision says: "There is no negotiation handshake. Every request carries its protocol version, and the server accepts or rejects each request independently." The version rides inside the message, in a "_meta" field under the key io.modelcontextprotocol/protocolVersion. If the server does not support that version, it must answer with an error that lists the versions it does support. This matches the note in the MCP lesson: check the current specification before you build.

The transport layer: how bytes travel

A computer cannot hand a message to another program by magic. The bytes have to move through something. The Transports page names two standard ways, and it also allows custom ones: "The protocol is transport-agnostic and can be implemented over any communication channel" that meets its needs. Messages must be UTF-8 encoded text.

Choosing between the two is mostly a question of where the server lives.

  • stdio, for local servers

    The client launches the server as its own subprocess on the same machine. The architecture page says this gives direct process communication with no network overhead, and that such local servers typically serve a single client.

  • Streamable HTTP, for remote servers

    The server runs on its own, maybe on the internet, and can handle many clients at once. The architecture page says remote servers using this transport typically serve many clients.

  • Custom, when neither fits

    You may add your own channel. The stdio page suggests reusing its newline framing where you can.

stdio: one message per line

Every program already has a way to read text in and write text out. The stdio page builds on that. In its words: "the client launches the MCP server as a subprocess". The server reads messages from its standard input and writes messages to its standard output.

Framing is wonderfully simple. The page says: "Messages are delimited by newlines, and MUST NOT contain embedded newlines." So one line holds exactly one JSON-RPC message, and a new line means a new message.

Two more rules keep the channel clean. The server "MUST NOT write anything to its stdout that is not a valid MCP message". If it wants to log something, it may write to a separate channel called stderr. And to shut down, the client closes the server's input; the page says servers should exit promptly when their input closes.

The page also says this wire format "works unchanged over Unix domain sockets, TCP connections, or any similar channel". That is the layer split paying off.

Streamable HTTP: one POST per message

For a server that lives elsewhere, the Streamable HTTP page describes a single web address, called the MCP endpoint, that accepts POST. "The client sends every JSON-RPC request or notification as its own HTTP POST." The server answers a request with either one JSON object or a stream of events, called Server-Sent Events, that carries progress notes and then the final response.

A notification gets no answer in JSON-RPC, so HTTP needs a small rule for it: the server must return "202 Accepted" with no body. The page says the client "MUST include an Accept header listing both application/json and text/event-stream as supported content types".

The protocol version also appears as an HTTP header, MCP-Protocol-Version. The Transports page says the HTTP transport mirrors some body fields into headers "so that intermediaries can route and inspect requests without parsing the body", and that "The body remains the source of truth".

The page adds safety rules. Servers must check the Origin header and answer 403 Forbidden if it is present and invalid, to block a trick called DNS rebinding. A server on your own machine should bind only to localhost, not to every network address. Revision 2026-07-28 also removed protocol-level sessions and the GET stream endpoint, so older clients must handle that.

Who is calling? Authorization on HTTP

A server on the internet needs to know who is asking. The Authorization page begins by saying it provides authorization "at the transport level" and defines the flow "for HTTP-based transports". The key rules are short.

  • It is optional

    "Authorization is OPTIONAL for MCP implementations." When it is used, HTTP implementations should follow the spec.

  • stdio skips it

    Implementations using stdio "SHOULD NOT follow this specification, and instead retrieve credentials from the environment". A program you launched yourself already runs with your permissions.

  • Tokens, not passwords

    The server acts as an OAuth 2.1 resource server and the client as an OAuth client. The client sends "Authorization: Bearer <access-token>", and the spec says it "MUST be included in every HTTP request".

Two more lines are worth remembering. Access tokens "MUST NOT be included in the URI query string", because web addresses get stored in logs. And "Invalid or expired tokens MUST receive a HTTP 401 response." A token with too few permissions gets 403 Forbidden.

Quick check

You build an MCP server that runs on your own laptop and is launched by an app over stdio. Does the spec ask you to add the HTTP OAuth flow?

Write, check and frame messages

Now let's handle the messages ourselves, in plain Python with only the json module. This is a teaching model, not an SDK and not a real MCP server. There is no network and no real tool. The text in the response is made up.

The program does three things. It builds a request, its response and a notification. A function called kind checks each shape against the rules above and names the type. And frame writes the messages as the stdio page describes, one per line. Then it reads the stream back line by line. At the end it feeds four broken messages to the checker to show the rules working.

Python
import json

META = "io.modelcontextprotocol/protocolVersion"

request = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
           "params": {"name": "get_weather", "arguments": {"city": "Pune"},
                      "_meta": {META: "2026-07-28"}}}
response = {"jsonrpc": "2.0", "id": 1,
            "result": {"resultType": "complete",
                       "content": [{"type": "text", "text": "Sunny, 31 C (made up)"}]}}
notification = {"jsonrpc": "2.0", "method": "notifications/cancelled"}

def kind(msg):
    """Check the shape and name the message type. Raises ValueError if it is wrong."""
    if msg.get("jsonrpc") != "2.0":
        raise ValueError('jsonrpc must be exactly "2.0"')
    has_id = "id" in msg
    if "method" in msg:
        if not has_id:
            return "notification"
        if msg["id"] is None or isinstance(msg["id"], bool) or not isinstance(msg["id"], (str, int)):
            raise ValueError("a request id must be a string or an integer, never null")
        return "request"
    if not has_id:
        raise ValueError("a response needs an id")
    if ("result" in msg) == ("error" in msg):
        raise ValueError("a response has result or error, never both and never neither")
    if "result" in msg and "resultType" not in msg["result"]:
        raise ValueError("an MCP result needs a resultType")
    return "response"

def frame(messages):
    """stdio framing: one JSON message per line, no newline inside a message."""
    lines = []
    for m in messages:
        kind(m)
        text = json.dumps(m, separators=(",", ":"))
        assert "\n" not in text
        lines.append(text + "\n")
    return "".join(lines)

stream = frame([request, response, notification])
print(stream, end="")
print("---")
for line in stream.splitlines():
    msg = json.loads(line)
    print(kind(msg), "id =", msg.get("id", "none"))

print("---")
bad = [
    {"jsonrpc": "1.0", "id": 2, "method": "ping"},
    {"jsonrpc": "2.0", "id": None, "method": "ping"},
    {"jsonrpc": "2.0", "id": 3, "result": {"resultType": "complete"}, "error": {"code": -1, "message": "x"}},
    {"jsonrpc": "2.0", "id": 4, "result": {"content": []}},
]
for b in bad:
    try:
        kind(b)
    except ValueError as e:
        print("rejected:", e)

Output

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_weather","arguments":{"city":"Pune"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}
{"jsonrpc":"2.0","id":1,"result":{"resultType":"complete","content":[{"type":"text","text":"Sunny, 31 C (made up)"}]}}
{"jsonrpc":"2.0","method":"notifications/cancelled"}
---
request id = 1
response id = 1
notification id = none
---
rejected: jsonrpc must be exactly "2.0"
rejected: a request id must be a string or an integer, never null
rejected: a response has result or error, never both and never neither
rejected: an MCP result needs a resultType

Read the first three lines. Each message sits on its own line with no spaces after the colons, so no newline is ever inside one. The request carries its protocol version in "_meta", as revision 2026-07-28 asks. The response has the same id, 1, and a result with "resultType" set to "complete". The notification has no id at all.

Below the dashes, the program cut the stream back into lines and named each message: a request with id 1, a response with id 1, and a notification with no id. That is the whole job of framing: a stream of text goes in one end and the same messages come out the other.

The last four lines show four broken messages being refused. The first has the wrong "jsonrpc" value. The second uses a null id, which MCP forbids. The third has both a result and an error. The fourth has a result with no "resultType".

Tip

The same three messages would work over HTTP too. Each would be the body of its own POST. Only the framing changes, never the messages.

A real SDK does all of this for you, and much more: timeouts, streams, authorization. Seeing the raw lines once makes its error messages easier to read.

Quick checks

Quick check

Which part of MCP decides how a message is cut apart from the next one on a stdio channel?

Quick check

A message has "jsonrpc": "2.0", a "method" and no "id". What is it?

What to remember

  • Two layers

    The data layer says what a message is. The transport layer says how it travels. The same JSON-RPC 2.0 messages run over any transport.

  • Four shapes

    Request with an id, result response, error response, and a notification with no id and no reply.

  • Two roads

    stdio for a local server, one message per line. Streamable HTTP for a remote one, one POST per message, with bearer tokens for authorization.

Next: building an MCP server, giving models a new tool.

Sources

How is this lesson?

Last updated on 16 November 2026

Learn with me

Every lesson is free. I add new ones as I learn. Have a question, or want help with your own work? Book a short call.