Start learning free

LESSON 53 OF 129 · AI ENGINEERING: MCP

Use an MCP Server from Your Assistant in Python

Practice

An MCP server is half of the story. The other half is the client: a program that connects to the server, asks which tools it has, and asks it to run them. In this lesson your assistant becomes an MCP client. It has no tools of its own: they live in the shop's MCP server, the ready-made file shop_mcp_server.py.

Talking to another program means waiting for its answers. Python marks code that waits with async, and every request to the server has await in front: "wait here until the answer arrives". For example, this is how a client of some other server reads a resource:

async def main():
    async with Client(docs_server) as docs:
        page = await docs.read_resource("help://units")
        print(page.contents[0].text)

asyncio.run(main())

The async with block starts the server program, keeps the connection open while the block runs, and stops the server at the end.

Your assistant does three jobs. It turns the server's list of tools into the dictionaries the model needs ("name", "description", "input_schema"). When the model asks for a tool, it passes the request to the server, which runs it. Then it sends the server's answer back to the model as a tool result, with is_error, the server's own mark for a call that failed.

The customer asks "Where is my order 40? My email is chloe@example.com." Your program and the check must print:

Tool: lookup_order {'order_id': 40}
Tool: find_orders {'email': 'chloe@example.com'}
Answer: I couldn't find an order with the number 40. Your email has two orders: order 7 from 2026-05-30 (paid) and order 4 from 2026-04-18 (shipped). Did you mean order 4?
Model calls: 3
Tools sent to the model: lookup_order, find_orders
Every tool has a description and an input schema: yes
Tool result 1 (is_error True): Error executing tool lookup_order: Order not found
Tool result 2 (is_error False): orders 7, 4

Your task: the tool loop is already written. Inside main, connect to the server with Client, ask it for its tools and turn each one into a dictionary for the model. In the loop, let the server run the tool the model asks for, join the texts of the result's items, and append the tool result with its is_error mark.


Assignment
Follow the Coding Tutorial to connect your assistant to the shop's MCP server and let the server run the model's tools.


Hint
Every request to the server (list_tools, call_tool) needs await in front. result.content is a list, even when it holds one item, so collect the texts with a loop.


STEP 1 OF 8
    Ctrl + Enter to check

    Ai Mcp Client in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free