使用说明
MCP+Ollama本地工具调用示例
该项目展示了本地AI代理如何 理解用户查询 和 自动调用Python函数 使用:
- 模型上下文协议(主控程序)
- 没有 运行本地LLM(例如,calla3)
- python MCP客户端和服务器
🔗 序列图
sequenceDiagram
participant User
participant MCP_Client
participant Ollama_LLM
participant MCP_Server
User->>MCP_Client: 1) User types: "What is 5 + 8?"
MCP_Client->>Ollama_LLM: 2) Send available tools + user query
Ollama_LLM->>Ollama_LLM: 3) Understand query & tool descriptions
Ollama_LLM->>Ollama_LLM: 4) Select tool: add(a=5, b=8)
Ollama_LLM->>MCP_Client: 5) Return tool_call
MCP_Client->>MCP_Server: 6) Execute add(a=5, b=8)
MCP_Server-->>MCP_Client: 7) Return result: 13
MCP_Client-->>User: 8) Show final answer: 13
📚 项目结构
.
├── math_server.py # MCP Server exposing add() and multiply() tools
├── ollama_client.py # MCP Client interacting with Ollama
├── README.md # Project documentation
🛠️ 安装说明
1.安装要求
pip install "mcp[cli] @ git+https://github.com/awslabs/mcp.git" openai==0.28 httpx
确保你有 Ollama已安装 跑步。
2.拉取或运行LLM模型
ollama run llama3
(确保您运行的模型支持工具调用。)
3.运行MCP服务器
python math_server.py
服务器提供了两个简单的工具:
add(a: int, b: int) -> intmultiply(a: int, b: int) -> int
4.运行MCP客户端
python ollama_client.py math_server.py
5.互动!
示例查询:
Query: What is 5 + 8?
Response: 13
Query: Multiply 7 and 9
Response: 63
MCP客户端将查询和可用工具发送给Ollama。LLM内部根据工具描述和用户意图决定使用哪种工具。
🚀 运作原理
- MCP客户端列出了可用的工具。
- 向Ollama LLM发送工具+用户查询。
- LLM关于最佳匹配工具的原因。
- LLM生成
tool_call. - MCP客户端通过MCP服务器调用该函数。
- 返回并显示最终结果。
✅ 无需手动硬编码! ✅ 一切都在本地运行! ✅ 完全自主!
📢 为什么这很重要
此模式支持构建 智能本地AI代理 即:
- 理解用户意图
- 动态选择正确的操作
- 完全离线和本地操作
它为以下方面打开了大门:
- 自主开发人员
- 本地智能助理
- 安全的人工智能工作流程
🏷️ 用于共享的标签
#MCP #ModelContextProtocol #Ollama #LocalLLM #FunctionCalling #Python #AI #DeveloperTools #AIEngineering #AutonomousAgents
🙌 鸣谢
“更聪明的人工智能代理从理解他们的思维方式开始!”
下一步: 添加Streamlit UI或将此项目Docker化🚀
