Context managers
Another thing you will see a lot when working with the MCP SDK is the use of context managers, so what are those? A context manager is a Python object that defines the runtime context to be established when executing a with statement. The most common use case is resource management, where you want to ensure that resources are properly acquired and released. For example, it’s a good idea to use it if you need to set up a resource such as a database connection or some other type of resource. Here’s a simple example:
with db_resource("sqlite.db") as conn:
    # Perform database operations
    pass
What makes us able to use the with keyword, you might ask. Well, context managers are able to use the with keyword because they implement two special methods: __enter__ and __exit__. When the with statement is executed, the __enter__ method is called, and when the block inside the with statement is exited, the __exit__ method is called. This...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                