返回市场
我的人工智能服务器

我的人工智能服务器

作者:eagurin9 星标更新:2025-03-15

项目介绍

MCP Server - 模型上下文协议API

FastAPI Python Poetry Prometheus GraphQL

MCP Server 是基于 FastAPI 实现的模型上下文协议 (MCP),提供了一个标准化接口用于大语言模型与应用程序之间的交互。

功能

  • 🚀 基于 FastAPI 和异步操作的高性能API
  • 🔄 完整支持 MCP,包括资源、工具、提示和采样
  • 📊 通过 Prometheus 和 Grafana 进行监控和指标收集
  • 🧩 通过简单接口扩展新工具
  • 📝 通过 GraphQL API 灵活处理数据
  • 💬 支持 WebSocket 实时交互
  • 🔍 通过集成 Elasticsearch 实现语义搜索
  • 🗃️ 使用 Redis 缓存以提高生产力
  • 📦 通过 Poetry 进行依赖管理,确保可靠的包管理

开始工作

安装

  1. 克隆仓库:

    git clone https://github.com/yourusername/myaiserv.git
    cd myaiserv
    
  2. 安装 Poetry(如果尚未安装):

    curl -sSL https://install.python-poetry.org | python3 -
    
  3. 通过 Poetry 设置依赖:

    poetry install
    

启动服务器

poetry run uvicorn app.main:app --host 0.0.0.0 --port  8000 --reload

或者通过工具:

just run

启动后,API 可在以下地址访问:http://localhost:8000

API 文档

项目结构

myaiserv/
├── app/
│   ├── core/             # MCP 基础组件
│   │   ├── base_mcp.py   # MCP 抽象类
│   │   └── base_sampling.py  # 采样基础类
│   ├── models/           # Pydantic 模型
│   │   ├── mcp.py        # MCP 数据模型
│   │   └── graphql.py    # GraphQL 模式
│   ├── services/         # 业务逻辑
│   │   └── mcp_service.py # MCP 服务
│   ├── storage/          # 数据存储
│   ├── tools/            # MCP 工具
│   │   ├── example_tool.py   # 工具示例
│   │   └── text_processor.py # 文本处理工具
│   ├── utils/            # 工具库
│   └── main.py           # FastAPI 入口点
├── app/tests/            # 测试
├── docs/                 # 文档
│   └── MCP_API.md        # API 描述
├── pyproject.toml        # Poetry 和工具配置
└── .justfile             # just 工具任务

可用工具

文件系统工具

用于文件系统操作的工具,支持读取、写入、删除和列出文件的操作。

curl -X POST "http://localhost:8000/tools/file_operations" \
     -H "Content-Type: application/json" \
     -d '{"operation": "list", "path": "."}'

天气工具

根据坐标获取天气数据的工具。

curl -X POST "http://localhost:8000/tools/weather" \
     -H "Content-Type: application/json" \
     -d '{"latitude": 37.7749, "longitude": -122.4194}'

文本分析工具

用于文本分析的工具,包括情感分析和总结。

curl -X POST "http://localhost:8000/tools/text_analysis" \
     -H "Content-Type: application/json" \
     -d '{"text": "Example text for analysis", "analysis_type": "sentiment"}'

文本处理器工具

用于文本处理的工具,包括格式化、统计计算、实体提取。

curl -X POST "http://localhost:8000/tools/text_processor" \
     -H "Content-Type: application/json" \
     -d '{"operation": "statistics", "text": "Example text", "stat_options": ["chars", "words"]}'

图像处理工具

支持调整大小、裁剪和应用滤镜的图像处理工具。

curl -X POST "http://localhost:8000/tools/image_processing" \
     -H "Content-Type: application/json" \
     -d '{"operation": "resize", "image_data": "base64...", "params": {"width": 800, "height": 600}}'

WebSocket API

连接到 WebSocket API:

const socket = new WebSocket("ws://localhost:8000/ws");

socket.onopen = () => {
  socket.send(JSON.stringify({
    type: "initialize",
    id: "my-request-id"
  }));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received:", data);
};

GraphQL API

通过 GraphQL 的查询示例:

# 获取所有工具的列表
query {
  getTools {
    name
    description
  }
}

# 执行工具
mutation {
  executeTool(input: {
    name: "text_processor",
    parameters: {
      operation: "statistics",
      text: "Example text for analysis"
    }
  }) {
    content {
      type
      text
    }
    is_error
  }
}

运行测试

运行测试使用 Poetry:

poetry run pytest

或者通过工具:

just test

Docker

通过 Docker Compose 安装和运行

docker compose up -d

启动单独的服务:

docker compose up -d web redis elasticsearch

与 LLM 集成

MCP Server 提供了与各种供应商的大语言模型集成的标准接口:

import httpx

async def query_mcp_with_llm(prompt: str):
    async with httpx.AsyncClient() as client:
        # 向 MCP 请求获取上下文和工具
        tools_response = await client.get("http://localhost:8000/tools")
        tools = tools_response.json()["tools"]

        # 向 LLM 发送请求,包含 MCP 上下文
        llm_response = await client.post(
            "https://api.example-llm.com/v1/chat",
            json={
                "messages": [
                    {"role": "system", "content": "You have access to the following tools:"},
                    {"role": "user", "content": prompt}
                ],
                "tools": tools,
                "tool_choice": "auto"
            }
        )

        return llm_response.json()

监控和指标

MCP Server 提供每个端点的 Prometheus 指标 /metrics,指标包括:

  • 每个工具的请求次数
  • 请求执行时间
  • 错误和异常

开发

对于代码格式化和 linter 检查:

just fmt
just lint

许可证

MIT 许可证