Skip to content

Commit 2fd86b1

Browse files
committed
update connecting lesson
1 parent dd6aad1 commit 2fd86b1

File tree

1 file changed

+14
-2
lines changed
  • asciidoc/courses/genai-mcp-build-custom-tools-python/modules/2-database-features/lessons/1-connecting-neo4j

1 file changed

+14
-2
lines changed

asciidoc/courses/genai-mcp-build-custom-tools-python/modules/2-database-features/lessons/1-connecting-neo4j/lesson.adoc

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,14 @@ FastMCP provides a **lifespan** feature that allows you to:
4646

4747
=== The Lifespan Context Manager
4848

49-
A lifespan function is an async context manager that yields a context object containing your initialized resources:
49+
To share objects across the server, we can create a function that initializes resources when the server starts and cleans them up when it shuts down.
50+
51+
The function yields an object that contains the FastMCP server will make available to any tools and resources that request it.
52+
53+
Let's take a look at a full example:
5054

5155
[source,python]
56+
.Full lifespan example
5257
----
5358
import os
5459
from collections.abc import AsyncIterator
@@ -138,6 +143,7 @@ For your MCP server, you will need to define a context class that holds the Neo4
138143
==== 2. Create the Lifespan Context Manager
139144

140145
[source,python]
146+
.Context manager function
141147
----
142148
@asynccontextmanager
143149
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
@@ -150,13 +156,16 @@ Code before `yield` runs at **server startup**, code in `finally` runs at **serv
150156
==== 3. Use Environment Variables
151157

152158
[source,python]
159+
.Accessing environment variables
153160
----
154161
uri = os.getenv("NEO4J_URI", "bolt://localhost:7687")
155162
username = os.getenv("NEO4J_USERNAME", "neo4j")
156163
password = os.getenv("NEO4J_PASSWORD", "password")
157164
database = os.getenv("NEO4J_DATABASE", "neo4j")
158165
----
159166

167+
The credentials needed to connect to the database are read from environment variables.
168+
160169
[WARNING]
161170
.Never hardcode credentials
162171
====
@@ -178,7 +187,10 @@ finally:
178187
await driver.close()
179188
----
180189

181-
The driver is created once at startup and closed at shutdown, ensuring proper resource management.
190+
The function establishes a connection to the database using Neo4j's `AsyncGraphDatabase` driver.
191+
The driver is combined with the database into the `AppContext` object, which is yielded to the application from the server.
192+
193+
When the application exits, the driver connection is closed, ensuring proper resource management.
182194

183195

184196
==== 5. Access Context in Tools

0 commit comments

Comments
 (0)