Skip to content
ImagineWorld

Explaining the Model Context Protocol

node_idnode-book_learn-model-context-protocol-with-python_chapter-02-explaining-the-model-context-protocol
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleExplaining the Model Context Protocol
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Explaining the Model Context Protocol

Section titled “Chapter 2 — Explaining the Model Context Protocol”

The MCP consists of many parts. In short, JavaScript Object Notation-Remote Procedure Call (JSON-RPC) messages are exchanged between the client and the server. A JSON-RPC message is a message following the JSON-RPC specification, which means it has the jsonrpc, id, method, and params fields, and the data type is JSON. An example could look like so:

{
"jsonrpc": "2.0",
"id": 1,
"method": "doSomething",
"params": {
"foo": "bar"
}
}

(1) to quickly copy code into your coding environment, or click the Explain button

(2) to get the AI assistant to explain a block of code to you.

![A white background with a black text

AI-generated content may be incorrect.](https://static.packt-cdn.com/products/9781806103232/graphics/Images/image_%282%29.png)

A white background with a black text AI-generated content may be incorrect.

To make it easier to understand, and more interesting, this chapter attempts to explain the protocol by taking you through an implementation of it. For that reason, we hope this chapter is an easier read (not just architecture diagrams) and a glimpse into how things work. If you’re keen on getting started with building MCP servers, then jump straight to Chapter 3, but if you want to understand the MCP protocol a bit more, then keep reading. You can also return to this chapter later.

In this chapter, you will learn about the following:

  • The most common message flows in MCP and their message types
  • How the underlying SDK implementation roughly works

The chapter covers the following topics:

  • Learning about the protocol by implementing it
  • Transports in MCP

Learning about the protocol by implementing it

Section titled “Learning about the protocol by implementing it”

Instead of making this a dry chapter about a protocol and its different messages, let’s make it enjoyable by actually talking about the processes and messages while implementing them. As part of explaining the process and its flows, you will be shown both the flows as diagrams and also implemented as code. Let’s begin.

The idea with transports in MCP is that they define how clients and servers communicate. MCP is transport agnostic, meaning it can work over HTTP, WebSockets, STDIO, and more. The transport is the layer that handles the underlying message exchange. It exchanges messages of type JSON-RPC.

MCP has a set of transports it supports from STDIO (for servers running locally) to streamable transports such as WebSockets and Server-Sent-Events (SSEs), and finally request/response transports such as HTTP.

For each of the specified transports, they all have in common that they operate on streams. All the transports have a method exposing those streams, like so:

async with anyio.create_task_group() as tg
...
yield (read_stream, write_stream)

There’s also a BaseSession class that all transports use to send raw JSON-RPC messages, which looks like so.

class BaseSession(
Generic[
SendRequestT,
SendNotificationT,
SendResultT,
ReceiveRequestT,
ReceiveNotificationT,
],
):
...
def send_request():
...
def send_notification():
...
def response():
...
def _send_response():
...

This class defines methods such as send_request, send_notification, and response, which send JSON-RPC messages.

Okay, let’s start our journey understanding and implementing the message flow in MCP. We will use the STDIO transport as an example for this exercise. Let’s go!

I’m sure you’re familiar with seeing messages in the console or even typing into the console – that’s standard input and output, or STDIO for short. But how can we leverage these streams for a program? Well, let’s start thinking in terms of a server and a client. A client would write a message to a server, and a server would respond with something. Let’s look at a very simple server implementation for STDIO:

The server will need to listen to standard input (stdin) for incoming messages. In Python, you can use sys.stdin and iterate over it to get the next message, like so:

import sys
for line in sys.stdin:
message = line.strip()

We also want to differentiate between simple text messages and JSON-RPC messages. Simple text messages can be handled directly, while JSON-RPC messages will need to be parsed and responded to according to the JSON-RPC specification. Let’s identify JSON-RPC messages by their structure with code such as this:

if line.startswith('{"jsonrpc":'):
json_message = json.loads(line)
# do something with message

Also, we need to send messages back to the calling client. We can do that with print and sys.stdout.flush(), like so:

print("message")
sys.stdout.flush()

Now that we’ve identified the key elements to implement, let’s create the first server:

import sys
import json
while True:
for line in sys.stdin:
message = line.strip()
if message == "hello":
# send message to client
print("hello there")
sys.stdout.flush() # Ensure output is sent immediately
elif message.startswith('{"jsonrpc":'):
# parse it as a JSON message
json_message = json.loads(message)
# identify what type of JSON-RPC message it is and
# respond accordingly
match json_message['method']:
case "tools/list":
response = {
"jsonrpc": "2.0",
"id": json_message["id"],
"result": ["tool1", "tool2"]
}
print(json.dumps(response))
sys.stdout.flush()
break
case _:
print(f"Unknown method: {json_message['method']}")
sys.stdout.flush()
break
elif message == "exit":
print("Exiting server.")
sys.stdout.flush()
sys.exit(0)
else:
print(f"Unknown message: {message}")

In the preceding code, we’ve done the following:

  • Created code that listens to sys.stdin
  • Responded with hello there if it’s being sent hello and if given a JSON message, parsed it and thereafter examined its method property and responded differently depending on its value
  • Added code that makes the program shut down if given the text exit

Note how we have code that prints and flushes like so:

print(json.dumps(response))
sys.stdout.flush()

That can be rewritten as a send_response function like so:

def send_response(response):
print(json.dumps(response))
sys.stdout.flush()

This means our server code will now look like so:

server.py
import sys
import json
def send_response(response):
print(json.dumps(response))
sys.stdout.flush()
while True:
for line in sys.stdin:
message = line.strip()
if message == "hello":
send_response("hello there")
elif message.startswith('{"jsonrpc":'):
json_message = json.loads(message)
match json_message['method']:
case "tools/list":
response = {
"jsonrpc": "2.0",
"id": json_message["id"],
"result": ["tool1", "tool2"]
}
send_response(response)
break
case _:
send_response(f"Unknown method:
{json_message['method']}")
break
elif message == "exit":
send_response("Exiting server.")
sys.exit(0)
else:
send_response(f"Unknown message: {message}")

So, how can we create a client for this? Well, a client should be sending messages and be able to receive server messages. A way to achieve this is by creating the server as a child process with the client being the parent process sending messages to the server. Then, we can communicate with it via standard input and output.

Here’s what an implementation can look like:

The way you send a message as a client to the server is by writing to its stdin and reading from its stdout. Here’s a simple example:

proc.stdin.write(message)
proc.stdin.flush()

This code can be refactored to a send_message function like so:

def send_message(proc, message):
proc.stdin.write(message)
proc.stdin.flush()

Let’s use the send_message function in our client code when we create the client.

client.py
import subprocess
import json
# Start the child process
proc = subprocess.Popen(
['python3', 'server.py'], # Replace with your child script
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True
)
list_tools_message = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
};
message = 'hello\n'
def send_message(message):
"""Send a message to the child process."""
print(f'[CLIENT] Sending message to server...
Message: {message.strip()}')
proc.stdin.write(message)
proc.stdin.flush()
def serialize_message(message):
"""Serialize a message to JSON format."""
return json.dumps(message) + '\n'
# Send a message to the child
send_message(message)
# Read response from child
response = proc.stdout.readline()
print('[SERVER]:', response.strip())
# send a JSON-RPC message
send_message(serialize_message(list_tools_message))
response = proc.stdout.readline()
print('[SERVER]:', response.strip())
# this closes down the child process aka server
send_message('exit\n')
proc.stdin.close()
exit_code = proc.wait()
print(f"Child exited with code {exit_code}")

Here, you can see how the following happens:

  • The client creates a server as a sub-process and ends up writing outgoing messages to said processes via writing to stdin using the send_message method
  • Conversely, it listens to stdout for the child process (server) to send back responses with the proc.stdout.readline() code

This code is a great start to build on to start implementing MCP and the STDIO transport. In fact, this is pretty much what happens, except for the fact that MCP communicates with JSON-RPC messages, so let’s make it more like MCP next.

Our code in the previous section pretty much acted like the STDIO transport does for MCP. For that to be fully true, though, we need the client and server to exchange JSON-RPC messages. So, what are those?

Let’s have a look at an example jsonrpc message:

const listTools = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
};

Here, we have a JSON-RPC message, and what makes it one is, first, it’s in JSON format, and secondly, it has an attribute called jsonrpc. Furthermore, it should have an id attribute, method, and params. The preceding tools/list message is something a client would send to a server, and the server should respond with its available tools, as this command is used to figure out what tools a server has.

So, what’s our first step when building an MCP server? Well, it’s the initialization process, also known as a handshake, so let’s work on that next.

See a running example of this code in the solution folder – check https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md.

Next, now that we have simple client and server code working, we should focus on the initialization process in MCP, sometimes referred to as a handshake.

Here’s what initialization looks like at the mile-high level:

Figure 2.1 – Initialization process

Figure 2.1 – Initialization process

What happens in the preceding process is this:

  • First, the client sends an initialize request, meaning it wants to know from the server what its capabilities are.
  • Then, the server responds with its capabilities – that is, what features it has.
  • Lastly, the client lets the server know it’s ready to perform operations by sending an initialized notification. Before the mentioned notification, any other types of messages, such as listing or running tools, should produce an error response as the handshake hasn’t fully taken place.

Let’s look at the message for each step:

  1. Client sends initialize request: Here’s what the client sends to the server:
    {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
    "roots": {
    "listChanged": true
    },
    "sampling": {}
    },
    "clientInfo": {
    "name": "ExampleClient",
    "version": "1.0.0"
    }
    }
    }

This is an initialize message, which you can see from method with the value initialize. The client must also send its capabilities, which includes roots and sampling in this case. Here’s a closer look at the capabilities of the client:

"capabilities": {
"roots": {
"listChanged": true
},
"sampling": {}
}
  1. Server initializes response: The server, on the other hand, must answer with a similar message of its capabilities – that is, whether it supports tools, resources, prompts, notifications, and so on. Here’s what a typical server response looks like:
    {
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
    "logging": {},
    "prompts": {
    "listChanged": true
    },
    "resources": {
    "subscribe": true,
    "listChanged": true
    },
    "tools": {
    "listChanged": true
    }
    },
    "serverInfo": {
    "name": "ExampleServer",
    "version": "1.0.0"
    }
    }
    }

Observe the capabilities attribute in the response, containing things such as logging, prompts, resources, and tools. Logging is the ability of the server to send log messages to the client. We will show an example of logging notifications in Chapter 5. The other capabilities – prompts, resources, and tools – are the basic features that a server can have – more on those in Chapter 3.

This answer will help the client determine what it can and can’t use. It also provides information on protocol version and server info.

Let’s have a look at the initialized message coming from the client, and then we’ll try implementing the preceding message flow.

  1. Concluding the handshake: As the final step, the client sends an initialized message. This is the final message of the handshake. Once received, the server is ready to take on any type of JSON-RPC message from the client on tools, resources, or prompts. This message from the client should not produce a response from the server. However, the server should remember it’s been initialized. Once initialized, normal operations can take place, such as calling tools, prompts, and more. Here’s the initialized message in detail – as you can see, it doesn’t carry much information but is crucial for the client and server to operate normally. Before this notification has been sent, you can’t do much.
    {
    "jsonrpc": "2.0",
    "method": "notifications/initialized"
    }

How can we implement this? Let us look at that next.

There were a few messages exchanged back and forth. In reality, the client can just send initialized to the server and you’re done, but it’s considered good practice to exchange capabilities first via initialize.

The client code in the previous subsection was just sending text messages and JSON-RPC messages, but it wasn’t really following the flow of the initialization process. To address this, we need to change the client so that it properly handles the initialization sequence. After said sequence is complete, then the client can send other types of messages such as listing tools and so on.

Let’s add a connect function to the client and make sure it first asks for server capabilities, followed by notifying the server that things have been initialized.

client.py
def connect():
print("Connecting to the server...")
# 1. Ask for capabilities
send_message(serialize_message(initialize_message))
# Read response from child/server
response = proc.stdout.readline()
print_response(response, prefix='[SERVER]: \n')
# 2. Send initialized notification, handshake is done
send_message(serialize_message(initialized_message))

Let’s explain the implementation:

  • It created a connect function, asking for both capabilities and sending an initialized notification.
  • It set up a call chain that starts with asking for capabilities by dispatching the initialize message, thereafter dispatching initialized, and thereby ending the handshake process.

Let’s improve things further with a main function, like so:

def list_tools():
# 3. send a message to list tools
# send a JSON-RPC message
send_message(serialize_message(list_tools_message))
response = proc.stdout.readline()
print_response(response, prefix='[SERVER]: \n')
def close_server():
send_message('exit\n')
exit_code = proc.wait()
print(f"Child exited with code {exit_code}")
def main():
connect()
list_tools()
close_server()
main()

Here’s what we created:

  • We created a main function that connects to the server, lists the tools, and ends up closing the server connection once done
  • We defined list_tools, which sends a specific JSON-RPC message that asks the server to list its tools
  • Additionally, we created the close_server method, which sends a quit message to the server.

Let’s work on the server part:

For the server, we need to ensure it reacts accordingly. This means the server needs to only accept messages with an initialize or notifications/initialized method. All other messages before initialization should cause an error. After initialization, all other messages that we support should be okay for the client to send.

To deal with a case of the client trying to do something other than initialization, here’s code to handle that:

if method != "initialize" and method != "notifications/initialized":
print(f"Server not initialized. Please send an 'initialized'
notification first. You sent {method}")
sys.stdout.flush()
continue

This code will stop any further processing of the message and wait for the next incoming message.

For the initialize and notifications/initialized messages, we can handle them like so:

match method:
case "notifications/initialized":
# print("Server initialized successfully.")
sys.stdout.flush()
initialized = True
break
case "initialize":
print(json.dumps(initializeResponse))
sys.stdout.flush()
# initialized = True
break
# should return capabilities

Let’s put the code together so we see what the full server looks like:

server.py
# code omitted for brevity
elif message.startswith('{"jsonrpc":'):
json_message = json.loads(message)
method = json_message.get('method', '')
if not initialized:
if method != "initialize" and method != "notifications/initialized":
print(f"Server not initialized. Please send an 'initialized'
notification first. You sent {method}")
sys.stdout.flush()
continue
match method:
case "notifications/initialized":
# print("Server initialized successfully.")
sys.stdout.flush()
initialized = True
break
case "initialize":
print(json.dumps(initializeResponse))
sys.stdout.flush()
# initialized = True
break
# should return capabilities
case "tools/list":
response = {
"jsonrpc": "2.0",
"id": json_message["id"],
"result": ["tool1", "tool2"]
}
print(json.dumps(response))
sys.stdout.flush()
break
case _:
print(f"Unknown method: {json_message['method']}")
sys.stdout.flush()
break

As an exercise, you’re recommended to improve the preceding solution as you see fit. You could rewrite this code into a send_response method like so:

def send_response(response):
print(json.dumps(response))
sys.stdout.flush()

In the preceding code, we’ve done the following:

  • Defined an elif that says if we have a JSON-RPC message, we will try to route the message correctly
  • Added a check that says, if we’re not initialized, and a message is not asking for capabilities or a notification from the client that says "notifications/initialized", then we send a message back indicating this is not an okay message type.
  • After initialization, we’re okay to accept messages such as listing tools, upon which we respond with our tools in that case.

See a running example of this code in the solution folder. Check Initialization (https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md).

Now that we have code that’s looking more robust, let’s support features such as tools, resources, and prompts.

You’ve already seen how connect is a method we call to handshake with the server. Thereafter, we want to call a tool, a resource, and a prompt, and wait for it to respond before carrying on with the next action. So, for that behavior to be possible, we need to do the following:

  1. Place the message on the stream.
  2. Wait for the response to arrive.
  3. If we get a normal response back, show it, if it’s a notification, then ignore it. Notifications from the server are usually a special message or a progress update, and we’ll implement support for that in the next section.

Great, we have a plan. Let’s revisit our main method to see what we have.

Now, we need to think about what to do with the response from a list_tools() call, like we have in the following code:

def main():
connect()
list_tools()
close_server()
main()

Ideally, we want to capture the response and do something with that response, such as storing these tools in case we want to call them later via, for example, call_tool (a method that we don’t have yet but plan to create).

So, we want the following code to be possible to write:

def main():
connect()
tools = list_tools()
call_tool(tools[0], args) # should specify args to call_tool
close_server()
main()

At this point, we need to capture the response from list_tools, and we need to print it. To make that happen, we need to ensure that both the server and the client are changed. The client needs to store the response in a tools variable, and the server needs to recognize that a list tools command is being sent and respond with the appropriate JSON-RPC message.

Let’s look at the server first. Here, we need to add a new case, tools/list, listing all tools:

server.py
# code omitted for brevity
case "tools/list":
response = {
"jsonrpc": "2.0",
"id": json_message["id"],
"result": {
"tools": [
{
"name": "example_tool",
"description": "An example tool that does something.",
"inputSchema": {
"type": "object",
"properties": {
"arg1": {
"type": "string",
"description": "An example argument."
}
},
"required": ["arg1"]
}
}
]
}
}
print(json.dumps(response))
sys.stdout.flush()
break

What’s worth calling out in the preceding code is the following:

  • The tools property: This should point to a list of tools.
  • inputSchema: This schema should describe the parameters this tool accepts and whether they’re mandatory to send. For this specific tool, it’s called example_tool and it has one parameter, arg1, which is required.

Now that we have the server side done, let’s focus on the client next. First, let’s define the list_tools method:

client.py
def list_tools():
# 3. send a message to list tools
# send a JSON-RPC message
send_message(serialize_message(list_tools_message))
response = proc.stdout.readline()
return json.loads(response)['result']['tools']

Next, let’s use list_tools from the main method:

client.py
tools = []
def main():
connect()
tool_response = list_tools()
tools.extend(tool_response)
print("Tools available:", tools)

In the main method, we call list_tools, save the tool_response response, and add it to a tools list that we will use later when we try calling one of the tools on the server.

We also need to support how to call a tool. Like before, let’s add the server part first:

server.py
case "tools/call":
tool_name = json_message['params']['name']
args = json_message['params']['args']
# todo create a response for the tool call, i.e call the right tool
response = {
"jsonrpc": "2.0",
"id": json_message["id"],
"result": {
"properties": {
"content": {
"description": "description of the content",
"items": [
{ "type": "text", "text": f"Called tool
{tool_name} with arguments {args}" }
]
}
}
}
}
print(json.dumps(response))
sys.stdout.flush()
break

In the preceding code, we’ve done the following:

  • Constructed a message in a JSON-RPC message.
  • Added result with the properties attribute, which itself has an attribute, content. Said property has an items array that contains a number of text blocks describing the outcome of calling the tool. In a more real implementation, the tool in question should be called, and its result should be listed here.

Let’s focus on the client part next. We need a call_tool method:

# omitting code for brevity
def call_tool(tool_name, args):
# 4. call a tool
# send a JSON-RPC message
tool_message = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": tool_name,
"args": args
},
"id": 1
}
send_message(serialize_message(tool_message))
response = proc.stdout.readline()
return
json.loads(response)["result"]["properties"]["content"]["items"]

Here, we do the following:

  • Construct a JSON-RPC message, and we pass in tool_name and args as part of the message.
  • Handle the response by loading it as JSON and dive into the response to fetch out items, which contains the relevant part of the response.

In the main method, we need to add the following code:

def main():
connect()
tool_response = list_tools()
tools.extend(tool_response)
print("Tools available:", tools)
tool = tools[0]
tool_call_response = call_tool(tool["name"],{"args1": "hello"})
for content in tool_call_response:
print_response(content['text'], prefix='[SERVER] tool response: \n')
# print_response(tool_call_response['result'], prefix='[SERVER]: \n')
# call tool, we need a name and arguments
close_server()

In the preceding code, we’ve done the following:

  • Called call_tool with the name of the tool, and we also passed arguments. We hardcoded the arguments.
  • Iterated over the response to get the text block response we defined on the server.

With all these parts in place, running the program should now also list this as part of the output:

[CLIENT]: {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "example_tool",
"args": {
"arg1": {
"type": "string",
"description": "An example argument."
}
}
},
"id": 1
}
[SERVER] tool response:
Called tool example_tool with arguments {'args1': 'hello'}

Great, now we have the features we need to both list the tools on the server and call a tool. It should be said, though, that calling a tool should also perform a computation. At present, we just list what tool was called and with what argument, so it’s a good start, but we should improve this further.

Let’s move on to notifications next. Notifications can be sent in both directions, from server to client as well as from client to server.

See a running example of this code in the solution folder – check Features (https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md).

Notifications, report progress, and important updates

Section titled “Notifications, report progress, and important updates”

Notifications are something both the client and the server can send to each other. Usually, they want to tell each party something important happened – for example, a long-running tool response might report progress, or a server may send a message to report on a change in its capabilities. So, how can we support notifications? Well, there are two aspects of it:

  • Sending a notification-type message from either client or server. This looks like so:
    {
    "jsonrpc": "2.0",
    "method": "notifications/[type]",
    "params": {}
    }

[type] is usually cancelled or progress. For a full specification of types, check https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-03-26/schema.ts.

  • The role of the notification. For a client, a notification is seen as an extra thing, and something you should show, for example, in a user interface to improve the user’s experience. A notification from a client to a server, though, tends to be different. For example, a client sends a notification to the server to set the state to "initialized".

How can we implement this, then? Well, we mostly have it in place already. We’re going to add the following to our code, though:

  • Dispatch a notification from the server to, in this case, report progress while waiting for the result of calling a tool
  • Add logic to our list_tools and call_tool functions to support handling an arriving notification.

First, let’s see how we can support notifications on the client:

client.py
# code omitted for brevity
def list_tools():
# 3. send a message to list tools
# send a JSON-RPC message
send_message(serialize_message(list_tools_message))
has_result = False
while not has_result:
response = proc.stdout.readline()
# check if message has result attribute, if so break out of loop
parsed_response = json.loads(response)
if 'result' in parsed_response:
has_result = True
return parsed_response['result']['tools']
else:
# this is a notification, we can print it
print_response(response, prefix='[SERVER] notification: \n')

Here, we have rewritten list_tools and added a loop to it. As long as what we receive is not the final result, we print it out (as it’s a notification). Then, once we get the final result – that is, it contains a result property – we return it from the function.

How can we deal with this on the server side? There are a few things we need:

  • A notification message needs to be created. We can place that in our utils folder and messages.py.
    utils/messages.py
    progress_notification = {
    "jsonrpc": "2.0",
    "method": "notifications/progress",
    "params": {
    "message": "Working on it..."
    }
    };
  • We need to dispatch the actual notification from where we want it to happen. For the sake of showing how it works, let’s add it to the tools/list case like so:
    server.py
    # code omitted for brevity
    case "tools/list":
    # send notification about progress first, then later the
    #response
    print(json.dumps(progress_notification))
    sys.stdout.flush()

It should be said that progress notifications, in particular, should be used when calling tools, rather than listing what tools you have, as calling a tool might be a lengthy operation in some cases, so let’s add that next. First, let’s redo call_tool in the same way as list_tools on the client:

client.py
# code omitted for brevity
def call_tool(tool_name, args):
# 4. call a tool
# send a JSON-RPC message
tool_message = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": tool_name,
"args": args
},
"id": 1
}
has_result = False
send_message(serialize_message(tool_message))
while not has_result:
response = proc.stdout.readline()
parsed_response = json.loads(response)
if 'result' in parsed_response:
has_result = True
return
parsed_response["result"]["properties"]
["content"]["items"]
else:
# this is a notification, we can print it
print_response(response, prefix='[SERVER]
notification: \n')

Just like with list_tools, we add a loop that just prints notifications unless the final result shows up. There’s definitely some duplication of code here, so we might want to break that out into a utility function at some point. Let’s see what we need to add on the server:

server.py
# code omitted for brevity
case "tools/call":
tool_name = json_message['params']['name']
args = json_message['params']['args']
print(json.dumps(progress_notification))
sys.stdout.flush()
print(json.dumps(progress_notification))
sys.stdout.flush()

Okay, so now we’ve added code that sends two notifications to the case that takes care of incoming messages of type tools/call.

When we try to run it all again, we should now see the following at the end of the output:

[SERVER] notification:
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"message": "Working on it..."
}
}
[SERVER] notification:
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"message": "Working on it..."
}
}
[SERVER] tool response:
Called tool example_tool with arguments {'args1': 'hello'}

Clearly, the two notifications arrive before the tool calling response.

It should be said, from a performance standpoint, that where we treat this as an SDK implementation, we would probably change and add the asyncio library to ensure we’re non-blocking. For the sake of demonstrating how messages flow back and forth, it serves its purpose, but it could be improved a bit.

Great – we’ve managed to implement notifications and did some nice refactoring. Let’s look at sampling next.

See a running example of this code in the solution folder – check Notifications (https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md).

Sampling – help the server complete a request

Section titled “Sampling – help the server complete a request”

Sampling is an interesting feature. What it means is that the server is telling the client, I don’t know how to do this, or You do it better – can you please help me complete this request?. More specifically, the server asks the client to complete the request using the client’s large language model (LLM).

Okay, so we established that the server sometimes needs the client to help it complete a request. The way the client helps is by asking its LLM for the response, which it then passes back to the server.

What is the starting point, though? Well, it could be a client that calls a tool on the server, and then the tool generates a sampling request. Then the flow could look like so:

Figure 2.2 – Sampling flow, scenario 1

Figure 2.2 – Sampling flow, scenario 1

Or, it could be an external service that generates an event that the server listens to. Here’s the flow for that scenario:

Figure 2.3 – Sampling flow, scenario 2

Figure 2.3 – Sampling flow, scenario 2

From a message standpoint, here’s what the server is sending to the client:

{
messages: [
{
role: "user" | "assistant",
content: {
type: "text" | "image",
// For text:
text?: string,
// For images:
data?: string, // base64 encoded
mimeType?: string
}
}
],
modelPreferences?: {
hints?: [{
name?: string // Suggested model name/family
}],
costPriority?: number, // 0-1, importance of minimizing cost
speedPriority?: number, // 0-1, importance of low latency
intelligencePriority?: number // 0-1, importance of capabilities
},
systemPrompt?: string,
includeContext?: "none" | "thisServer" | "allServers",
temperature?: number,
maxTokens: number,
stopSequences?: string[],
metadata?: Record<string, unknown>
}

Here’s some of the information included in the preceding request:

  • messages is a chat conversation between an assistant and a user, and provides the required context for the request
  • modelPreferences: Here, the server can specify things such as the preferred model name and decide the prioritization of cost, speed, and capabilities

There’s also model configuration data being sent on temperature, the number of tokens to use, and more. It’s worth calling out that these are recommendations that the client can choose to accept or modify.

The client should then respond with a completion message, like so:

{
model: string, // Name of the model used
stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
role: "user" | "assistant",
content: {
type: "text" | "image",
text?: string,
data?: string,
mimeType?: string
}
}

In the preceding response, the following information is covered:

  • model is the model used. It doesn’t have to be the same as what the server asked for.
  • stopReason – it’s good to know whether you got a full response or whether it stopped for some other reason.
  • content is the content response.

When does this happen, though? Well, the server could be listening to events that it should react to. For example, let’s say you have an e-commerce scenario and there are new products being registered by a system somewhere. However, before these products can be sold, they need a proper description. This description is something a client and its LLM can help with.

Figure 2.4 – E-commerce scenario flow

Figure 2.4 – E-commerce scenario flow

In the final step, the server logs, stores, and possibly caches the response.

Let’s look at a request in this context. Here’s an example request from a server:

{
"method": "sampling/createMessage",
"params": {
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Create a selling product description for this sweater,
keywords autumn, cozy, knitted"
}
}
],
"systemPrompt": "You are a helpful assistant assisting with
product descriptions",
"includeContext": "thisServer",
"maxTokens": 300
}
}

As you can see, we settled on only providing it with context and omitted any recommendations on the model to use or configuration, but we could add that if we wanted.

It’s now up to the client how to interpret this request and respond.

Let’s implement sampling in our code, and we’ll use the product description scenario so you can see how it can be used. Here’s what we need:

  • External service: This service should produce a new product in need of a product description. This product has been registered by someone else in another system and shows up in this server as a message payload as a result of listening to an event. This is scenario-specific code.
  • Server – sample request: We just need the capability to send a json-rpc request.
  • Client response: We need to listen to this specific message type, call the LLM using the message’s payload, and return a response to the server.

Let’s start with the external service. This isn’t really part of MCP, but it will hopefully give you a sense of how you can integrate an external component that produces a message that you’re interested in:

Here, we are adding the external service that will end up registering new products. It will produce new products at random intervals and send them to any listener.

server.py
# code omitted for brevity
class ProductStore:
def __init__(self):
self.started = False
self.listeners = {}
# create timer that adds a product to the queue every 5 seconds
def add_product(self):
"""Add a product to the store and notify listeners."""
product = {
"id": str(random.randint(10000, 99999)),
"name": f"Product {random.randint(1, 100)}",
"price": round(random.uniform(10.0, 100.0), 2),
"keywords": [f"keyword{random.randint(1, 5)}" for _ in
range(random.randint(1, 3))]
}
self.dispatch_message("new_product", product)
def start_product_queue_timer(self):
"""Start a timer that adds a product to the queue
every 5 seconds."""
def schedule_next():
delay = random.uniform(1, 2)
self.product_timer = threading.Timer(delay, self.add_product)
self.product_timer.start()
def add_twice():
schedule_next()
schedule_next()
add_twice()
def add_listener(self, message, callback):
if not self.started:
self.started = True
self.start_product_queue_timer()
"""Add a listener for product updates."""
# In a real application, this would register the callback
#to be called when a new product is added
callbacks = self.listeners.get(message, [])
callbacks.append(callback)
self.listeners[message] = callbacks
def dispatch_message(self, message, payload):
"""Dispatch a message to all registered listeners."""
callbacks = self.listeners.get(message, [])
for callback in callbacks:
callback(payload)

First, we create a class capable of creating and dispatching products that we want the client’s help with. In the previously mentioned scenario, we needed the client and its LLM to produce a description for us.

Here’s what the product store code consists of:

  • A ProductStore class: This store should emulate an external source that raises events that, at any point, can send new products that need their product descriptions augmented. See the store as a queue that could, for example, be long-polling an API or listening to a message queue. The point is it’s just a placeholder and only you know what this construct is as it’s solution-specific.
  • Several helper methods, such as add_listener, dispatch_message, and start_product_queue_timer: The latter is responsible for starting a timer for dispatching the products at a certain time interval.

Now we will interact with the product store by first creating it and then adding a listener to it. The listener should dispatch a message to the client whenever a new product is added.

def create_sampling_message(product):
sampling_message = {
"jsonrpc": "2.0",
"id": 1,
"method": "sampling/createMessage",
"params": {
"messages": [{
"role": "system",
"content": {
"type": "text",
"text": f"New product available:
{product['name']} (ID: {product['id']},
Price: {product['price']}). Keywords:
{', '.join(product['keywords'])}"
}
}],
"systemPrompt": "You are a helpful assistant assisting
with product descriptions",
"includeContext": "thisServer",
"maxTokens": 300
}
}
return sampling_message
store = ProductStore()
store.add_listener("new_product", lambda product:
print(json.dumps(create_sampling_message(product))))

We also need a way on the server to receive a sampling response from the client. Let’s see how we can handle that next. The main problem we have with the client is that we’re not really set up to handle a message that can arrive at any time. What we have right now is that we explicitly send calls from the client to the server and expect a response that we handle. To address this, we need to change our architecture slightly to use a background thread. That works in the following way:

  1. The thread listens to messages on stdout.
  2. If a message arrives (sent from the server), then it will be put in a queue for later processing.
  3. For sample messages, we will not put those in a queue but handle them directly, and for notifications and normal responses, we will have them in a queue and let them be handled in their respective method (e.g., list_tools, call_tool, etc.).

Let’s show how we set up the thread next:

client.py
def listen_to_stdout():
"""Listen to the stdout of the child process and handle messages."""
while True:
response = proc.stdout.readline()
if not response:
break # Exit if no more output
try:
parsed_response = json.loads(response)
if is_sampling_message(parsed_response):
handle_sampling_message(parsed_response)
# consume message if it is a sampling message
else:
# put message in the queue for further processing
message_queue.put(response.strip())
except json.JSONDecodeError:
# If the response is not JSON, just print it
print("[THREAD] Non-JSON response received:",
response.strip())
# print_response(response, prefix='[THREAD]: \n')
# create thread and start it
listener_thread = threading.Thread(target=listen_to_stdout, daemon=True)
listener_thread.start()

The preceding code does the following:

  • Reads from stdout.
  • Checks to see whether there’s a sampling message. If so, it tries to handle it by calling handle_sampling_message. If it’s not a sampling message, then it’s put in the queue.

Here are some helper methods that we also need:

def is_sampling_message(message):
"""Check if a message is a sampling message."""
return message.get('method', '').startswith('sampling')
def create_sampling_message(llm_response):
"""Create a sampling message for a product."""
sampling_message = {
"jsonrpc": "2.0",
"result": {
"content": {
"text": llm_response
}
}
}
return sampling_message
def call_llm(message):
return "LLM: " + message
def handle_sampling_message(message):
"""Handle a sampling message."""
print("[CLIENT] Calling LLM to complete request", message)
# get content info from message, send that to LLM
content = message['params']['messages'][0]['content']['text']
llm_response = call_llm(content)
message = create_sampling_message(llm_response)
send_message(serialize_message(message))
# should call LLM to complete request

Especially of interest is handle_sampling_message, which takes the message from the server and calls call_llm (we stubbed out this method; you should ensure in a real implementation that it calls an actual LLM). Then the response is constructed and sent back to the server for caching, logging, or whatever else the server needs to do with it.

Because we now rely on this queue for messages, we need to alter list_tools and call_tool to read from this queue instead of reading from the stream, like so:

while not has_result:
# response = proc.stdout.readline()
response = message_queue.get()

Here, we have commented how we used to ask for the latest message, calling readline, and we now instead call message_queue.get.

That’s it – that’s how sampling works. It originates in the server as the result of an event, and then it asks the client for help, and the client responds. It should be emphasized that the client doesn’t have to do exactly what the server wants it to do – that is, use a specific mode or configuration. You should present the server request in front of an equal user so they have a chance to respond and configure what the client sends back – that is, human in the loop.

See a running example of this code in the solution folder – check Sampling (https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md).

At this point, we’ve gone through large parts of the MCP. So, what’s the difference between SSE and STDIO? The main difference is how messages flow. In STDIO, messages are passed on your local machine between stdin and stdout streams; for SSE, messages flow over the web using HTTP. That means all the major motions, such as handshake, initialization, tool calling, and so on, need to be rethought as web requests from the client and web requests to the server.

Conceptually, SSE transport is implemented as a web server with the /messages and /sse routes. The former handles incoming MCP messages, while the latter is used to establish a connection for streaming events.

Here’s what that looks like from a high level:

Figure 2.5 – SSE transport flow

Figure 2.5 – SSE transport flow

We will cover SSE in more detail in Chapter 4, but now we have a good understanding at a mile-high level of what the difference is compared to STDIO.

Streamable HTTP is just like SSE in the sense that MCP servers using Streamable HTTP can be reached via a URL on the web. There are some differences and similarities. Let’s make that a bit clearer:

  • Both SSE and Streamable HTTP need the client to accept text/event-stream. For Streamable HTTP, the client also needs to accept application/json, as the server can choose whether to stream responses or send them as JSON. For SSE, the server always sends content as text/event-stream.
  • SSE connections are usually long-lived GET requests, where Streamable HTTP is typically POST.

From an implementation standpoint, it’s very similar to that of SSE – that is, it’s implemented as a web server. However, for Streamable HTTP, in the context of MCP, you should set up a route, /mcp, that handles both connections and messages, and it should also be set up as POST.

Figure 2.6 – Streamable HTTP flow

Figure 2.6 – Streamable HTTP flow

Therefore, implementing Streamable HTTP is a bit easier than SSE as you only need to keep track of one endpoint, /mcp. There’s more on Streamable HTTP in Chapter 5.

In this chapter, we covered quite a bit of information. The most important takeaway is that client and server communication needs to be initialized before further action can take place. Fortunately, most SDKs take care of the initialization part, and you can usually start the client-server communication by calling and listing tools and more. Hopefully, this was a good read for both those who find diagrams clarifying and those who like to see how code looks. The code works, but could surely be improved for performance, maintainability, and more. Do give the code a try – check the solutions folder.

In the next chapter, we will learn how to build and test our first server. The chapter will serve as a good introduction to getting hands-on with MCP.

Try running the code provided in https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md to see how things work. The code should do the following:

  • Initialize a connection
  • Send an initialized notification
  • List tools
  • Call a tool and produce notifications
  • Produce sample messages

The code is built up in steps, so it’s worth going through all the subfolders for your chosen runtime.

You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/README.md.

What needs to happen before a handshake between a server and a client can be considered complete?

  • A: The client needs to first send initialize, wait for the server response, and then send initialized.
  • B: The client and server can call, for example, list tools right away.
  • C: The client needs to send initialized to the server.

You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter02/Solutions/solution-quiz.md.