1. Defining the Custom Server using FastMCP
To build MCP servers easily, the SDK provides a high-level framework called FastMCP. FastMCP handles the JSON-RPC message serialization and transport setup automatically under the hood.Step 1: Install FastMCP Dependency
Run in your terminal:Step 2: Write the Server Script (mcp_server.py)
We initialize a FastMCP instance and register tools using the @mcp.tool() decorator:
2. Consuming Custom Server Tools in an Agentic Client
Now, we build a client application that:- Spawns our
mcp_server.pyscript as a subprocess stdio transport connection. - Queries the server’s available tools.
- Binds those tools to a Chat Model so the LLM can invoke them.
Step 1: Initialize the Stdio Subprocess Param
We configure parameters to launch our server script:Step 2: Bind MCP Tools to ChatModel
We fetch the tool definitions from the server, format them for LangChain, and bind them:3. Client Implementation Script (mcp_client.py)
Here is the complete, self-contained client script that connects to our server subprocess, binds the exposed math tools to Gemini, and executes a calculation query:
4. Practice Exercises
Practice 1: Adding a Division Tool
Modify the custom server scriptmcp_server.py to add a new division tool called divide_numbers(a: float, b: float) -> float. Define its docstring indicating that it divides a by b, and returns the result.
Solution
Solution
Add the following decorator and function to the server script
mcp_server.py: