Implementing sampling
Now, we’ve come to the extra exciting part of this chapter, namely, how to implement sampling.
We’ll cover the following parts of the implementation:
- Server side: How to add this to the MCP server
- Client side: How to enable it and what the code looks like, both to receive a request and send a response
Server implementation
To implement sampling on the server side, we need to consider when the sampling request should take place. Usually, a sampling request doesn’t happen out of nowhere, but it happens in the context of an action. Imagine the following scenario. A user working in the back office of an e-commerce site adds new products for sale. They need help with the description, and it should be as compelling as possible. For the description, they will therefore use the help of a client and its LLM. Here’s how it will play out:
- The user’s client calls a tool on the server that asks...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                