AI代理工具交互演示

一个展示AI代理如何通过LLM与MCP服务器提供的工具(如天气、事件查询)进行交互的演示项目。

  • by dvhthomas
  • Python
  • 本地部署
  • 3 星标
  • 更新于
在 GitHub 查看 dvhthomas/mcp_demo

使用说明

MCP演示:代理+LLM+MCP工具

演示由LLM支持的AI代理如何与MCP(模型上下文协议)服务器提供的工具进行交互。

它的作用: LangGraph ReACT代理使用Ollama(llama3.2:3b)对用户查询进行推理,并调用MCP工具(天气、事件)来回答问题。

快速开始

1.安装Ollama并获取模型

# Install Ollama
# Mac: brew install ollama
# Or download from https://ollama.ai

# Start Ollama server (keep this running)
ollama serve

# In a separate terminal, pull the model:
ollama pull llama3.2:3b

2.安装依赖项

uv sync

3.运行MCP服务器

# Terminal 2 (Ollama serve is in Terminal 1)
uv run python main.py

服务器启动于http://localhost:8000

4.运行代理

# Terminal 3
uv run python client/agent.py

示例用法

# Interactive mode (verbose by default - shows reasoning steps)
uv run python client/agent.py

You: What's the weather in Tokyo?
Agent: [Shows ReACT reasoning loop, then final answer]

# Single query (shows reasoning steps by default)
uv run python client/agent.py --query "What events are happening in Paris today?"

# Quiet mode - show only final answers (no reasoning steps)
uv run python client/agent.py --quiet --query "What's the weather in Berlin?"

注: 默认情况下,代理以详细模式运行,显示ReACT推理循环(问题→ 工具调用→ 观察→ 实时回答。这是一种教育,可以帮助你理解代理人的想法。使用 --quiet 只看到最终的答案。

项目结构

mcp_demo/
├── server/              # MCP server (FastMCP + tools)
│   ├── server.py       # FastMCP server with SSE
│   ├── mcp_adapters.py # Protocol adapters
│   └── tools/          # Weather & Events tools
├── client/              # LangGraph agent
│   └── agent.py        # LangGraph ReACT agent with MCP
├── tests/              # Pytest tests
├── main.py             # Server entry point
└── example.py          # Direct tool usage

文档

需求

核心要求

用于运行代理(测试时可选)

备注:您可以在没有Ollama的情况下运行MCP服务器和集成测试。Ollama仅在使用LangGraph代理时才需要(client/agent.py).

提供的工具

  1. get_weather -任何城市的当前天气(Open-Meteo API,无需密钥)
  2. 搜索事件 -任何城市今天发生的事件(DuckDuckGo搜索)

测试

# Run all tests
uv run pytest

# Run unit tests only
uv run pytest tests/server/

# Run with verbose output
uv run pytest -v

故障排除

错误: [Errno 48] Address already in use

当端口8000已被另一个进程占用时,会发生此错误。

在Mac上,找到并终止进程:

# Option 1: Find what's using port 8000
lsof -i :8000

# Look for the PID in the output, then kill it:
kill -9 <PID>

# Option 2: One-liner to find and kill the process
lsof -ti :8000 | xargs kill -9

# Verify the port is free
lsof -i :8000
# (should return nothing)

常见原因:

  • 上一个服务器实例未正确关闭
  • 另一个应用程序正在使用端口8000
  • 测试使服务器在后台运行

关键技术

  • MCP-SDK -官方模型上下文协议实现(FastMCP服务器、SSE客户端)
  • LangGraph -现代代理框架(预构建的ReACT代理)
  • LangChain MCP适配器 -LangChain与MCP正式整合
  • 奥拉玛 -局部LLM推理(llama3.2:3b)
  • FastAPI/Starlette -HTTP服务器框架
  • pytest -测试框架