Building an MCP Client - Part 1: Mechanism

6 months ago

Building a basic MCP client is not difficult, but first, to do anything, we need to understand how it works. The MCP client needs to have a well-coordinated mechanism with the MCP server, and that is the specification of MCP.

The communication process between the client and the server generally proceeds as follows. Here, I will omit components such as authentication, discovering the list of prompts, resources... provided by the server. Instead, I will focus on a basic main flow from entering a command request to execution and then receiving the result.

MCP Client Workflow Diagram

Step 1: The client initializes connections to the large language model (e.g., using the openai library) and the MCP server.

Step 2: The client self-discovers the tools list from the MCP server.

Step 3: The user inputs a request, the client processes the request, and sends all data to the large language model.

Step 4: The model responds with results along with a suitable tool for the request. There may or may not be a suitable tool. If not, the process ends with a response indicating no match was found. If there is, proceed to Step 5.

Step 5: The client calls the MCP tools from the server and receives the results.

Step 6: The client receives the results from the server, continues processing, and provides the final response to the user.

At this point, some of you may realize that these steps seem familiar. Exactly! They are quite similar to Function calling in some LLM providers like OpenAI. Function calling requires a list of functions for LLMs to identify the appropriate function to call and retrieve the result. The MCP client is similar, with the main difference being that one calls functions within the server while the other calls functions to the server.

In the MCP SDK, basic APIs such as retrieving the list of prompts, resources, and functions to call the server are already provided. Our remaining task is simply to combine them together to create a client as desired. In the next article, we will write a basic MCP client for use in the command line.