Spaces:
Paused
Paused
Commit ·
a348131
0
Parent(s):
【xxx】初始化python-agent工程,连接nacos成功
Browse files- .env.example +16 -0
- .gitignore +35 -0
- .python-version +1 -0
- README.md +98 -0
- app/__init__.py +0 -0
- app/agent/__init__.py +0 -0
- app/agent/graph.py +73 -0
- app/agent/state.py +9 -0
- app/core/__init__.py +0 -0
- app/core/config.py +44 -0
- app/core/nacos.py +63 -0
- app/services/__init__.py +0 -0
- app/services/mcp_client.py +163 -0
- app/setup.py +69 -0
- main.py +55 -0
- requirements.txt +8 -0
- tests/test_mcp_connection.py +51 -0
.env.example
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
APP_ENV=development
|
| 2 |
+
|
| 3 |
+
# Server
|
| 4 |
+
HOST=0.0.0.0
|
| 5 |
+
PORT=8181
|
| 6 |
+
|
| 7 |
+
# Nacos
|
| 8 |
+
NACOS_SERVER_ADDR=
|
| 9 |
+
NACOS_NAMESPACE=public
|
| 10 |
+
NACOS_USERNAME=
|
| 11 |
+
NACOS_PASSWORD=
|
| 12 |
+
SERVICE_NAME=python-agent
|
| 13 |
+
NACOS_GATEWAY_SERVICE_NAME=gateway
|
| 14 |
+
|
| 15 |
+
# MCP Config
|
| 16 |
+
# MCP_BRAVE_PATH=C:\Program Files\nodejs\npx.cmd
|
.gitignore
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
target/
|
| 2 |
+
.mvn
|
| 3 |
+
|
| 4 |
+
__pycache__/
|
| 5 |
+
.venv/
|
| 6 |
+
mvnw*
|
| 7 |
+
|
| 8 |
+
### STS ###
|
| 9 |
+
.apt_generated
|
| 10 |
+
.classpath
|
| 11 |
+
.factorypath
|
| 12 |
+
.project
|
| 13 |
+
.settings
|
| 14 |
+
.springBeans
|
| 15 |
+
.sts4-cache
|
| 16 |
+
|
| 17 |
+
### IntelliJ IDEA ###
|
| 18 |
+
.idea
|
| 19 |
+
*.iws
|
| 20 |
+
*.iml
|
| 21 |
+
*.ipr
|
| 22 |
+
|
| 23 |
+
### NetBeans ###
|
| 24 |
+
/nbproject/private/
|
| 25 |
+
/nbbuild/
|
| 26 |
+
/dist/
|
| 27 |
+
/nbdist/
|
| 28 |
+
/.nb-gradle/
|
| 29 |
+
!**/src/main/**/build/
|
| 30 |
+
!**/src/test/**/build/
|
| 31 |
+
|
| 32 |
+
### VS Code ###
|
| 33 |
+
.vscode/
|
| 34 |
+
.DS_Store
|
| 35 |
+
.env
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.11.8
|
README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python Agent
|
| 2 |
+
|
| 3 |
+
A modular Python-based AI agent service built with FastAPI, integrating **Nacos** for service discovery and **Model Context Protocol (MCP)** for extensible tool usage. This agent uses **LangGraph** to orchestrate agentic workflows.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
|
| 7 |
+
- **FastAPI Framework**: High-performance, easy-to-learn web framework.
|
| 8 |
+
- **Service Discovery**: Seamless integration with Nacos for service registration and discovery.
|
| 9 |
+
- **LangGraph**: Stateful, multi-actor applications with cycles (agentic orchestration).
|
| 10 |
+
- **Model Context Protocol (MCP)**:
|
| 11 |
+
- **Stdio Client**: Connects to local CLI tools (e.g., Brave Search via Node.js).
|
| 12 |
+
- **SSE Client**: Connects to remote services (e.g., Java backend) via Server-Sent Events.
|
| 13 |
+
|
| 14 |
+
## Prerequisites
|
| 15 |
+
|
| 16 |
+
- **Python 3.10+**
|
| 17 |
+
- **Node.js**: Required for running the Brave Search MCP server (`npx`).
|
| 18 |
+
- **Nacos Server 2.x**: A running Nacos instance is required for the application to start.
|
| 19 |
+
|
| 20 |
+
## Installation
|
| 21 |
+
|
| 22 |
+
1. Clone the repository:
|
| 23 |
+
```bash
|
| 24 |
+
git clone <repository_url>
|
| 25 |
+
cd python-agent
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
2. Create and activate a virtual environment:
|
| 29 |
+
```bash
|
| 30 |
+
python -m venv .venv
|
| 31 |
+
# Windows
|
| 32 |
+
.venv\Scripts\activate
|
| 33 |
+
# Linux/Mac
|
| 34 |
+
source .venv/bin/activate
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
3. Install dependencies:
|
| 38 |
+
```bash
|
| 39 |
+
pip install -r requirements.txt
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Configuration
|
| 43 |
+
|
| 44 |
+
The application is configured via environment variables. You can create a `.env` file in the root directory (see `.env.example`).
|
| 45 |
+
|
| 46 |
+
| Variable | Default | Description |
|
| 47 |
+
|----------|---------|-------------|
|
| 48 |
+
| `APP_ENV` | `development` | Application environment (`development` or `production`). |
|
| 49 |
+
| `HOST` | `0.0.0.0` | Host to bind the server to. |
|
| 50 |
+
| `PORT` | `8181` | Port to listen on. |
|
| 51 |
+
| `NACOS_SERVER_ADDR` | `pei.12277.xyz:18848` | Address of the Nacos server. |
|
| 52 |
+
| `NACOS_NAMESPACE` | `public` | Nacos namespace ID. |
|
| 53 |
+
| `NACOS_USERNAME` | `nacos` | Nacos username. |
|
| 54 |
+
| `NACOS_PASSWORD` | `nacos` | Nacos password. |
|
| 55 |
+
| `SERVICE_NAME` | `python-agent` | Name of this service in Nacos. |
|
| 56 |
+
| `MCP_BRAVE_PATH` | (Auto-detected) | Optional override for `npx` path. |
|
| 57 |
+
| `NACOS_GATEWAY_SERVICE_NAME` | `gateway` | Name of the Java/Gateway service to discover. |
|
| 58 |
+
|
| 59 |
+
## Usage
|
| 60 |
+
|
| 61 |
+
### Running the Application
|
| 62 |
+
|
| 63 |
+
Using `python`:
|
| 64 |
+
```bash
|
| 65 |
+
python main.py
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
Using `uvicorn` (with hot reload):
|
| 69 |
+
```bash
|
| 70 |
+
uvicorn main:app --reload --port 8181
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
> **Note**: The application will fail to start if it cannot connect to the configured Nacos server.
|
| 74 |
+
|
| 75 |
+
### API Endpoints
|
| 76 |
+
|
| 77 |
+
- **Health Check**: `GET /health`
|
| 78 |
+
- **Chat**: `POST /chat`
|
| 79 |
+
```json
|
| 80 |
+
{
|
| 81 |
+
"message": "Search for the latest news on AI."
|
| 82 |
+
}
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## Project Structure
|
| 86 |
+
|
| 87 |
+
The project follows a modular package structure:
|
| 88 |
+
|
| 89 |
+
```text
|
| 90 |
+
python-agent/
|
| 91 |
+
├── app/
|
| 92 |
+
│ ├── core/ # Core configuration & infrastructure (Nacos, Config)
|
| 93 |
+
│ ├── services/ # External service clients (MCP)
|
| 94 |
+
│ ├── agent/ # LangGraph logic (State, Graph, Nodes)
|
| 95 |
+
│ └── setup.py # Startup setup scripts
|
| 96 |
+
├── main.py # Entry point
|
| 97 |
+
└── ...
|
| 98 |
+
```
|
app/__init__.py
ADDED
|
File without changes
|
app/agent/__init__.py
ADDED
|
File without changes
|
app/agent/graph.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langgraph.graph import StateGraph, END
|
| 2 |
+
from app.agent.state import AgentState
|
| 3 |
+
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
|
| 4 |
+
from app.services.mcp_client import get_all_tools, mcp_clients
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
# Placeholder for RAG
|
| 8 |
+
async def retrieve(state: AgentState):
|
| 9 |
+
# Simulating RAG retrieval
|
| 10 |
+
query = state['messages'][-1].content
|
| 11 |
+
# In reality, query vector DB
|
| 12 |
+
context = f"Retrieved context for: {query}"
|
| 13 |
+
return {"context": context}
|
| 14 |
+
|
| 15 |
+
# Placeholder for LLM / Think
|
| 16 |
+
async def think(state: AgentState):
|
| 17 |
+
messages = state['messages']
|
| 18 |
+
context = state.get('context', '')
|
| 19 |
+
|
| 20 |
+
# Simple logic to simulate "thinking"
|
| 21 |
+
last_msg = messages[-1].content.lower()
|
| 22 |
+
|
| 23 |
+
# If user asks to "search", we trigger tool call
|
| 24 |
+
if "search" in last_msg:
|
| 25 |
+
# Mocking a tool call decision
|
| 26 |
+
return {"current_step": "tool_call", "tool_calls": [{"name": "brave-search", "args": {"q": "search term"}}]}
|
| 27 |
+
|
| 28 |
+
return {"current_step": "generate"}
|
| 29 |
+
|
| 30 |
+
# Tool execution node
|
| 31 |
+
async def tool_call_node(state: AgentState):
|
| 32 |
+
# This would parse the decision from 'think'
|
| 33 |
+
# For now, we just list tools or call a mock one
|
| 34 |
+
# Assuming 'think' decided to call a tool
|
| 35 |
+
|
| 36 |
+
# Example: fetch all tools
|
| 37 |
+
tools = await get_all_tools()
|
| 38 |
+
|
| 39 |
+
# Mock execution
|
| 40 |
+
# result = await client.call_tool(...)
|
| 41 |
+
|
| 42 |
+
return {"messages": [AIMessage(content=f"Executed tool. Available tools: {len(tools)}")]}
|
| 43 |
+
|
| 44 |
+
# Generation node
|
| 45 |
+
async def generate(state: AgentState):
|
| 46 |
+
context = state.get('context', '')
|
| 47 |
+
return {"messages": [AIMessage(content=f"Generated response based on: {context}")]}
|
| 48 |
+
|
| 49 |
+
def route_step(state: AgentState):
|
| 50 |
+
step = state.get('current_step')
|
| 51 |
+
if step == "tool_call":
|
| 52 |
+
return "tool_call"
|
| 53 |
+
return "generate"
|
| 54 |
+
|
| 55 |
+
# Build Graph
|
| 56 |
+
builder = StateGraph(AgentState)
|
| 57 |
+
|
| 58 |
+
builder.add_node("retrieve", retrieve)
|
| 59 |
+
builder.add_node("think", think)
|
| 60 |
+
builder.add_node("tool_call", tool_call_node)
|
| 61 |
+
builder.add_node("generate", generate)
|
| 62 |
+
|
| 63 |
+
builder.set_entry_point("retrieve")
|
| 64 |
+
|
| 65 |
+
builder.add_edge("retrieve", "think")
|
| 66 |
+
builder.add_conditional_edges("think", route_step, {
|
| 67 |
+
"tool_call": "tool_call",
|
| 68 |
+
"generate": "generate"
|
| 69 |
+
})
|
| 70 |
+
builder.add_edge("tool_call", "generate") # Loop back or go to generate? User said "Tool Call -> Generate"
|
| 71 |
+
builder.add_edge("generate", END)
|
| 72 |
+
|
| 73 |
+
graph = builder.compile()
|
app/agent/state.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TypedDict, Annotated, List, Union
|
| 2 |
+
from langchain_core.messages import BaseMessage
|
| 3 |
+
import operator
|
| 4 |
+
|
| 5 |
+
class AgentState(TypedDict):
|
| 6 |
+
messages: Annotated[List[BaseMessage], operator.add]
|
| 7 |
+
context: str
|
| 8 |
+
current_step: str
|
| 9 |
+
tool_outputs: dict
|
app/core/__init__.py
ADDED
|
File without changes
|
app/core/config.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
|
| 5 |
+
class Config:
|
| 6 |
+
"""Base configuration."""
|
| 7 |
+
APP_ENV = os.getenv("APP_ENV", "development")
|
| 8 |
+
|
| 9 |
+
# Server
|
| 10 |
+
HOST = os.getenv("HOST", "0.0.0.0")
|
| 11 |
+
PORT = int(os.getenv("PORT", 8181))
|
| 12 |
+
|
| 13 |
+
# Nacos
|
| 14 |
+
NACOS_SERVER_ADDR = os.getenv("NACOS_SERVER_ADDR", "pei.12277.xyz:18848")
|
| 15 |
+
NACOS_NAMESPACE = os.getenv("NACOS_NAMESPACE", "public")
|
| 16 |
+
NACOS_USERNAME = os.getenv("NACOS_USERNAME", "nacos")
|
| 17 |
+
NACOS_PASSWORD = os.getenv("NACOS_PASSWORD", "nacos")
|
| 18 |
+
SERVICE_NAME = os.getenv("SERVICE_NAME", "python-agent")
|
| 19 |
+
|
| 20 |
+
# MCP Clients
|
| 21 |
+
MCP_BRAVE_PATH = os.getenv("MCP_BRAVE_PATH") # Optional override
|
| 22 |
+
NACOS_GATEWAY_SERVICE_NAME = os.getenv("NACOS_GATEWAY_SERVICE_NAME", "gateway")
|
| 23 |
+
|
| 24 |
+
class DevelopmentConfig(Config):
|
| 25 |
+
"""Development configuration."""
|
| 26 |
+
DEBUG = True
|
| 27 |
+
# In Dev, we might want to default to localhost if not specified,
|
| 28 |
+
# but the user's current valid config points to an external Nacos.
|
| 29 |
+
# We'll keep the external Nacos as default for now based on current working code.
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
class ProductionConfig(Config):
|
| 33 |
+
"""Production configuration."""
|
| 34 |
+
DEBUG = False
|
| 35 |
+
# Enforce stricter defaults or require env vars here if needed
|
| 36 |
+
|
| 37 |
+
@lru_cache()
|
| 38 |
+
def get_settings():
|
| 39 |
+
env = os.getenv("APP_ENV", "development")
|
| 40 |
+
if env == "production":
|
| 41 |
+
return ProductionConfig()
|
| 42 |
+
return DevelopmentConfig()
|
| 43 |
+
|
| 44 |
+
settings = get_settings()
|
app/core/nacos.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import nacos
|
| 2 |
+
import socket
|
| 3 |
+
import logging
|
| 4 |
+
from app.core.config import settings
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
class NacosManager:
|
| 9 |
+
def __init__(self, server_addr, username, password, namespace, service_name, ip=None, port=8181):
|
| 10 |
+
self.server_addr = server_addr
|
| 11 |
+
self.namespace = namespace
|
| 12 |
+
self.service_name = service_name
|
| 13 |
+
self.port = port
|
| 14 |
+
self.ip = ip or self._get_local_ip()
|
| 15 |
+
self.client = nacos.NacosClient(
|
| 16 |
+
server_addr,
|
| 17 |
+
namespace=namespace,
|
| 18 |
+
username=username,
|
| 19 |
+
password=password
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def _get_local_ip(self):
|
| 23 |
+
try:
|
| 24 |
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
| 25 |
+
# Doesn't even have to be reachable
|
| 26 |
+
s.connect(('10.255.255.255', 1))
|
| 27 |
+
IP = s.getsockname()[0]
|
| 28 |
+
except Exception:
|
| 29 |
+
IP = '127.0.0.1'
|
| 30 |
+
finally:
|
| 31 |
+
s.close()
|
| 32 |
+
return IP
|
| 33 |
+
|
| 34 |
+
def register_service(self):
|
| 35 |
+
try:
|
| 36 |
+
self.client.add_naming_instance(self.service_name, self.ip, self.port)
|
| 37 |
+
logger.info(f"Registered service {self.service_name} at {self.ip}:{self.port}")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Failed to register service: {e}")
|
| 40 |
+
|
| 41 |
+
def deregister_service(self):
|
| 42 |
+
try:
|
| 43 |
+
self.client.remove_naming_instance(self.service_name, self.ip, self.port)
|
| 44 |
+
logger.info(f"Deregistered service {self.service_name}")
|
| 45 |
+
except Exception as e:
|
| 46 |
+
logger.error(f"Failed to deregister service: {e}")
|
| 47 |
+
|
| 48 |
+
def get_service(self, service_name):
|
| 49 |
+
try:
|
| 50 |
+
return self.client.list_naming_instance(service_name)
|
| 51 |
+
except Exception as e:
|
| 52 |
+
logger.error(f"Failed to get service {service_name}: {e}")
|
| 53 |
+
return []
|
| 54 |
+
|
| 55 |
+
# Singleton instance
|
| 56 |
+
nacos_manager = NacosManager(
|
| 57 |
+
server_addr=settings.NACOS_SERVER_ADDR,
|
| 58 |
+
namespace=settings.NACOS_NAMESPACE,
|
| 59 |
+
username=settings.NACOS_USERNAME,
|
| 60 |
+
password=settings.NACOS_PASSWORD,
|
| 61 |
+
service_name=settings.SERVICE_NAME,
|
| 62 |
+
port=settings.PORT
|
| 63 |
+
)
|
app/services/__init__.py
ADDED
|
File without changes
|
app/services/mcp_client.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import httpx
|
| 5 |
+
from sseclient import SSEClient
|
| 6 |
+
import threading
|
| 7 |
+
import subprocess
|
| 8 |
+
import shutil
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
class MCPClient:
|
| 13 |
+
def __init__(self, name):
|
| 14 |
+
self.name = name
|
| 15 |
+
self.tools = []
|
| 16 |
+
|
| 17 |
+
async def list_tools(self):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
async def call_tool(self, tool_name, arguments):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
class SSEMCPClient(MCPClient):
|
| 24 |
+
def __init__(self, name, base_url):
|
| 25 |
+
super().__init__(name)
|
| 26 |
+
self.base_url = base_url.rstrip('/')
|
| 27 |
+
self.sse_url = f"{self.base_url}/mcp/sse"
|
| 28 |
+
self.post_url = f"{self.base_url}/mcp/message" # Assuming standard implementation
|
| 29 |
+
self._listening = False
|
| 30 |
+
|
| 31 |
+
async def connect(self):
|
| 32 |
+
# In a real implementation, we'd start a background task to listen to SSE
|
| 33 |
+
# and handshake. For now, we'll assume we can just query tools.
|
| 34 |
+
# But wait, MCP requires initialization.
|
| 35 |
+
logger.info(f"Connecting to SSE MCP Server at {self.sse_url}")
|
| 36 |
+
# Simplified for this task: specific implementation details might vary
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
async def list_tools(self):
|
| 40 |
+
# JSON-RPC request to list tools
|
| 41 |
+
payload = {
|
| 42 |
+
"jsonrpc": "2.0",
|
| 43 |
+
"id": 1,
|
| 44 |
+
"method": "tools/list",
|
| 45 |
+
"params": {}
|
| 46 |
+
}
|
| 47 |
+
async with httpx.AsyncClient() as client:
|
| 48 |
+
response = await client.post(self.post_url, json=payload)
|
| 49 |
+
response.raise_for_status()
|
| 50 |
+
result = response.json()
|
| 51 |
+
if 'result' in result:
|
| 52 |
+
self.tools = result['result'].get('tools', [])
|
| 53 |
+
return self.tools
|
| 54 |
+
return []
|
| 55 |
+
|
| 56 |
+
async def call_tool(self, tool_name, arguments):
|
| 57 |
+
payload = {
|
| 58 |
+
"jsonrpc": "2.0",
|
| 59 |
+
"id": 2,
|
| 60 |
+
"method": "tools/call",
|
| 61 |
+
"params": {
|
| 62 |
+
"name": tool_name,
|
| 63 |
+
"arguments": arguments
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
async with httpx.AsyncClient() as client:
|
| 67 |
+
response = await client.post(self.post_url, json=payload)
|
| 68 |
+
response.raise_for_status()
|
| 69 |
+
return response.json().get('result', {})
|
| 70 |
+
|
| 71 |
+
class StdioMCPClient(MCPClient):
|
| 72 |
+
def __init__(self, name, command, args):
|
| 73 |
+
super().__init__(name)
|
| 74 |
+
self.command = command
|
| 75 |
+
self.args = args
|
| 76 |
+
self.process = None
|
| 77 |
+
self._response_futures = {}
|
| 78 |
+
self._lock = asyncio.Lock()
|
| 79 |
+
|
| 80 |
+
async def connect(self):
|
| 81 |
+
full_command = [self.command] + self.args
|
| 82 |
+
if shutil.which(self.command) is None:
|
| 83 |
+
if self.command == 'npx':
|
| 84 |
+
full_command[0] = 'npx.cmd'
|
| 85 |
+
|
| 86 |
+
logger.info(f"Starting Stdio MCP Server: {full_command}")
|
| 87 |
+
self.process = await asyncio.create_subprocess_exec(
|
| 88 |
+
*full_command,
|
| 89 |
+
stdin=asyncio.subprocess.PIPE,
|
| 90 |
+
stdout=asyncio.subprocess.PIPE,
|
| 91 |
+
stderr=asyncio.subprocess.PIPE
|
| 92 |
+
)
|
| 93 |
+
asyncio.create_task(self._listen_stdout())
|
| 94 |
+
|
| 95 |
+
# Initialize
|
| 96 |
+
await self._send_json_rpc("initialize", {
|
| 97 |
+
"protocolVersion": "0.1.0",
|
| 98 |
+
"capabilities": {},
|
| 99 |
+
"clientInfo": {"name": "python-agent", "version": "0.1"}
|
| 100 |
+
})
|
| 101 |
+
await self._send_json_rpc("notifications/initialized")
|
| 102 |
+
|
| 103 |
+
async def _listen_stdout(self):
|
| 104 |
+
while True:
|
| 105 |
+
line = await self.process.stdout.readline()
|
| 106 |
+
if not line:
|
| 107 |
+
break
|
| 108 |
+
try:
|
| 109 |
+
data = json.loads(line)
|
| 110 |
+
if 'id' in data and data['id'] in self._response_futures:
|
| 111 |
+
self._response_futures[data['id']].set_result(data)
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logger.error(f"Error parsing JSON from stdio: {e}")
|
| 114 |
+
|
| 115 |
+
async def _send_json_rpc(self, method, params=None):
|
| 116 |
+
req_id = 1 # In real app, increment this
|
| 117 |
+
future = asyncio.Future()
|
| 118 |
+
self._response_futures[req_id] = future
|
| 119 |
+
|
| 120 |
+
payload = {
|
| 121 |
+
"jsonrpc": "2.0",
|
| 122 |
+
"id": req_id,
|
| 123 |
+
"method": method,
|
| 124 |
+
"params": params or {}
|
| 125 |
+
}
|
| 126 |
+
json_str = json.dumps(payload) + "\n"
|
| 127 |
+
self.process.stdin.write(json_str.encode())
|
| 128 |
+
await self.process.stdin.drain()
|
| 129 |
+
|
| 130 |
+
return await future
|
| 131 |
+
|
| 132 |
+
async def list_tools(self):
|
| 133 |
+
response = await self._send_json_rpc("tools/list")
|
| 134 |
+
if response and 'result' in response:
|
| 135 |
+
self.tools = response['result'].get('tools', [])
|
| 136 |
+
return self.tools
|
| 137 |
+
return []
|
| 138 |
+
|
| 139 |
+
async def call_tool(self, tool_name, arguments):
|
| 140 |
+
response = await self._send_json_rpc("tools/call", {
|
| 141 |
+
"name": tool_name,
|
| 142 |
+
"arguments": arguments
|
| 143 |
+
})
|
| 144 |
+
if response and 'result' in response:
|
| 145 |
+
return response['result']
|
| 146 |
+
return {}
|
| 147 |
+
# Registry
|
| 148 |
+
mcp_clients = {}
|
| 149 |
+
|
| 150 |
+
def register_mcp_client(client: MCPClient):
|
| 151 |
+
mcp_clients[client.name] = client
|
| 152 |
+
|
| 153 |
+
async def get_all_tools():
|
| 154 |
+
all_tools = []
|
| 155 |
+
for client in mcp_clients.values():
|
| 156 |
+
try:
|
| 157 |
+
tools = await client.list_tools()
|
| 158 |
+
for t in tools:
|
| 159 |
+
t['client_name'] = client.name # Tag with client name
|
| 160 |
+
all_tools.extend(tools)
|
| 161 |
+
except Exception as e:
|
| 162 |
+
logger.error(f"Error listing tools from {client.name}: {e}")
|
| 163 |
+
return all_tools
|
app/setup.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import sys
|
| 4 |
+
import asyncio
|
| 5 |
+
from app.services.mcp_client import StdioMCPClient, SSEMCPClient, register_mcp_client
|
| 6 |
+
from app.core.nacos import nacos_manager
|
| 7 |
+
import logging
|
| 8 |
+
from app.core.config import settings
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
async def setup_mcp_clients():
|
| 13 |
+
# 1. Stdio Client (e.g., Brave Search)
|
| 14 |
+
# We'll use a placeholder command or the one requested if we can find it.
|
| 15 |
+
# The user mentioned "Node.js MCP Server (如 Brave Search)".
|
| 16 |
+
# Let's assume the user has npx and the package.
|
| 17 |
+
|
| 18 |
+
# Check config first, then fall back to auto-discovery
|
| 19 |
+
npx_path = settings.MCP_BRAVE_PATH or shutil.which("npx")
|
| 20 |
+
|
| 21 |
+
# 2. 安全检查:如果没有安装 Node.js/npx,提前报错
|
| 22 |
+
if not npx_path:
|
| 23 |
+
raise FileNotFoundError("未找到 npx 命令,请确保已安装 Node.js 并添加到环境变量中,或在配置中指定路径。")
|
| 24 |
+
|
| 25 |
+
# 3. 初始化客户端
|
| 26 |
+
brave_client = StdioMCPClient(
|
| 27 |
+
name="brave-search",
|
| 28 |
+
command=npx_path, # 传入绝对路径,如 "C:\...\npx.cmd"
|
| 29 |
+
args=["-y", "@modelcontextprotocol/server-brave-search"]
|
| 30 |
+
)
|
| 31 |
+
# We register it but connection happens async
|
| 32 |
+
# await brave_client.connect() # Connect in background
|
| 33 |
+
register_mcp_client(brave_client)
|
| 34 |
+
|
| 35 |
+
# 2. SSE Client (Java Service)
|
| 36 |
+
# Discover via Nacos
|
| 37 |
+
# In a real app we might poll or wait for service to be available.
|
| 38 |
+
# Here we'll try once or assume fixed path for testing if not found.
|
| 39 |
+
# Wait, the java service is running? User said "run time query".
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
async def connect_clients():
|
| 43 |
+
# Connect Stdio
|
| 44 |
+
try:
|
| 45 |
+
# We need to find the client from registry
|
| 46 |
+
from app.services.mcp_client import mcp_clients
|
| 47 |
+
if "brave-search" in mcp_clients:
|
| 48 |
+
await mcp_clients["brave-search"].connect()
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logger.error(f"Failed to connect to Brave Search: {e}")
|
| 51 |
+
|
| 52 |
+
# Connect SSE
|
| 53 |
+
try:
|
| 54 |
+
# Resolve Java service
|
| 55 |
+
instances = nacos_manager.get_service(settings.NACOS_GATEWAY_SERVICE_NAME)
|
| 56 |
+
if instances:
|
| 57 |
+
# Pick one
|
| 58 |
+
target = instances[0]
|
| 59 |
+
ip = target['ip']
|
| 60 |
+
port = target['port']
|
| 61 |
+
url = f"http://{ip}:{port}"
|
| 62 |
+
sse_client = SSEMCPClient(name="java-service", base_url=url)
|
| 63 |
+
# await sse_client.connect()
|
| 64 |
+
register_mcp_client(sse_client)
|
| 65 |
+
logger.info(f"Registered SSE client for Java service at {url}")
|
| 66 |
+
else:
|
| 67 |
+
logger.warning(f"No {settings.NACOS_GATEWAY_SERVICE_NAME} service found in Nacos")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
logger.error(f"Failed to setup SSE client: {e}")
|
main.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import uvicorn
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
from app.core.nacos import nacos_manager
|
| 6 |
+
from app.setup import setup_mcp_clients, connect_clients
|
| 7 |
+
from app.agent.graph import graph
|
| 8 |
+
from langchain_core.messages import HumanMessage
|
| 9 |
+
import logging
|
| 10 |
+
import asyncio
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
@asynccontextmanager
|
| 16 |
+
async def lifespan(app: FastAPI):
|
| 17 |
+
# Startup logic
|
| 18 |
+
logger.info("Agent starting up...")
|
| 19 |
+
nacos_manager.register_service()
|
| 20 |
+
|
| 21 |
+
# Setup and connect MCP clients
|
| 22 |
+
await setup_mcp_clients()
|
| 23 |
+
# connect_clients needs to run after startup potentially or concurrency
|
| 24 |
+
asyncio.create_task(connect_clients())
|
| 25 |
+
|
| 26 |
+
yield
|
| 27 |
+
# Shutdown logic
|
| 28 |
+
logger.info("Agent shutting down...")
|
| 29 |
+
nacos_manager.deregister_service()
|
| 30 |
+
|
| 31 |
+
app = FastAPI(lifespan=lifespan)
|
| 32 |
+
|
| 33 |
+
@app.get("/health")
|
| 34 |
+
async def health():
|
| 35 |
+
return {"status": "ok"}
|
| 36 |
+
|
| 37 |
+
class ChatRequest(BaseModel):
|
| 38 |
+
message: str
|
| 39 |
+
|
| 40 |
+
@app.post("/chat")
|
| 41 |
+
async def chat(request: ChatRequest):
|
| 42 |
+
try:
|
| 43 |
+
inputs = {"messages": [HumanMessage(content=request.message)]}
|
| 44 |
+
result = await graph.ainvoke(inputs)
|
| 45 |
+
# Extract final message
|
| 46 |
+
last_message = result['messages'][-1]
|
| 47 |
+
return {"response": last_message.content, "state": result}
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logger.error(f"Error during chat: {e}")
|
| 50 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 51 |
+
|
| 52 |
+
from app.core.config import settings
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
uvicorn.run(app, host=settings.HOST, port=settings.PORT)
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
langchain
|
| 4 |
+
langgraph
|
| 5 |
+
nacos-sdk-python
|
| 6 |
+
httpx
|
| 7 |
+
sseclient-py
|
| 8 |
+
"mcp[sse]"
|
tests/test_mcp_connection.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from mcp import ClientSession, StdioServerParameters
|
| 3 |
+
from mcp.client.sse import sse_client
|
| 4 |
+
from mcp.types import CallToolRequestParams
|
| 5 |
+
|
| 6 |
+
# Java 服务的地址 (注意:/mcp/sse 是你在 Java Controller 定义的 endpoint)
|
| 7 |
+
# 如果你是 Docker 部署,请确保这里能访问到 Java 容器
|
| 8 |
+
JAVA_MCP_URL = "http://localhost:8080/mcp/sse"
|
| 9 |
+
|
| 10 |
+
async def run_test():
|
| 11 |
+
print(f"🔌 正在连接 Java MCP Server: {JAVA_MCP_URL} ...")
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
# 1. 建立 SSE 连接
|
| 15 |
+
async with sse_client(JAVA_MCP_URL) as (read, write):
|
| 16 |
+
# 2. 建立 MCP 会话 (握手)
|
| 17 |
+
async with ClientSession(read, write) as session:
|
| 18 |
+
await session.initialize()
|
| 19 |
+
print("✅ 握手成功 (Initialize)")
|
| 20 |
+
|
| 21 |
+
# 3. 列出可用工具 (List Tools)
|
| 22 |
+
tools_result = await session.list_tools()
|
| 23 |
+
print(f"\n🛠️ Java 端暴露了 {len(tools_result.tools)} 个工具:")
|
| 24 |
+
for tool in tools_result.tools:
|
| 25 |
+
print(f" - {tool.name}: {tool.description}")
|
| 26 |
+
|
| 27 |
+
# 4. 发起工具调用 (Call Tool)
|
| 28 |
+
tool_name = "query_order"
|
| 29 |
+
test_args = {"orderId": "CN-8888"}
|
| 30 |
+
|
| 31 |
+
print(f"\n🚀 正在调用工具 [{tool_name}] 参数: {test_args} ...")
|
| 32 |
+
|
| 33 |
+
result = await session.call_tool(
|
| 34 |
+
name=tool_name,
|
| 35 |
+
arguments=test_args
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# 5. 解析结果
|
| 39 |
+
print("\n📩 Java 返回结果:")
|
| 40 |
+
for content in result.content:
|
| 41 |
+
if content.type == 'text':
|
| 42 |
+
print(f" >> {content.text}")
|
| 43 |
+
else:
|
| 44 |
+
print(f" >> (非文本数据) {content}")
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"\n❌ 测试失败: {e}")
|
| 48 |
+
print("💡 提示:请检查 Java 服务是否启动,以及 URL 是否正确。")
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
asyncio.run(run_test())
|