Skip to content

Commit 7e95e4d

Browse files
committed
switch order of code in 2c-add-neo4j-connection
1 parent 2fd86b1 commit 7e95e4d

File tree

1 file changed

+40
-69
lines changed
  • asciidoc/courses/genai-mcp-build-custom-tools-python/modules/2-database-features/lessons/2c-add-neo4j-connection

1 file changed

+40
-69
lines changed

asciidoc/courses/genai-mcp-build-custom-tools-python/modules/2-database-features/lessons/2c-add-neo4j-connection/lesson.adoc

Lines changed: 40 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ First, create a new directory for your MCP server, and use the `uv add` command
2727
----
2828
mkdir server
2929
cd server
30-
uv add neo4j python-dotenv
30+
uv add mcp neo4j python-dotenv
3131
----
3232

3333

@@ -119,20 +119,14 @@ Then define a new `FastMCP` server instance with the name [copy]#Movies GraphRAG
119119
----
120120
# Create server with lifespan
121121
mcp = FastMCP("Movies GraphRAG Server", lifespan=app_lifespan)
122-
123-
if __name__ == "__main__":
124-
mcp.run()
125122
----
126123

127124

128125
== Step 4: Add a Graph Statistics Tool
129126

130-
Now that we have our lifespan management set up, let's create a tool to return the number of nodes and relationships in the graph.
131-
132-
133-
First, create a `graph_statistics` tool function, and pass the `Context` object as a parameter.
127+
Now that we have our lifespan management set up, let's create a tool to return the number of nodes and relationships in the graph.
134128

135-
Use `ctx.request_context.lifespan_context` to access the driver and database from the lifespan context.
129+
Create a `graph_statistics` tool function that uses `ctx.request_context.lifespan_context` to access the driver and database from the lifespan context, then executes a Cypher query to count nodes and relationships:
136130

137131
[source,python]
138132
.server/main.py
@@ -146,13 +140,7 @@ async def graph_statistics(ctx: Context) -> dict[str, int]:
146140
# Access the driver from lifespan context
147141
driver = ctx.request_context.lifespan_context.driver
148142
database = ctx.request_context.lifespan_context.database
149-
----
150-
151-
Next, use the driver to execute a Cypher query that counts nodes and relationships:
152-
153-
[source,python]
154-
.server/main.py
155-
----
143+
156144
# Use the driver to query Neo4j with the correct database
157145
records, summary, keys = await driver.execute_query(
158146
r"RETURN COUNT {()} AS nodes, COUNT {()-[]-()} AS relationships",
@@ -172,74 +160,57 @@ The `database_` parameter is used to specify the database to execute the query o
172160
Any named arguments that do not end with an underscore will be passed as parameters to the Cypher query.
173161
====
174162

175-
== Step 5: Configure VS Code and Test the Tool
176163

177-
Add the new server definition to your `.vscode/mcp.json` file to pass environment variables to the server:
164+
== Step 5: Add the Main Function
165+
166+
Finally, add the main function at the bottom of your `main.py` file to run the server:
178167

179-
[source,json,subs="attributes+"]
180-
..vscode/mcp.json
168+
[source,python]
169+
.server/main.py
181170
----
182-
{
183-
"servers": {
184-
"Movie Server": {
185-
"type": "stdio",
186-
"command": "uv",
187-
"args": [
188-
"--directory",
189-
"server",
190-
"run",
191-
"main.py"
192-
],
193-
"env": {
194-
"NEO4J_URI": "{instance-scheme}://{instance-ip}:{instance-boltPort}",
195-
"NEO4J_USERNAME": "{instance-username}",
196-
"NEO4J_PASSWORD": "{instance-password}",
197-
"NEO4J_DATABASE": "{instance-database}"
198-
}
199-
}
200-
}
201-
}
171+
if __name__ == "__main__":
172+
mcp.run(transport="streamable-http")
202173
----
203174

204-
// Alternatively, you can reference your `.env` file using environment variables:
205175

206-
// [source,json]
207-
// ..vscode/mcp.json (alternative)
208-
// ----
209-
// {
210-
// "servers": {
211-
// "Movie Server": {
212-
// "type": "stdio",
213-
// "command": "bash",
214-
// "args": [
215-
// "-c",
216-
// "cd server && source .env && uv run main.py"
217-
// ]
218-
// }
219-
// }
220-
// }
221-
// ----
176+
== Step 6: Run the Server and Test with Inspector
222177

178+
Now let's test your server with the MCP Inspector.
223179

224-
Test it with the MCP Inspector:
225180

226-
[source,bash]
181+
=== Start the Server
182+
183+
First, start your MCP server in a terminal:
184+
185+
[source,shell]
227186
----
228-
npx @modelcontextprotocol/inspector uv --directory $PWD/server run main.py
187+
cd server
188+
uv run main.py
229189
----
230190

231-
Run the `graph_statistics` tool. If it returns the node and relationship counts from your database, your lifespan management is working correctly!
191+
If the server starts successfully, you should see a URL displayed (e.g., `http://0.0.0.0:8000`). This confirms your server is running correctly.
192+
193+
194+
=== Start the Inspector
195+
196+
In a separate terminal, start the MCP Inspector:
197+
198+
[source,shell]
199+
----
200+
ALLOWED_ORIGINS=https://$CODESPACE_NAME-6274.app.github.dev,https://$CODESPACE_NAME-6277.app.github.dev DANGEROUSLY_OMIT_AUTH=true npx @modelcontextprotocol/inspector
201+
----
232202

203+
Once running:
233204

234-
== Verify Your Implementation
205+
1. Configure the Codespaces ports (6274, 6277, and 8000) to be **Public**
206+
2. Connect the Inspector using **Streamable HTTP** transport with the forwarded addresses
207+
3. Use the **Tools** tab to run the `graph_statistics` tool
208+
4. Verify it returns the node and relationship counts from your database
235209

236-
Once you've implemented the lifespan management:
210+
link:/courses/genai-mcp-build-custom-tools-python/1-getting-started/5c-test-with-inspector/[See full Inspector setup instructions^] if you need detailed steps.
237211

238-
1. The server should start without errors
239-
2. The `graph_statistics` tool should return node and relationship counts from your database
240-
3. The server should cleanly shut down when stopped (no connection warnings)
241212

242-
read::My lifespan management is working![]
213+
read::I have database statistics![]
243214

244215

245216
[TIP]
@@ -263,8 +234,8 @@ In this challenge, you successfully added lifespan management to your MCP server
263234
* **Environment variables** - Stored credentials in `.env` file and loaded them with `python-dotenv`
264235
* **Lifespan function** - Created an async context manager to initialize and clean up the Neo4j driver
265236
* **Context access** - Used `ctx.request_context.lifespan_context` to access the driver in tools
266-
* **Connection testing** - Verified the connection works with a simple test tool
237+
* **Connection testing** - Verified the connection works with the `graph_statistics` tool via the MCP Inspector
267238

268239
Your server now properly manages the Neo4j driver lifecycle, creating it once on startup and reusing it across all tool calls.
269240

270-
In the next lesson, you'll learn about the MCP Inspector and how to use it to test your server's tools and resources.
241+
In the next lesson, you'll learn how to add more advanced database features to your MCP server.

0 commit comments

Comments
 (0)