Advanced Servers
local graph
Chapter 6 — Advanced Servers
Section titled “Chapter 6 — Advanced Servers”In Chapter 3, you saw how you can build MCP servers. However, there’s another way to build these servers – namely, by using a more advanced approach. The reason for using this more advanced approach is that you want to be more in control.
In this chapter, you will learn how to do the following:
- Use context managers to manage the lifecycle of your server
- Improve the architecture of your server
- Understand low-level access to MCP servers
The chapter covers the following topics:
- Why this low-level approach?
- Context managers
- Context managers in MCP servers
- Low-level access
- Organizing your architecture
Why this low-level approach?
Section titled “Why this low-level approach?”At this point, you might be thinking, Why would I want to do that? The previous approach was so easy! Well, there are a few reasons why you might want to use this approach. You may want to do the following:
- Use context managers to manage the lifecycle of your server: Here, you can do things such as connecting to a database or other services that are connected to your server. By having more control over the lifecycle of your server, you can ensure that your server is properly initialized and cleaned up when it’s no longer needed.
- Improve the architecture of your server: Having more control over how the server is built allows for more freedom in how tools and resources are registered, but also how incoming requests are handled. This increased control allows you to organize your code in a way that is more maintainable and scalable. This chapter shows you how you can organize your code with both a low-level server and a normal MCP server. It’s possible to create a clean architecture in both cases. However, it could be argued that the low-level server approach is a bit cleaner, as you don’t have to pass the server instance around. You’ll see more about what’s meant by that last statement later in this chapter.
- The only way forward in some cases: There are cases when you deal with certain features where there simply is no other way forward than a low-level approach. This is true for using Chapter 9, on sampling, and Chapter 10, on elicitation.
Let’s dive into a more low-level approach, so you know what it looks like, so you can choose the approach that suits your project the best.
Context managers
Section titled “Context managers”So, what’s a context manager to begin with? A context manager is a construct that allows you to allocate and release resources precisely when you want to. The most common way to use a context manager is with the with statement, which ensures that resources are properly cleaned up after use, even if an error occurs. By using a context manager, your code becomes cleaner and more readable. Let’s look at a simple example:
with Database_connection() as conn: # Use the connection result = conn.execute("SELECT * FROM table") for row in result: print(row)Using contextlib to create context managers
Section titled “Using contextlib to create context managers”Another way to use context managers is to create a custom context manager using the contextlib (there’s a corresponding NPM library called contextlib) module. This allows you to create context managers without defining a class. Here’s an example:
import contextlib@contextlib.contextmanagerdef database_connection(): conn = connect_to_database() try: yield conn # This is where the resource is provided to the block finally: close_connection(conn) # Cleanup happens hereHere, you can see how the DatabaseConnection class is replaced with a database_connection() function that uses the contextlib.contextmanager decorator. The yield statement provides the resource to the block, and the code after the yield statement is executed when the block is exited, ensuring proper cleanup. Is this better than the previous example? Well, at least you type less code.
Implementing a context manager
Section titled “Implementing a context manager”If you’re interested in knowing how to implement a context manager, because you’re curious or because you don’t want yet another dependency, here’s how you can do that:
class DatabaseConnection: def __enter__(self): self.conn = self.connect_to_database() return self.conn def __exit__(self, exc_type, exc_value, traceback): self.close_connection(self.conn) def connect_to_database(self): # Logic to connect to the database pass def close_connection(self, conn): # Logic to close the database connection passIn the preceding, the DatabaseConnection class implements the context manager protocol by defining the __enter__ and __exit__ methods. The __enter__ method is called when the with block is entered, and it returns the resource (in this case, a database connection). The __exit__ method is called when the block is exited, and it handles any cleanup necessary, such as closing the connection. Let’s call it like so:
with DatabaseConnection() as conn: # Use the connection result = conn.execute("SELECT * FROM table") for row in result: print(row)Without a context manager, your code would look like so:
conn = DatabaseConnection().connect_to_database()try: # Use the connection result = conn.execute("SELECT * FROM table") for row in result: print(row)finally: DatabaseConnection().close_connection(conn)Imagine what would happen if you forgot to close the connection in the finally block? You might be a very disciplined programmer and always remember to close the connection, but in a larger code base, it’s easy to forget. Context managers help you avoid such pitfalls by ensuring that resources are always cleaned up properly.
Let’s look at how context managers are used in the context of MCP servers next.
Context managers in MCP servers
Section titled “Context managers in MCP servers”MCP allows you to control the lifecycle management of your resources. Let’s have a look at some code:
async def load_settings() -> dict: """Load settings from a configuration file.""" # Simulate loading settings return {"setting1": "value1", "setting2": "value2"}@asynccontextmanagerasync def server_lifespan(server: Server) -> AsyncIterator[dict]: """Manage server startup and shutdown lifecycle.""" # Initialize resources on startup db = await Database.connect() settings = await load_settings() try: yield {"db": db, "settings": settings} finally: # Clean up on shutdown await db.disconnect()Here, we’ve done several things:
- Defined an asynchronous context manager,
server_lifespan, that manages the lifecycle of the server - Initialized resources such as a database connection and settings when the server starts, cleaning them up when the server shuts down
- Exposed these resources to the server’s request context, allowing handlers to access them easily
Speaking of handlers, let’s see how you can access these resources in your server’s handlers in the following code:
# Pass lifespan to serverserver = Server("example-server", lifespan=server_lifespan)# Access lifespan context in handlers@server.call_tool()async def query_db(name: str, arguments: dict) -> list: ctx = server.request_context db = ctx.lifespan_context["db"] settings = ctx.lifespan_context["settings"] # TODO: Use the database connection and settings return await db.query(arguments["query"])In the preceding code, we’ve done the following:
- Defined a tool,
query_db, that accesses the resources initialized in theserver_lifespancontext manager. - Accessed the database connection and settings from the
lifespan_contextof the server’s request context using thedb = ctx.lifespan_context["db"]andsettings = ctx.lifespan_context["settings"]code.
Great – now we have an understanding of context management and why it exists. Let’s look more at low-level access in the next section.
Low-level access
Section titled “Low-level access”Let’s recap how we first build a server so we can easily compare it to how low-level access is different. Here’s how you build a simple MCP server with a high-level API:
from mcp.server.fastmcp import FastMCPmcp = FastMCP("Echo")@mcp.resource("echo://{message}")def echo_resource(message: str) -> str: """Echo a message as a resource""" return f"Resource echo: {message}"@mcp.tool()def echo_tool(message: str) -> str: """Echo a message as a tool""" return f"Tool echo: {message}"The FastMCP class is what you use to instantiate a server – in this case, an instance called mcp. Then we use @mcp to define resources, tools, and prompts.
This is a high-level way of building a server, but what if you want more control over how the server is built? Here’s how you can do that using low-level access.
Let’s look at how registering features is different. In the past, you would have been used to using decorators associated with specific tools or resources, and so on. What’s different in a low-level server is that you need to handle all requests yourself. Instead of handling one tool or resource at a time, you handle all requests related to tools, resources, and prompts in one place.
First, the import is different. See how we import from from mcp.server.lowlevel and Server:
from mcp.server.lowlevel import ServerThat’s followed by instantiating a server like so:
server = Server("low-level-server")Instead of using @mcp.tools() or @mcp.resource(), you register using handlers such as @server.list_tools() and @server.call_tool(). That’s a huge difference. The difference lies in that, instead of there being one decorator for every feature, in a low-level server, you respond to all tool requests, whether to call a tool or list tools, resources, or prompts. That means @server.list_tools() is responsible for listing all tools, and you need to implement that logic yourself, whereas a high-level server does that for you. Here’s an example of how @server.list_tools() can be implemented:
@server.list_tools()async def handle_list_tools() -> list[types.Tool]: tool_list = [] print(tools) for tool in tools.tools.values(): tool_list.append( types.Tool( name=tool["name"], description=tool["description"], inputSchema=tool["input_schema"], ) ) return tool_listIn the preceding code, we’ve done the following:
- Defined a handler,
handle_list_tools, that responds to thelist_toolsrequest. - Used the
@server.list_tools()decorator to register this handler with the server. - Iterated over
tools.tools.values()to collect all tools and return them in the required format – in this case, a list oftypes.Toolobjects. In this case,tools.toolsis a dictionary that contains all the tools registered with the server that we’ve created, so it looks something like this:{"tools": {"echo_tool": {"name": "echo_tool","description": "Echo a message as a tool","input_schema": {"type": "object", "properties":{"message": {"type": "string"}}}}}}
Isn’t this more work? Well, actually, let’s explore in the next section how this could be a great way to organize your code.
Organizing your architecture
Section titled “Organizing your architecture”A huge advantage of using a low-level server is that you can control the architecture of your server. You can organize your code in a way that makes sense for your project. For example, you can define all your tools in a folder called tools. Tools also don’t need to know about the server instance. Sounds promising, right? Let’s see how next.
You can organize your code well with a high-level server too, but it’s usually a bit messier as you need to pass the server instance around, as we said initially in this chapter.
Here’s how you have defined MCP server features so far in a high-level server:
from mcp.server.fastmcp import FastMCPmcp = FastMCP("Echo")@mcp.tool()def echo_tool(message: str) -> str: """Echo a message as a tool""" return f"Tool echo: {message}"@mcp.tool()def add_tool(a: int, b: int) -> int: """Add two numbers as a tool""" return a + b@mcp.tool()def subtract_tool(a: int, b: int) -> int: """Subtract two numbers as a tool""" return a - b@mcp.tool()def multiply_tool(a: int, b: int) -> int: """Multiply two numbers as a tool""" return a * b@mcp.tool()def divide_tool(a: int, b: int) -> float: """Divide two numbers as a tool""" if b == 0: raise ValueError("Cannot divide by zero") return a / bThere’s nothing wrong with defining a server and its features like the preceding. However, it might be tempting to keep your entry point file relatively empty (save for the server definition) and define all your features in that file. So, you might resort to having a project structure like this:
project/├── server.py├── tools.pyThen your server.py might look like so:
from mcp.server.fastmcp import FastMCPimport toolsmcp = FastMCP("Echo")tools.register_tools(mcp)# code for running the serverYour tools.py might look like so:
from mcp.server.fastmcp import FastMCPdef register_tools(mcp: FastMCP): @mcp.tool() def echo_tool(message: str) -> str: """Echo a message as a tool""" return f"Tool echo: {message}" @mcp.tool() def add_tool(a: int, b: int) -> int: """Add two numbers as a tool""" return a + b @mcp.tool() def subtract_tool(a: int, b: int) -> int: """Subtract two numbers as a tool""" return a - b @mcp.tool() def multiply_tool(a: int, b: int) -> int: """Multiply two numbers as a tool""" return a * b @mcp.tool() def divide_tool(a: int, b: int) -> float: """Divide two numbers as a tool""" if b == 0: raise ValueError("Cannot divide by zero") return a / bYou might even have dedicated files for each tool:
project/├── server.py├── tools/│ ├── echo.py│ ├── add.py│ ├── subtract.py│ ├── multiply.py│ └── divide.pySo yes, you can organize your code in a way that makes sense for your project. It’s hard to get away from having to pass the server instance. It should be said that the high-level server does provide a create_tool() function that allows you to create tools without you having to use the @mcp.tool() decorator. However, and this is the opinion of the author, it’s just easier to use the low-level server for this purpose. Let’s look at how you can do this in the next section.
Constructing a list tools response in a low-level server
Section titled “Constructing a list tools response in a low-level server”So, let’s see whether low-level access can help improve our architecture further. The goal is to have a server that can register tools, resources, and prompts in a way that is easy to maintain and extend.
So, we said the following so far about the low-level server:
- Instead of using
FastMCP, you use theServerclass frommcp.server.lowlevel - You can register features using handlers such as
@server.list_tools()and@server.call_tool()to handle listing all tools and handling all tool calls
Let’s study these handlers in more detail and how we can construct them, to see how we can leverage them:
@server.list_tools()async def handle_list_tools() -> list[types.Tool]: tool_list = [] tool_list.append( types.Tool( name=tool["name"], description=tool["description"], inputSchema=tool["input_schema"], ) ) return tool_listHere, we observe that the return type is a list of types.Tool objects. This is reflected in the code, where we append a types.Tool object to tool_list like so:
tool_list.append( types.Tool( name=tool["name"], description=tool["description"], inputSchema=tool["input_schema"], ))Organizing your code and creating tools and schemas
Section titled “Organizing your code and creating tools and schemas”Now that we know how to register tools, let’s see how we can organize the code a bit. The goal is to achieve the following:
- A file for each tool, so we can easily manage the code
- Register all the tools in one place
Sounds like a great goal, right? Who doesn’t want maintainability? Let’s create a folder structure like so:
server.pytools/├── __init__.py├── add.pyWhat we’re seeing here is that we have a server.py file that will be the entry point of our server, and a tools/ folder that contains all the tools. The tools/init.py file is used to register to collect all the tools, and server.py and @mcp.list_tools() will be used to register all the tools. Let’s look at __init__.py first:
from .add import tool_addtools = { tool_add["name"] : tool_add}That looks super simple – just a dictionary that imports the tool_add function from the add.py file and adds it to the tools dictionary. Now let’s look at the add.py file:
from .schema import AddInputModelasync def add_handler(args) -> float: try: # Validate input using Pydantic model input_model = AddInputModel(**args) except Exception as e: raise ValueError(f"Invalid input: {str(e)}") # TODO: add Pydantic, so we can create an AddInputModel and validate args """Handler function for the add tool.""" return float(input_model.a) + float(input_model.b)tool_add = { "name": "add", "description": "Adds two numbers", "input_schema": AddInputModel, "handler": add_handler}In the preceding code, we’ve done the following:
- Imported
AddInputModeland added that asinput_schema - Defined an
add_handlerfunction that takes the arguments and returns their sum - Created a
tool_adddictionary that contains the tool’s name, description, input schema, and handler function
As you can see, there are no imports to anything MCP, and it therefore looks pretty clean.
Finally, let’s look at the schema.py file:
from pydantic import BaseModelclass AddInputModel(BaseModel): a: float b: floatHere we’re using the Pydantic library to define input models. We can extend this file with new types as we add more tools to our solution.
Handling a tool being called
Section titled “Handling a tool being called”So far, you’ve seen how we’re able to take care of a call asking us to list all the tools. But there’s another case we need to handle, namely when a client is trying to call a tool. For that, we need to do the following with the incoming tool calling request:
- Identify which tool to call.
- Parse out the arguments and, in doing so, also validate them. This is where our Pydantic schemas will come in handy to help us with this.
Let’s start with the request on the server:
@server.call_tool()async def handle_call_tool( name: str, arguments: dict[str, str] | None) -> list[types.TextContent]: passNote how we need to refer to the @server.call_tool decorator and that the return type needs to be list[types.TextContext].
Next, let’s see if we can identify the correct tool:
if name not in tools.tools: raise ValueError(f"Unknown tool: {name}")
tool = tools.tools[name]Okay, let’s get ready to call a handler on the tool and construct a response to the calling client:
try: result = await tool["handler"](arguments)except Exception as e: raise ValueError(f"Error calling tool {name}: {str(e)}")return [ types.TextContent(type="text", text=str(result))]Note how we invoke the handler property on the tool object with arguments as a parameter. What does the handler look like on the tool, though, and how does it work?
from .schema import AddInputModelasync def add_handler(args) -> float: try: # Validate input using Pydantic model input_model = AddInputModel(**args) except Exception as e: raise ValueError(f"Invalid input: {str(e)}") print (f"Adding {args['a']} and {args['b']}") """Handler function for the add tool.""" return float(args['a']) + float(args['b'])Here, we use a try-catch to pass args into the AddInputModel class. It takes a dictionary, and by passing it as **args, we’re unpacking the dictionary into keyword arguments. If the input is invalid, ValueError is raised, with a message indicating what went wrong. This way, you can ensure that the input to your tool is always valid and meets the expected schema.
Great, we’ve now managed to handle both listing all tools and calling a specific tool while also ensuring some validation of input arguments takes place.
I’m sure you could improve this setup further, but this is a lot better than what we started with.
Summary
Section titled “Summary”In this chapter, you learned how to use the low-level server to create a more maintainable architecture for your MCP server. You saw how to register tools, handle requests, and validate input using schemas. This approach allows you to easily add new tools and manage existing ones, making your server more flexible and easier to maintain.
In our next chapter, we’ll cover how to build clients that can interact with our MCP servers.
Assignment
Section titled “Assignment”Let’s see if we can organize the e-commerce server that we created in Chapter 3. Here’s the code for reference. Create a tools directory – use Pydantic and a low-level API.
from mcp.server.fastmcp import FastMCPimport uuid# Create an MCP servermcp = FastMCP("Demo")class Customer: def __init__(self,id: int, name: str, email: str): self.id = id self.name = name self.email = emailclass Category: def __init__(self, name: str, description: str): self.id = uuid.uuid4() self.name = name self.description = descriptionclass Product: def __init__(self, name: str, price: float, description: str): self.name = name self.price = price self.description = descriptionclass CartItem: def __init__(self, cart_id: int, product_id: int, quantity: int): if cart_id != 0: self.cart_id = cart_id else: self.cart_id = uuid.uuid4() self.product_id = product_id self.quantity = quantityclass Cart: def __init__(self, cart_id: int, customer_id: int): if cart_id != 0: self.cart_id = cart_id else: self.cart_id = uuid.uuid4() self.customer_id = customer_idclass Order: def __init__(self, order_id: int, customer_id: int): if order_id != 0: self.order_id = order_id else: self.order_id = uuid.uuid4() self.customer_id = customer_idproducts = [ Product("Product 1", 10.0, "Description of Product 1"), Product("Product 2", 20.0, "Description of Product 2"), Product("Product 3", 30.0, "Description of Product 3")]orders = [ Order(1, 101), Order(0, 101), Order(0, 102)]carts = []customers = [ Customer(1, "Customer 1", "email")]categories = [ Category("Category 1", "Description of Category 1"), Category("Category 2", "Description of Category 2"), Category("Category 3", "Description of Category 3")]product_catalog = [ { "name": "Product 1", "price": 10.0, "description": "Description of Product 1", "category_id": 1 }, { "name": "Product 2", "price": 20.0, "description": "Description of Product 2", "category_id": 2 }, { "name": "Product 3", "price": 30.0, "description": "Description of Product 3", "category_id": 3 }]# get orders@mcp.tool()def get_orders(customer_id:int = 0) -> [Order]: """get all orders""" if customer_id != 0 and not any(customer.id == customer_id for customer in customers): raise ValueError(f"Invalid customer_id: {customer_id}") filtered_orders = orders if customer_id != 0: filtered_orders = [order for order in orders if order.customer_id == customer_id] return [{"type": "text", "name": f"ID: {order.order_id},customer: {order.customer_id}"} for order in filtered_orders]# get order by id@mcp.tool()def get_order(order_id:int) -> Order: """get order by id""" for order in orders: if order.order_id == order_id: return {"type": "text", "name": f"ID: {order.order_ id},customer: {order.customer_id}"} return None# place order@mcp.tool()def place_order(customer_id:int) -> Order: """place order""" if customer_id != 0 and not any(customer.id == customer_id for customer in customers): raise ValueError(f"Invalid customer_id: {customer_id}") new_order = Order(0, customer_id) orders.append(new_order) return {"type": "text", "name": f"ID: {new_order.order_id},customer: {new_order.customer_id}"}# get carts@mcp.tool()def get_cart(customer_id:int) -> [Cart]: """get a singular cart""" if customer_id != 0 and not any(customer.id == customer_id for customer in customers): raise ValueError(f"Invalid customer_id: {customer_id}") cart = next((cart for cart in carts if cart.customer_id == customer_ id), None) if cart: return {"type": "text", "name": f"ID: {cart.cart_id},customer: {cart.customer_id}"} else: return None
# get cart items@mcp.tool()def get_cart_items(cart_id:int) -> [CartItem]: """get cart items""" cart_items = [item for item in carts if item.cart_id == cart_id] return [{"type": "text", "name": f"ID: {item.cart_id},product: {item. product_id},quantity: {item.quantity}"} for item in cart_items]# add to cart@mcp.tool()def add_to_cart(cart_id:int, product_id:int, quantity:int) -> CartItem: """add to cart""" new_cart_item = CartItem(cart_id, product_id, quantity) carts.append(new_cart_item) return {"type": "text", "name": f"ID: {new_cart_item.cart_id},product: {new_cart_item.product_id},quantity: {new_cart_item.quantity}"}# tool, all products@mcp.tool()def get_all_products() -> [Product]: """Get all products""" return [{"type": "text", "name": f"ID: {product.name},price: {product. price},description: {product.description}"} for product in products]# tool, product by id@mcp.tool()def get_product(product_id: int) -> Product: """Get product by ID""" for product in products: if product.name == product_id: return {"type": "text", "name": f"ID: {product.name},price: {product.price},description: {product.description}"} return None# tool, all categories@mcp.tool()def get_all_categories() -> [Category]: """Get all categories""" return [{"type": "text", "name": f"ID: {category.name},description: {category.description}"} for category in categories]# tool, all customers@mcp.tool()def get_all_customers() -> [Customer]: """Get all customers""" return [{"type": "text", "name": f"ID: {customer.id},name: {customer. name},email: {customer.email}"} for customer in customers]Solution
Section titled “Solution”You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter06/solutions/README.md.
What are some benefits of using a low-level server?
- A: You use less memory
- B: You have better control over how requests are processed
- C: You can define your own transports
You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter06/solutions/solution-quiz.md.