Skip to main content

Activity: Creating a client

To create a client, we'll use a similar set up as with the server. At high level, here's what we need to do:

  • Create a new project by creating a new folder (or reuse the existing one).
  • Install the necessary dependencies.
  • Add a server.py and client.py file.
  • Write the client code to connect to the server and call the add tool.

-1- Create a new project

--| src
----| server.py
----| client.py

You can use the following for server.py:

# server.py
from mcp.server.fastmcp import FastMCP

# Create an MCP server
mcp = FastMCP("Demo")

# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b


# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"

-2- Install the necessary dependencies

We need to install the necessary dependencies for the client.

pip install "mcp[cli]"

-3- Write the client code

Now that we have the project set up, let's write the client code to connect to the server and call the add tool.

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()


if __name__ == "__main__":
import asyncio

asyncio.run(run())

In the preceding code we've:

  • Created a client instance that also initialized the client-server communication.
  • Started a server instance with mcp run server.py.

We're now ready to add features.

List tools and call the add tool

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 a resource
print("READING RESOURCE")
content, mime_type = await session.read_resource("greeting://hello")

# Call a tool
print("CALL TOOL")
result = await session.call_tool("add", arguments={"a": 1, "b": 7})
print(result.content)


if __name__ == "__main__":
import asyncio

asyncio.run(run())

Now we've added all the features we need so we can:

  • List resources and read resources.
  • List and call tools.

-4- Run the client

To run the client type the following command in the terminal (make sure you stand in the client directory):

python client.py

You should see the following output:

LISTING RESOURCES
Resource: ('meta', None)
Resource: ('nextCursor', None)
Resource: ('resources', [])
INFO Processing request of type ListToolsRequest server.py:625
LISTING TOOLS
Tool: add
READING RESOURCE
INFO Processing request of type ReadResourceRequest server.py:625
CALL TOOL
INFO Processing request of type CallToolRequest server.py:625
[TextContent(type='text', text='8', annotations=None, meta=None)]

In our next activity, let's learn how we can add a large language model (LLM) to our client. This will make it possible for the client to negotiate with the server. Why this is useflu is that you can now show an NLP, Natural Language Processing user interface to the user, and the user can interact using natural language prompts.

Summary

You've built a client capable of communicating with an MCP Server. The client can list tools and call the add tool. Either run this client from your project or clone the repository below to see a working solution:

git clone https://github.com/softchris/mcp-workshop.git
cd tutorial-mcp