Strands AI 代理与 MCP 和 Neo4j

将 Neo4j 图数据库与 Strands 代理集成。Neo4j 的图功能可以作为 MCP 工具暴露,使得基于 LLM 的 Strands 代理能够通过 HTTP 或 SSE 上的标准协议查询和修改数据库。

本指南提供了使用官方 Neo4j MCP Server 通过 stdio 传输的示例,消除了手动运行单独本地服务器进程的需求。

安装

pip install strands mcp neo4j pandas matplotlib seaborn openai

您还需要安装 uv,以直接运行 Neo4j MCP 服务器。

pip install uv

使用

直接运行 Strands 代理客户端。它会自动将 Neo4j MCP 服务器作为子进程启动。

前置条件:确保您已在环境中设置了 OpenAI API 密钥。

export OPENAI_API_KEY=sk-proj-...
python client.py

示例:client.py(使用官方 Neo4j MCP via Stdio)

此示例演示了 Strands 代理使用 uvx 直接连接官方 neo4j-mcp 服务器。它连接到公开的 Companies 演示数据库。

import os
from strands import Agent
from strands.tools.mcp import MCPClient
from strands.models.openai import OpenAIModel
from mcp import stdio_client, StdioServerParameters

# 1) Configure the MCP Client with Stdio transport
# This uses 'uvx' to run the official neo4j-mcp package directly
# Environment variables are passed to configure the specific database connection
def create_mcp_client():
    return stdio_client(
        StdioServerParameters(
            command="neo4j-mcp",
            args=[],
            env={
                "NEO4J_URI": "neo4j+s://demo.neo4jlabs.com:7687",
                "NEO4J_USERNAME": "companies",
                "NEO4J_PASSWORD": "companies",
                "NEO4J_DATABASE": "companies"
            }
        )
    )

def main():
    # 2) Initialize the MCP Client wrapper
    # Strands uses this wrapper to manage the tool discovery and execution
    client = MCPClient(create_mcp_client)

    print("Connecting to Neo4j via MCP...")

    with client:
        # 3) List available tools
        tools = client.list_tools_sync()

        # Helper to print tool names (accessing the internal mcp_tool object)
        tool_names = [t.mcp_tool.name for t in tools]
        print("Available tools:", tool_names)

        # 4) Create a Strands Agent using OpenAI
        # We explicitly use OpenAIModel to avoid defaulting to AWS Bedrock.
        # Note: 'model_id' is required (not 'model').
        # The API Key is picked up automatically from the OPENAI_API_KEY env var.
        agent = Agent(
            tools=tools,
            model=OpenAIModel(
                model_id="gpt-4o"
            ),
            system_prompt="You are a helper for querying graph databases. Use the available tools to answer questions."
        )

        # 5) Ask a question
        query = "What are 5 companies mentioned in articles from January 2023?"
        print(f"\nUser Query: {query}")

        response = agent(query)
        print("\nAgent Response:")
        print(response)

if __name__ == "__main__":
    main()

示例:金融犯罪分析(Stdio 传输)

此示例使用托管在公开 Neo4j 演示实例上的 FinCEN 数据集。它展示了带有滑动窗口对话管理器的更复杂用例。

import os
from strands import Agent
from strands.agent.conversation_manager import SlidingWindowConversationManager
from strands.tools.mcp import MCPClient
from strands.models.openai import OpenAIModel
from mcp import stdio_client, StdioServerParameters

# 1) Configure the MCP Client with Stdio transport
# This uses 'uvx' to run the official neo4j-mcp package
stdio_neo4j_mcp_client = MCPClient(
    lambda: stdio_client(
        StdioServerParameters(
            command="neo4j-mcp"
            args=[],
            env = {
                "NEO4J_URI" :  "neo4j+s://demo.neo4jlabs.com:7687",
                "NEO4J_USERNAME" : "fincen",
                "NEO4J_PASSWORD" :  "fincen",
                "NEO4J_DATABASE" : "fincen"
            }
        )
    )
)

# 2) Create a conversation manager
conversation_manager = SlidingWindowConversationManager(
    window_size=20,  # Maximum number of messages to keep
)

def call_agent(query):
    print('Starting agent query...')

    # 3) Create and run the agent context
    with stdio_neo4j_mcp_client:
        # Fetch available tools dynamically from the MCP server
        tools = stdio_neo4j_mcp_client.list_tools_sync()

        # Initialize the Strands Agent
        agent = Agent(
            tools=tools,
            callback_handler=None,
            conversation_manager=conversation_manager,
            model=OpenAIModel(
                model_id="gpt-4o"
            )
        )

        # Execute the query
        response = agent(query)

    print('Agent response:')
    print(response)
    return response

if __name__ == "__main__":
    # Example Query suitable for the FinCEN dataset
    call_agent("Retrieve the schema of the database to understand the nodes and relationships.")

示例:使用 Pandas 与 Seaborn 进行可视化

通过代理或直接从 Neo4j 检索数据后,您可以使用 Python 数据科学库可视化结果。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from neo4j import GraphDatabase

# 1) Direct connection for visualization data retrieval
NEO4J_URI = "neo4j+s://demo.neo4jlabs.com:7687"
NEO4J_USERNAME = "fincen"
NEO4J_PASSWORD = "fincen"

def get_transaction_data():
    with GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD)) as driver:
        # Example query: Count transactions by Entity
        query = """
        MATCH (s:Entity)-[r:FILED]->(f:Filing)
        RETURN s.name as Entity, count(r) as TransactionCount
        ORDER BY TransactionCount DESC
        LIMIT 10
        """
        records, summary, keys = driver.execute_query(query, database_="fincen")
        # Convert to Pandas DataFrame
        return pd.DataFrame([r.data() for r in records])

# 2) Visualize Data
if __name__ == "__main__":
    df = get_transaction_data()

    if not df.empty:
        plt.figure(figsize=(10, 6))
        sns.barplot(data=df, x='TransactionCount', y='Entity', palette='viridis')
        plt.title('Top 10 Entities by Transaction Filings (FinCEN)')
        plt.xlabel('Number of Filings')
        plt.ylabel('Entity Name')
        plt.tight_layout()
        plt.show()
    else:
        print("No data found to visualize.")

功能包括

  • read-cypher / write-cypher — 官方服务器暴露的标准工具

  • Strands 代理使用 MCP 传输调用工具

  • 通过 OpenAI 或 Mistral 集成 LLM

  • 支持使用 uvxstdio 传输,以进行短暂的服务器执行

  • 使用 pandasseabornmatplotlib 的数据可视化集成

社区支持

Neo4j 在线社区

Neo4j MCP 服务器

Neo4j MCP 服务器

文档

Strands 代理 SDK

© . This site is unofficial and not affiliated with Neo4j, Inc.