模型上下文协议框架

一个用于创建MCP(模型上下文协议)工具的简单教育框架,允许AI模型通过干净、可扩展的接口与外部工具和资源交互。

  • by scarlettlee
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 scarlettlee/mcp_test

使用说明

MCP框架-模型上下文协议

一个用于创建MCP(模型上下文协议)工具的简单教育框架。该框架允许AI模型通过干净、可扩展的界面与外部工具和资源进行交互。

什么是MCP?

模型上下文协议(MCP) 使AI模型能够:

  • 呼叫工具:执行函数以执行操作(计算、API调用等)
  • 访问资源:需要时检索数据或信息
  • 保持上下文:记住交互中的信息

将其视为赋予AI助手以下能力:

  • 使用计算器(工具)
  • 检查天气(工具)
  • 记住你的名字(上下文/记忆)
  • 访问地理空间数据(STAC API工具)

项目结构

├── mcp_framework.py       # Core framework (MCPServer class)
├── config/                 # API configuration management
│   ├── __init__.py        # Config exports
│   └── api_config.py      # API key and configuration management
├── tools/                  # Tool modules
│   ├── __init__.py        # Tool exports
│   ├── basic_tools.py      # Example tools (calculator, memory, weather)
│   └── stac_tools.py      # STAC API tools (geospatial data)
├── examples.py            # Comprehensive examples
├── requirements.txt       # Python dependencies
├── config.json.example    # Example configuration file
└── README.md              # This file

快速开始

1.安装依赖项

pip install -r requirements.txt

2.配置API密钥

有些工具需要API键才能运行。在中配置它们 config.json:

复制 config.json.example 到 config.json:

cp config.json.example config.json  # On Windows: copy config.json.example config.json

然后编辑 config.json 并添加您的API密钥:

{
  "weather": {
    "api_key": "your_openweathermap_api_key_here"
  },
  "stac": {
    "api_url": "https://planetarycomputer.microsoft.com/api/stac/v1"
  }
}

注: config.json 被gitignored以保护您的API密钥。

3.获取API密钥

  • 天气API:从获取免费的API密钥 OpenWeatherMap
  • API STAC:Microsoft Planetary Computer(默认)不需要密钥,但您可以配置自定义STAC端点

4.运行示例

python examples.py

这表明:

  • 基本工具(计算器、内存、天气)
  • STAC API工具(地理空间数据访问)
  • 创建自定义工具

框架使用

基本用法

from mcp_framework import MCPServer
from tools import calculator_tool, memory_tool

# Create server
server = MCPServer()

# Register tools
server.register_tool("calculator", calculator_tool)
server.register_tool("memory", memory_tool)

# Use tools
result = server.call_tool("calculator", {
    "operation": "add",
    "a": 10,
    "b": 5
})
print(result["result"])  # "10 add 5 = 15"

创建自己的工具

from mcp_framework import MCPServer
from typing import Dict, Any

def my_tool(args: Dict[str, Any], context: Dict[str, Any]) -> str:
    """My custom tool."""
    name = args.get("name", "World")
    return f"Hello, {name}!"

# Register and use
server = MCPServer()
server.register_tool("greeting", my_tool)
result = server.call_tool("greeting", {"name": "Student"})

示例工具包括

基本工具(tools/basic_tools.py)

  1. calculator_tool:简单的算术运算

    • 运算:加、减、乘、除
    • Args: operation, a, b
  2. memory_tool:存储和检索数据(上下文持久性示例)

    • 操作:存储、检索
    • Args: action, key, value (用于商店)
  3. weather_tool:来自OpenWeatherMap API的真实天气数据

    • Args: city (必填)
    • 需要:config.json中的API密钥: {"weather": {"api_key": "..."}}
    • 例子: {"city": "Beijing"}
    • 返回:简单格式,如“北京天气:晴,25°C”

STAC API工具(team1a/scarlett/stac_tools.py -学生开发工具示例)

  1. stac_list_collections_tool:列出可用的地理空间数据集

  2. stac_search_tool:搜索地理空间数据

    • Args: collection, bbox, date_start, date_end, limit
    • 例子: {"collection": "io-lulc-annual-v02", "bbox": [116.2, 39.8, 116.5, 40.0]}
  3. stac_download_tool:下载地理空间数据文件

    • Args: item_index, asset_type, output_dir
  4. stac_visualize_tool:创建交互式地图

    • Args: item_index, zoom, output_file, image_path (可选)

STAC API示例

from mcp_framework import MCPServer
import sys
import os

# Import STAC tools from student directory (example)
sys.path.insert(0, os.path.join('team1a', 'scarlett'))
from stac_tools import (
    stac_search_tool,
    stac_download_tool,
    stac_visualize_tool
)

server = MCPServer()
server.register_tool("stac_search", stac_search_tool)
server.register_tool("stac_download", stac_download_tool)
server.register_tool("stac_visualize", stac_visualize_tool)

# Search for Land Use/Land Cover data
result = server.call_tool("stac_search", {
    "collection": "io-lulc-annual-v02",
    "bbox": [-122.5, 37.7, -122.3, 37.8],  # California
    "date_start": "2023-01-01",
    "date_end": "2023-12-31"
})

# Download the data
result = server.call_tool("stac_download", {
    "item_index": 0,
    "asset_type": "data"
})

# Visualize on map
result = server.call_tool("stac_visualize", {
    "item_index": 0,
    "output_file": "map.html"
})

STAC热门系列

  • io-lulc-annual-v02:每年10米土地利用/土地覆盖(9类)
  • **sentinel-2-l2a**Sentinel-2卫星图像(10米分辨率)
  • landsat-c2-l2:陆地卫星图像(30米分辨率)
  • modis-09a1:MODIS地表反射率数据
  • naip:国家农业影像计划

理解边界框

边界框使用: [min_longitude, min_latitude, max_longitude, max_latitude]

示例(北京):

  • 经度:东经116.2°至东经116.5°
  • 纬度:北纬39.8°至40.0°
  • Bbox: [116.2, 39.8, 116.5, 40.0]

关键概念

1.工具

工具是具有签名的函数: func(args: Dict[str, Any], context: Dict[str, Any]) -> str

2.服务器

MCPServer类:

  • 注册工具
  • 执行工具
  • 在通话中保持上下文

3.背景

跨工具调用持续存在的共享数据:

server.set_context("key", "value")
value = server.get_context("key")

扩展框架

添加新工具

重要:有两个地方可以创建工具:

  1. tools/ 目录 -用于共享/通用工具(如 basic_tools.py 和 stac_tools.py)

    • 这些是每个人都可以使用的框架工具
    • 仅当需要在整个项目中共享工具时,才在此处添加工具
  2. 您的个人目录 -对于您自己的工具(例如。, team1a/scarlett/, team1b/joey/)

    • 这就是你应该创建自己的工具的地方
    • 每个学生都有自己的目录,以避免冲突
    • 看 CONTRIBUTING.md 详细说明

对于学生:在您的个人目录中创建您的工具(例如。, team1a/scarlett/my_tools.py)

例子:

# team1a/scarlett/my_tools.py
def my_tool(args: Dict[str, Any], context: Dict[str, Any]) -> str:
    param = args.get("param", "default")
    return f"Result: {param}"

然后在脚本中使用它:

from mcp_framework import MCPServer
import sys
sys.path.append('team1a/scarlett')  # Add your directory to path
from my_tools import my_tool

server = MCPServer()
server.register_tool("my_tool", my_tool)

需求

核心依赖关系:

  • Python 3.7+

对于STAC工具:

  • requests -HTTP请求
  • planetary-computer -Microsoft Planetary计算机的URL签名
  • rasterio -地理空间光栅I/O
  • folium -交互式地图
  • numpy -数值运算

API配置

该项目包括一个简单的API配置系统,从 config.json.

支持服务列表

天气API(OpenWeatherMap)

from config import get_api_key

# Get API key from config.json
api_key = get_api_key('weather')

在中配置 config.json:

{
  "weather": {
    "api_key": "your_api_key_here"
  }
}

API STAC

from config import get_api_url

# Get STAC API URL (defaults to Microsoft Planetary Computer)
stac_url = get_api_url('stac')

在中配置 config.json:

{
  "stac": {
    "api_url": "https://planetarycomputer.microsoft.com/api/stac/v1"
  }
}

认证

Microsoft Planetary Computer需要URL签名才能访问数据文件。这 planetary-computer 软件包会自动处理此问题,基本使用不需要帐户。

对于其他STAC API,请配置 STAC_API_URL 并且可选 STAC_API_KEY 在您的配置中。

学习路径

  1. 简单开始:运行 examples.py 查看基本工具的运行情况
  2. 研究实例:阅读 tools/basic_tools.py 了解工具结构
  3. 探索STAC:尝试使用不同集合的STAC工具
  4. 创建自己的:在您的个人目录中添加新工具(例如。, team1a/scarlett/)
  5. 扩展框架:修改 mcp_framework.py 如果需要(高级)

后续步骤

  • 通读 mcp_framework.py 了解核心框架
  • 学习 tools/basic_tools.py 用于简单的工具示例
  • 检查 team1a/scarlett/stac_tools.py API集成示例(学生开发的工具示例)
  • 在个人目录中创建自己的工具 (参见 CONTRIBUTING.md)
  • 尝试不同的STAC集合和区域

许可证

教育用途-专为学习和教授MCP概念而设计。