Skip to content
ImagineWorld

Building Clients

node_idnode-book_learn-model-context-protocol-with-python_chapter-07-building-clients
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleBuilding Clients
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

To consume an MCP server, you need some form of client. You could, for example, use an application such as Claude Desktop or Virtual Studio Code (VS Code), as they have the ability to consume MCP servers and will handle the discovery of features and be able to use them. There are also cases where you want your own written client. A good example of this situation is when you want to build in AI capabilities as part of your app. Imagine, for example, that you have an e-commerce app and want to have an AI-improved search. The MCP server would be a separate app, whereas the client would be built into the e-commerce app.

With this in mind, let’s explore how we can build a client and what goes into it.

In this chapter, you will learn how to do the following:

  • Build a client using both STDIO and SSE transports
  • Consume an MCP server and its features
  • Leverage an LLM to enhance your client experience

The chapter covers the following topics:

  • Building a client
  • Exercise: Building a client
  • Clients with LLMs
  • Working with an LLM
  • Exercise: Integrating the LLM

So, what goes into building a client? At a mile-high level, here’s what we need to do:

  1. Set up the client to connect to the server.
  2. List features.
  3. Select a feature to use.
  4. Prompt the user for parameters.
  5. Present the results.

Great, now that we understand the high-level steps, let’s see if we can build it next in an exercise that you’re welcome to code along with.

In this exercise, you will build a client that connects to the server and consumes its features. You will use the SDK to build the client and call the server. The client will be a simple command-line application that allows you to select a feature and provide its parameters. The client will then call the server and display the results.

Set up the client to connect to the server

Section titled “Set up the client to connect to the server”

Let’s first create the client code needed to establish a connection to the server:

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="mcp", # Executable
args=["run", "server.py"], # Optional command line arguments
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(
read, write
) as session:
# Initialize the connection
await session.initialize()
# list features
if __name__ == "__main__":
import asyncio
asyncio.run(run())

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

  • Created a StdioServerParameters object that specifies the command to run the server and any optional command-line arguments. Why we do this is because the server will be run at the same time as the client, so we need to specify how to run it.
  • Defined a run function that creates a ClientSession object and initializes the connection to the server. Inside the run function, we will soon add the code to list and call features.

So far, we’ve set up the client to connect to the server. Now, let’s add the code to list the features available on the server. This is done differently depending on the type of feature. Let’s add some code:

# List available resources
resources = await session.list_resources()
print("LISTING RESOURCES")
for resource in resources:
print("Resource: ", resource)
# List available tools
tools = await session.list_tools()
print("LISTING TOOLS")
for tool in tools.tools:
print("Tool: ", tool.name)

There, we have the following code to list the features:

  • List available resources: This lists all the resources available on the server. We also print the resource name to the console.
  • List available tools: This lists all the tools available in the server, and we print the tool name to the console. We could also print the tool description and input schema, but for now, we just print the name.

Let’s show how to use our listed features by taking one of the tools and calling it. In this case, we will use the add tool that we created in the previous chapter. The add tool takes two parameters, a and b, and returns the sum of the two numbers. However, imagine now the user has been presented with a list of tools and chosen a tool. Let’s now prompt the user for the parameters needed to call the tool:

# Read information from the first tool
tool_name = tools.tools[0].name
print(f"Using tool: {tool_name}")
first_value = input("Enter first value: ")
second_value = input("Enter second value: ")
# Call a tool
print("CALL TOOL")
result = await session.call_tool(tool_name, arguments={
"a": first_value, "b": second_value})
print(result.content)

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

  • Read the name of the first tool in the list and printed it to the console.
  • Prompted the user for the first and second value to use as parameters for the tool.
  • Called the tool using the call_tool method and passed the parameters as a dictionary. The result is printed to the console.

Great, now we have a client that can connect to the server, list the features, and call a tool. However, this is still quite programmatic and not very user-friendly.

Before we move on to integrate an LLM, let’s show the complete code for the client:

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="mcp", # Executable
args=["run", "server.py"], # Optional command line arguments
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(
read, write
) as session:
# Initialize the connection
await session.initialize()
# List available resources
resources = await session.list_resources()
print("LISTING RESOURCES")
for resource in resources:
print("Resource: ", resource)
# List available tools
tools = await session.list_tools()
print("LISTING TOOLS")
for tool in tools.tools:
print("Tool: ", tool.name)
# Read information from the first tool
tool_name = tools.tools[0].name
print(f"Using tool: {tool_name}")
first_value = input("Enter first value: ")
second_value = input("Enter second value: ")
# Call a tool
print("CALL TOOL")
result = await session.call_tool(tool_name, arguments={"a": first_value, "b": second_value})
print(result.content)
# Read a resource
print("READING RESOURCE")
content, mime_type = await session.read_resource("greeting:// hello")
if __name__ == "__main__":
import asyncio
asyncio.run(run())

Okay, if you typed along with the code, you should now have a working client that can connect to the server and consume its features. You will get an additional chance to practice this in the assignment at the end of this chapter.

Let’s improve the client next by integrating an LLM into it. You will get to see how this offers a better user experience and how it can be used to abstract away the complexity of using the server.

So far, you’ve seen how you can build and test a client using STDIO and SSE. However, you might have noticed how this approach is quite programmatic and not very user-friendly. That is, for each capability you want to use, you need to know the exact name of the feature and its parameters. This is where LLMs come in. By involving an LLM in the client, you can abstract away the knowing part and instead focus on the doing part. Here’s how it works.

Here’s how you would build an app without an LLM and how the flow in the app would be:

  1. List server features.
  2. The user selects a feature and the client asks for the parameters.
  3. Do something with the response.

This approach is quite rigid and requires the user to explicitly know and select one of the features listed. So, what’s better?

To address clients that feel rigid, imagine instead that the user doesn’t know about the features; they only communicate with prompts. With that thought in mind, now let’s look at the flow of the app:

  1. List server features.
  2. Convert the list of features into an LLM tool.
  3. The user types a natural language request.
  4. The client sends the request to the LLM, which figures out which feature to use and what parameters to send, and if there’s no matching feature, responds with a generic LLM response.

The difference in user experience is quite significant. This second approach means the user no longer needs to know about the features, and doesn’t need to select features to use. Instead, the user can just type a natural language request, and the LLM will figure out the rest.

Let’s see how this works in practice.

There are many AI providers out there that let you call an LLM. In this book, we will use GitHub Models, as that’s a free option, and all you need to use it is a GitHub account. To use GitHub Models, you will either need to start your project in GitHub Codespaces or set up a personal access token (PAT) with the right permissions. The reason you need a token in the first place is that you are calling an API, and the token is used as a bearer token to authenticate the request. To use a local AI model via, for example, Ollama, you wouldn’t need a token. You can type the token directly in the source code, but it’s recommended to keep it in an environment variable for security reasons.

So, what do we need to know if we’ve never worked with AI before? Well, the idea is to send in a prompt and get back a response. The prompt is natural language text that describes what you want the LLM to do. The response is also natural language text that contains the answer to your prompt.

To use LLM in combination with MCP, however, the idea is to have the LLM indicate which functions to call given a specific prompt. For example, with the prompt Add 1 and 2, the LLM should indicate that the add function should be called with the parameters a=1 and b=2, if we have defined an add function in the MCP server with that name and parameters.

Here’s what the calling code looks like. In the following code, we will be calling a GitHub model, so make sure you have a GitHub account and have created a PAT with the right permissions, or start it in GitHub Codespaces.

What’s important to define is the following:

  • The endpoint for GitHub Models
  • The model to use – in this case, gpt-4o
  • The prompt to send in – you can collect this data from a user input or hardcode it, as in the following example
  • The functions to use – in this case, we will be using the add tool that we created in the previous chapter

It’s entirely possible to just send a prompt and get a response back, but in this case, we want the LLM to indicate which function to call, so we will be sending in a function definition as well. A function definition is a JSON object that describes the function name, description, and parameters. The parameters are defined using JSON schema.

# json description of functions
functions = [
{
"type": "function",
"function": {
"name": "add",
"description": "Add two numbers",
"type": "function",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "number",
"description": "The first number to add"
},
"b": {
"type": "number",
"description": "The second number to add"
}
},
"required": ["a", "b"]
}
}
}
]
# get token from environment variable
token = os.environ["GITHUB_TOKEN"]
# the endpoint for GitHub Models
endpoint = "https://models.github.ai/inference"
# the model to use
model_name = "gpt-4o"
# creation of chat client
client = OpenAI(
base_url=endpoint,
api_key=token
)
print("CALLING LLM")
response = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": prompt,
},
],
model=model_name,
tools = functions,
# Optional parameters
temperature=1.,
max_tokens=1000,
top_p=1.
)
response_message = response.choices[0].message
print("LLM RESPONSE: ", response_message)

It’s worth mentioning though that, additionally to prompts, you can also send in configuration to the LLM, such as temperature, max_tokens, and top p. We won’t dive into what these parameters mean – you can read more about them in the OpenAI documentation – but in short, they control the randomness and creativity of the LLM response and also the size of what’s known as the context window.

So, let’s see how we can integrate an LLM into the client. The goal is to have a much better user experience and to abstract away the complexity of using the server. To get there, we will need to take the following steps:

  1. List server features: By listing the features, we can see what we have available to us
  2. Convert the list of features to an LLM tool: The features from the MCP server are not directly usable by the LLM, so we need to convert them into a format that the LLM can understand
  3. Manage user input: This will allow the user to type a natural language request and the LLM on our client will make a completion request, and in doing so, tell us which feature to use and what parameters to send.

Let’s do this!

You might be building this client as the first thing you do if you, for example, are consuming someone else’s MCP server. In that case, make sure you install the MCP SDK before proceeding.

The first step is no different from what we did before. We need to list the features available on the server. This is done by a call to listing tools, like so:

tools = await session.list_tools()
print("LISTING TOOLS")
for tool in tools.tools:
print("Tool: ", tool.name)

Convert the list of features into an LLM tool

Section titled “Convert the list of features into an LLM tool”

Our next step is important, as we’re going to convert the list of features into a format that the LLM can understand. This will set us up for the next step, where we will use the LLM to figure out which feature to use. Here’s the conversion code:

  1. Let’s add the conversion code function:
    def to_llm_tool(tool):
    tool_schema = {
    "type": "function",
    "function": {
    "name": tool.name,
    "description": tool.description,
    "type": "function",
    "parameters": {
    "type": "object",
    "properties": tool.inputSchema["properties"]
    }
    }
    }
    return tool_schema

The preceding code defines a function that takes a tool as input and converts it into a format that the LLM can understand.

  1. Let’s call the conversion code:
    functions = []
    for tool in tools.tools:
    print("Tool: ", tool.name)
    print("Tool", tool.inputSchema["properties"])
    functions.append(to_llm_tool(tool))

From the code, you can see that we loop through the tools’ response and call the conversion code for each tool.

Great, now we are well set up for using the LLM. The next step is to manage user input and send a completion request to the LLM. In the response from the LLM, the LLM will tell us which function to use and what parameters. In this case, the function to call will be a feature on the server.

The user types a natural language request and the LLM makes a completion request

Section titled “The user types a natural language request and the LLM makes a completion request”

Let’s look at how we can call the LLM now that we have tools for it to use.

There are two parts to this: the first part is to call the LLM, and the second part is to learn whether the LLM has returned a function call or a generic response.

  1. Make the LLM call:
    def call_llm(prompt, functions):
    token = os.environ["GITHUB_TOKEN"]
    endpoint = "https://models.github.ai/inference"
    model_name = "gpt-4o"
    client = OpenAI(
    base_url=endpoint,
    api_key=token,
    )
    print("CALLING LLM")
    response = client.complete(
    messages=[
    {
    "role": "system",
    "content": "You are a helpful assistant.",
    },
    {
    "role": "user",
    "content": prompt,
    },
    ],
    model=model_name,
    tools = functions,
    # Optional parameters
    temperature=1.,
    max_tokens=1000,
    top_p=1.
    )
    response_message = response.choices[0].message
    print("LLM RESPONSE: ", response_message)
    functions_to_call = []

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

  • Created a function that takes a prompt and the list of functions as input and returns the LLM response.
  • Called the LLM using the complete method and passed the prompt and functions as parameters. The response is printed to the console.
  1. Let’s check whether the LLM returned a function call by adding the following code:
    if response_message.tool_calls:
    for tool_call in response_message.tool_calls:
    print("TOOL: ", tool_call)
    name = tool_call.function.name
    args = json.loads(tool_call.function.arguments)
    functions_to_call.append({ "name": name, "args": args })
    return functions_to_call

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

  • Checked whether the LLM returned a function call by checking whether the tool_calls property is present in the response message
  • Looped through the tool_calls and printed the tool name and arguments to the console
  • Returned the list of functions to call

The client figures out which server feature to use and what parameters to send

Section titled “The client figures out which server feature to use and what parameters to send”

At this point, we have the LLM response, and it even returns which functions to call, if any. The next step is to check the functions to call and call the MCP server if needed:

functions_to_call = call_llm(prompt, functions)
# call suggested functions
for f in functions_to_call:
result = await session.call_tool(f["name"], arguments=f["args"])
print("TOOLS result: ", result.content)

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

  • Called the LLM and got the functions to call.
  • Looped through the functions to call and called the MCP server using the call_tool method. The result is printed to the console.

Nice, right? The user is surely thanking you now for making their life easier, as they can use natural language to interact with the server.

In this chapter, we’ve explored how to build clients that can connect to an MCP server and consume its features. We started by building a simple client that could list and call features on the server. We then improved the client by integrating an LLM, which allowed us to create a much better user experience by enabling natural language interactions with the server.

In the next chapter, we will explore how to consume an MCP server using VS Code and Claude for desktop.

For this assignment, you will once again focus on e-commerce. You will build an experience where the user can interact with an e-commerce server:

  • Ask for products of a certain category
  • Add products to the cart, all done using natural language

Here’s a solution for a client. It covers both clients with and without an LLM.

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

What can a client access on an MCP server?

  • A: Prompts, tools, and resources
  • B: Tools, prompts, and services
  • C: Tools and prompts

What’s the benefit of adding an LLM to your client?

  • A: It’s better to place the LLM on the server
  • B: It makes the client faster
  • C: An LLM on the client allows the end user to use prompts to interact with the server, which makes for a much better user experience

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

References