Skip to content
Index Ai Academy
Phase 9 · Protocol foundations

JSON-RPC 2.0 in depth

Requests, notifications, errors and a dispatcher built from scratch.

About 35 minutes · API rules checked November 2026 · Free lesson

What it covers8

First principles

Which part of an RPC message makes a server owe the caller a reply?

An ID identifies a request that expects an outcome. A notification omits that ID, and a result or error echoes the ID of an ordinary request.

  1. Starting point

    Client supplies a method and a request ID

  2. What changes

    Dispatcher validates the message and attempts the method

  3. Result

    Reply carries the original ID and one outcome

Compare all three steps
  1. Starting point

    Client supplies a method and a request ID

  2. What changes

    Dispatcher validates the message and attempts the method

  3. Result

    Reply carries the original ID and one outcome

Complete and reverse the trace

Given Client supplies a method and a request ID and Reply carries the original ID and one outcome, write down the missing step that connects them.

Compare with the worked step

Dispatcher validates the message and attempts the method

Now take Dispatcher validates the message and attempts the method and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Client supplies a method and a request ID. Check that your implementation produces the result shown above.

Try it on a new case

One valid message is a notification and another has ID 8 with an unknown method. What replies should a server send?

Show worked reasoning

The notification has no reply. The method lookup on request 8 produces an error response with ID 8, so the client can resolve the correct pending request.

Try a different case

Two requests are still pending and response 32 arrives before 31. How should the client decide which request to complete?

Show reasoning for this case

Match the response ID to the pending request ID. Arrival order does not identify a request when work can finish out of order.

Run, change, and build

Check this when debugging. Replying to notifications.

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. One valid message is a notification and another has ID 8 with an unknown method. What replies should a server send?

Why it matters

Every MCP message is JSON-RPC 2.0, so this is the floor everything else in the phase stands on. The spec fits on one page, but the details decide whether a server works with every client or only with yours. Notifications get no answer, ids must match, and a parse error has no id. Bugs here show up as hangs and mysterious timeouts in someone else's app, which makes them painful to debug.

What you'll be able to do

  • Tell requests, results, errors and notifications apart, and know which get answers
  • Use the standard error codes correctly, from -32700 to -32603
  • Follow MCP's extra rules on ids, params and batches
  • Build a JSON-RPC dispatcher that never crashes and never leaks internals
Quick check
A client sends a JSON-RPC message with no "id". What should the server send back?
  1. An error, because every message needs an id
  2. A reply with "id": null, so the client knows
  3. A reply that uses the method name as its id
  4. Nothing: a message with no id is a notification
Show the answer

Nothing: a message with no id is a notification

A message without an id is a notification: the sender doesn't expect an answer, and replying can confuse a client. Getting rules like this exactly right is what makes a server work with every client.

The idea: four kinds of message and one id

This rests on Model Context Protocol, where a tool call crossed the wire as JSON-RPC. Here is the whole format, and the rules that make a server work with every client.

Four kinds of message

You met JSON-RPC briefly in Phase 1. Here's the full picture, and a busy restaurant is a good way to see it.

A waiter writes an order on a numbered ticket. The kitchen sends back a dish with that number, or a note saying "we're out of that", also with the number on it. Now and then someone calls out "table six is leaving", and nobody answers, because nobody asked anything.

Quick check
In the restaurant, someone calls out "table six is leaving" and nobody answers. Why not?
  1. The waiter had lost the ticket
  2. The kitchen was too busy to reply
  3. The dish had already run out
  4. It asked nothing, so no reply is owed
Show the answer

It asked nothing, so no reply is owed

Some messages only tell. With no numbered ticket, there is nothing to send an answer back to. JSON-RPC calls these notifications.

JSON-RPC works the same way. Every message is a JSON object with "jsonrpc": "2.0", and there are exactly four shapes:

messagehas id?has method?has result or error?gets a reply?
requestyesyesnoyes, exactly one
notificationnoyesnonever
result responseyes (same as the request)noresultno
error responseyes (or null if unknown)noerrorno
{"jsonrpc": "2.0", "id": 7, "method": "tools/call",
 "params": {"name": "get_campaign", "arguments": {"id": "cmp_103"}}}
{"jsonrpc": "2.0", "id": 7,
 "result": {"resultType": "complete", "content": [{"type": "text", "text": "..."}]}}
{"jsonrpc": "2.0", "id": 8,
 "error": {"code": -32601, "message": "Method not found: tools/delete"}}
{"jsonrpc": "2.0", "method": "notifications/progress",
 "params": {"progressToken": "t1", "progress": 40, "total": 100}}

The receiver tells them apart by which keys are present. A message with method and id is a request. With method and no id, it's a notification, and the receiver must not reply, not even with an error. Answering a notification is a classic bug: the other side gets a response for an id it never sent.

The id is how answers find their questions. Like tickets in a kitchen, a client can have many requests in flight at once, over one connection, and replies can come back in any order. So the id is the only link.

In plain words: an id means "someone is waiting for an answer to this". No id means nobody is, so stay quiet.

Quick check
From the lesson on the Model Context Protocol: an MCP tool becomes a Claude tool with the same name and description, and inputSchema becomes input_schema. What does this print?
mcp_tool = {"name": "get_campaign", "description": "Look up one campaign.",
            "inputSchema": {"type": "object"}}
claude_tool = {"name": mcp_tool["name"], "description": mcp_tool["description"],
               "input_schema": mcp_tool["inputSchema"]}
print(sorted(claude_tool), claude_tool["name"])
  1. ['description', 'input_schema', 'name'] get_campaign
  2. ['description', 'inputSchema', 'name'] get_campaign
  3. ['description', 'input_schema', 'name'] Look up one campaign.
  4. ['input_schema', 'name'] get_campaign
Show the answer

['description', 'input_schema', 'name'] get_campaign

Three fields carry over, and only one key changes its spelling. That tool list reached the host inside JSON-RPC messages, and so does every call the model makes afterward. This lesson is about those messages: their four shapes, and what a server may and may not send back.

Try it now

Two questions identify any message: does it have an id, and does it have a method?

Quick check
Which of these should a server NOT reply to?
  1. {"jsonrpc": "2.0", "id": 0, "method": "server/discover", "params": {}}
  2. {"jsonrpc": "2.0", "id": "a", "method": "nonsense", "params": {"x": 1}}
  3. {"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 4}}
  4. {"jsonrpc": "2.0", "id": 4, "method": "tools/list", "params": {"cursor": "p2"}}
Show the answer

{"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 4}}

No id means notification, and notifications never get a reply. The unknown method still gets an error reply, because it's a request. An id of 0 is a perfectly good id.

Error codes

Error codes are like the stamps on returned mail: "address unreadable", "no such person", "wrong postage". JSON-RPC reserves a few codes for problems with the message itself:

codenamewhen
-32700Parse errorthe text isn't valid JSON at all
-32600Invalid Requestvalid JSON, but not a proper request (no method, wrong version)
-32601Method not foundno such method
-32602Invalid paramsthe method exists, but the params are wrong
-32603Internal errorthe server failed while handling it

JSON-RPC leaves -32000 to -32099 to implementations, and MCP splits it. It takes -32020 to -32099 for itself, with names such as UnsupportedProtocolVersion (-32022), which Versions and stateless requests uses. -32000 to -32019 is a legacy range: older SDKs and revisions used it, such as -32002 for a missing resource, and new servers shouldn't add codes there. A server's own error codes go outside -32768 to -32000 altogether.

Two subtle rules. First, for a parse error the server can't read the id, so the error response has "id": null. If a letter arrives soaked and unreadable, you can't tell who to answer. Second, an error has a message for people and an optional data field for machines, like the list of supported versions.

Worked example

Which error code?

Each failure has its own code, and the first checks happen before your tool code runs. Follow one message at a time through the checks.

import json

METHODS = {"tools/list": {"params": []}, "tools/call": {"params": ["name"]}}

def check(raw):
    try:
        msg = json.loads(raw)
    except ValueError:
        return -32700, "parse error"
    if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0" or "method" not in msg:
        return -32600, "invalid request"
    if msg["method"] not in METHODS:
        return -32601, "method not found"
    for needed in METHODS[msg["method"]]["params"]:
        if needed not in msg.get("params", {}):
            return -32602, "invalid params"
    return 0, "ok"

for raw in ['{"jsonrpc": ',
            '{"id": 1, "method": "tools/list"}',
            '{"jsonrpc": "2.0", "id": 2, "method": "tools/delete"}',
            '{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {}}',
            '{"jsonrpc": "2.0", "id": 4, "method": "tools/list"}']:
    print(check(raw))
It runs right here in your browser, with nothing to install.

The order runs from can't read it, to not a valid message, to no such method, to missing arguments. A precise code tells a client developer exactly where to look. An unhelpful -32603 on everything tells them nothing.

MCP's extra rules

MCP adds a few rules on top of plain JSON-RPC:

  • Ids must be a string or an integer, never null, and never reused while that request is still waiting. Watch out for true: Python's isinstance(True, int) is True, but a boolean id is invalid.
  • params is always an object with named fields. JSON-RPC also allows a list, but MCP never uses one.
  • No batches. Plain JSON-RPC lets you send a list of requests at once. MCP removed batching in 2025, so every message is a single object.
  • Both directions are allowed in JSON-RPC. In current MCP, clients send requests and servers answer them. Servers also send notifications, such as progress, while working on a request.
Quick check
A server receives the text {"jsonrpc": "2.0", "id": 3, "method": (cut off mid-message). What should it send back?
  1. An error with code -32601
  2. Nothing, because it's broken
  3. An error with code -32700 and id null
  4. An error with code -32700 and id 3
Show the answer

An error with code -32700 and id null

It isn't valid JSON, so it's a parse error. The server can't trust anything inside, including the id, so the id is null.

In your own words
What are JSON-RPC's four kinds of message, and which get answers?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: a dispatcher that never falls over

This part builds the dispatcher from the six checks, one message in and at most one out.

The six checks in order

A dispatcher turns one incoming message into at most one outgoing message. Think of a mailroom clerk. Every envelope goes through the same steps in the same order, and whatever goes wrong, the clerk sends back a proper note instead of walking out. A good dispatcher has a fixed order of checks, and every failure becomes a proper error response:

  1. Parse the JSON. Failure: -32700, id null.
  2. Check the shape: an object, jsonrpc is "2.0", method is a string, and the id (if present) is a string or an integer. Failure: -32600.
  3. If there's no id, it's a notification: run it, ignore any error, and return nothing.
  4. Check params is an object (or missing). Failure: -32602.
  5. Look up the method. Failure: -32601.
  6. Call it. Errors your code raises on purpose keep their code and message. Anything unexpected becomes -32603 with a generic message, logged privately but never sent with the traceback.

That last step is the framework idea from Phase 8 again: expected errors pass through, and surprises are caught and hidden.

Quick check
A dispatcher turns one incoming message into at most one reply. What does this print for a notification, a request for an unknown method, and a discovery request?
METHODS = {"server/discover": lambda params: {"supportedVersions": ["2026-07-28"]}}

def dispatch(msg):
    if "id" not in msg:
        return None
    if msg.get("method") not in METHODS:
        return {"jsonrpc": "2.0", "id": msg["id"],
                "error": {"code": -32601, "message": "Method not found"}}
    return {"jsonrpc": "2.0", "id": msg["id"],
            "result": METHODS[msg["method"]](msg.get("params"))}

note = {"jsonrpc": "2.0", "method": "notifications/progress"}
nope = {"jsonrpc": "2.0", "id": 4, "method": "tools/nope"}
discover = {"jsonrpc": "2.0", "id": 5, "method": "server/discover"}
print(dispatch(note), dispatch(nope)["error"]["code"],
      dispatch(discover)["result"]["supportedVersions"])
  1. None -32601 ['2026-07-28']
  2. None -32600 ['2026-07-28']
  3. None -32601 None
  4. -32601 -32601 ['2026-07-28']
Show the answer

None -32601 ['2026-07-28']

The first message has no id, so it is a notification and gets no reply at all, not even an error. The second names a method the server doesn't have, which is error −32601. The third is server/discover, which every server must answer, and its result lists the versions the server supports. Every reply carries the id of the request it answers.

Worked example

One message in, at most one out

A tiny dispatcher with two methods. Notice the notification produces no output at all.

import json

def handle(raw, methods):
    try:
        msg = json.loads(raw)
    except json.JSONDecodeError:
        return {"jsonrpc": "2.0", "id": None,
                "error": {"code": -32700, "message": "Parse error"}}
    if "id" not in msg:
        if msg.get("method") in methods:
            methods[msg["method"]](msg.get("params", {}))
        return None                                  # notifications get no reply
    fn = methods.get(msg.get("method"))
    if fn is None:
        error = {"code": -32601, "message": f"Method not found: {msg.get('method')}"}
        return {"jsonrpc": "2.0", "id": msg["id"], "error": error}
    return {"jsonrpc": "2.0", "id": msg["id"], "result": fn(msg.get("params", {}))}

seen = []
methods = {"echo": lambda p: {"you_said": p.get("text")},
           "notifications/log": lambda p: seen.append(p["line"])}
for raw in ['{"jsonrpc": "2.0", "id": 1, "method": "echo", "params": {"text": "hi"}}',
            '{"jsonrpc": "2.0", "method": "notifications/log",'
            ' "params": {"line": "started"}}',
            '{"jsonrpc": "2.0", "id": 2, "method": "missing"}',
            '{"jsonrpc": "2.0", "id": 3, "method": ']:
    print(handle(raw, methods))
print("logged:", seen)
In the lesson you can change this and run it.

Four messages in, three replies out: the notification ran (it logged "started") but sent nothing back. This version skips several checks from the list above. The exercise adds them all, which is what makes a dispatcher safe to expose.

Drill

Which kind of message is this?

Write kind(msg) for a parsed JSON-RPC message (a dict): "request" if it has a method and an id; "notification" if it has a method and no id; "response" if it has an id and exactly one of result or error; otherwise "invalid". Anything that isn't a dict, or lacks "jsonrpc": "2.0", is invalid.

def kind(msg):
    return "request" if "method" in msg else "response"


print(kind({"jsonrpc": "2.0", "method": "notifications/cancelled",
            "params": {"requestId": 4}}))
In the lesson, your code is checked as you write it.
Drill

Build an error reply

Write error_reply(msg_id, code, data=None): return a JSON-RPC error response with the standard message for the code, from MESSAGES, and a data field inside the error only when data is given. Raise ValueError for a code that isn't in the table.

MESSAGES = {
    -32700: "Parse error",
    -32600: "Invalid Request",
    -32601: "Method not found",
    -32602: "Invalid params",
    -32603: "Internal error",
}


def error_reply(msg_id, code, data=None):
    return {"id": msg_id, "error": code}


print(error_reply(7, -32601, {"method": "tools/run"}))
In the lesson, your code is checked as you write it.
Quick check
Is this message a request or a notification? What does this print?
import json

msg = json.loads(
    '{"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progress": 5}}')
print("id" in msg)
  1. True
  2. None
  3. False
  4. 5
Show the answer

False

The message has no "id" key, so in gives False. No id means a notification, and notifications never get a reply, not even an error.

In your own words
What makes a dispatcher that never falls over?

Write a sentence or two, then compare it with a good answer in the lesson.

In the SDK and a real host: ids in a real log

Purpose. Know where your dispatcher lives in a real server, and how to read a real exchange when a call hangs.

In an SDK server you never write the dispatcher: the SDK parses, checks the shape, matches methods, wraps your handler's errors and numbers the replies. It does exactly the six checks in this part. What you gain from having written one is the ability to read a host's log when a call hangs.

In an engineer's week. A user says "the tool never answers". You open the host's log or the Inspector's history and find request 7. If reply 7 is missing, the server crashed or hung on it. If a reply with a different id appears, the server answered the wrong message, usually a notification. If the reply is an error, the code tells you which of the six checks failed.

Goes deeper in

In your own words
A host shows request 7 and no reply 7. What are the two likeliest causes?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 2 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What makes a JSON-RPC message a notification?

  1. It has a method but no id
  2. Its method starts with notifications/
  3. It has an id of 0
  4. It has no params

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 9 · about 13 hours of study

Model Context Protocol

Build MCP servers, clients and hosts, from the wire format to production 17 lessons 1 free
  1. JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
  2. Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
  3. Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
  4. Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
  5. Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
  6. Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
  7. Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
  8. The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
  9. Build a clientMetadata on every request, version fallback, paging and caching.40 min
  10. Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
  11. Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
  12. Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
  13. MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
  14. Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
  15. Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
  16. MCP in production: gateways, limits and auditAn allowlist, per-user rate limits, header checks and an audit log in front of many servers.35 min
  17. Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
Part of a free course 15 lessons

Build and Deploy MCP Integrations

Build a Model Context Protocol client and server, then verify the integration with a compatible host.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write