模型上下文协议实现

一个基于FastAPI和Next.js的模型上下文协议实现,支持SSE、Streamable HTTP和Stdio三种传输方式。

  • by jaehyodev
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 jaehyodev/mcp-protocol

使用说明

MCP协议(FastAPI+Next.js)

Model Context Protocol实现-FastAPI后端和Next.js前端

🎯 项目概述

该项目使用FastAPI实现了模型上下文协议(MCP)的三种传输方式。

  • 前端:Next.js 16+React 19+TailwindCSS 4
  • 后端:FastAPI+Pydantic+uvicorn
  • 包管理器:
    • 前端:纱线(离线镜像)
    • 后端:uv

📂 项目结构

mcp-protocol/
├── frontend/                # Next.js 프론트엔드
│   ├── src/
│   │   ├── app/
│   │   │   ├── api/stdio/route.ts      # Stdio API Route
│   │   │   ├── mcpClientSSE.ts         # SSE 클라이언트
│   │   │   └── mcpClientStreamableHttp.ts  # HTTP 클라이언트
│   │   ├── components/                 # UI 컴포넌트
│   │   ├── hooks/                      # React 훅
│   │   └── types/                      # TypeScript 타입
│   ├── package.json
│   └── .yarnrc                        # Yarn offline mirror
│
├── backend/                 # FastAPI 백엔드
│   ├── src/
│   │   ├── main.py                    # FastAPI 앱
│   │   ├── models/
│   │   │   └── jsonrpc.py            # Pydantic 모델
│   │   ├── routers/
│   │   │   ├── sse.py                # SSE 라우터
│   │   │   └── http.py               # Streamable HTTP 라우터
│   │   └── stdio_server.py           # Stdio 독립 서버
│   ├── pyproject.toml                # uv 프로젝트 설정
│   └── .python-version               # Python 버전
│
└── README.md

🚀 安装和运行

前提条件

  • Node.js 18+(前端)
  • python 3.11+(后端)
  • 纱线 1.22+(前端软件包管理)
  • 紫外线 (后端包管理)

1.Backend设置(FastAPI)

cd backend

# uv로 의존성 설치
uv sync

# 개발 서버 실행 (포트 8000)
uv run uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

运行单独的Stdio服务器 (可选):

# Stdio 서버 (포트 없음, stdin/stdout)
uv run python src/stdio_server.py stdio

2.设置Frontend(Next.js)

cd frontend

# Yarn으로 의존성 설치
yarn install

# 개발 서버 실행 (포트 3000)
yarn dev

3.浏览器连接

  • 前端:http://localhost:3000
  • 后端API文档:http://localhost:8000/docs
  • 后端健康:http://localhost:8000/health

📡 按传输方式划分的端点

SSE(服务器发送事件)

方法 端点 说明
职位 /api/sse/messages 客户端→服务器请求(initialize、echo等)
得到 /api/sse/stream 服务器→客户端通知流(每5秒)

使用示例:

# Initialize
curl -X POST http://localhost:8000/api/sse/messages \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":"1","method":"initialize","params":{}}'

# SSE 스트림 구독
curl -N http://localhost:8000/api/sse/stream

可流式传输的HTTP

方法 端点 说明
职位 /api/http 请求处理(单个或流式处理)
得到 /api/http SSE通知(可选长期连接)

使用示例:

# 단일 응답 (Echo)
curl -X POST http://localhost:8000/api/http \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{"jsonrpc":"2.0","id":"1","method":"echo","params":{"message":"hello"}}'

# 스트리밍 응답 (Stream)
curl -X POST http://localhost:8000/api/http \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"jsonrpc":"2.0","id":"1","method":"stream","params":{}}'

# GET SSE 알림
curl -N http://localhost:8000/api/http

工作室

Stdio不由FastAPI直接处理,而是由Next.js API Route(/api/stdio)充当代理。

# Stdio 서버를 별도로 실행한 후
uv run python src/stdio_server.py stdio

# Next.js API Route를 통해 통신
# (브라우저 UI에서 Stdio 탭 사용)

🔧 开发命令

后端

cd backend

# 의존성 설치
uv sync

# 개발 서버 (hot reload)
uv run uvicorn src.main:app --reload

# Stdio 서버
uv run python src/stdio_server.py stdio

# 테스트 (추후)
uv run pytest

# 린트
uv run ruff check src/

前端

cd frontend

# 의존성 설치
yarn install

# 개발 서버
yarn dev

# 프로덕션 빌드
yarn build

# 프로덕션 서버
yarn start

📝 JSON-RPC 2.0方法

通用方法

方法 参数 响应 说明
initialize {protocolVersion, capabilities, clientInfo} {protocolVersion, serverInfo} 协议初始化
echo {message: string} {message: string} 消息回声
resources/list {} {resources: [...]} 资源列表(仅SSE)
tools/list {} {tools: [...]} 工具列表(仅SSE)

流方法(仅HTTP)

方法 参数 响应 说明
stream {} SSE Stream 每隔1秒发送5个区块

🎨 UI配置

在浏览器中 http://localhost:3000 连接时:

  1. 切换选项卡:标准/SSE/流式HTTP
  2. 控制按钮:
    • 标准:热,回声
    • SSE:SSE连接,Init,Echo
    • HTTP:Init、Echo、Stream、GET SSE连接
  3. 控制台日志:显示实时请求/响应日志

🔄 与现有项目的区别

主题 mcp-client(现有) mcp-protocol(新)
后端 Python http.server FastAPI
端口SSE(8001)、HTTP(8002)、集成端口(8000)
端点 /messages, /sse /api/sse/messages, /api/sse/stream
类型验证 手动 Pydantic自动验证
文档 无 Swagger UI(/docs)
异步基于线程基于asyncio

🧪 测试

手动测试

  1. Backend运行: uv run uvicorn src.main:app --reload
  2. 启动Frontend: yarn dev
  3. 在浏览器中测试每个选项卡:
    • SSE:按照连接→Init→Echo的顺序进行测试
    • HTTP:Init→Echo→Stream→GET SSE连接

API测试(curl)

# SSE Initialize
curl -X POST http://localhost:8000/api/sse/messages \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":"test-1","method":"initialize","params":{"protocolVersion":"2025-06-18"}}'

# HTTP Stream
curl -N -X POST http://localhost:8000/api/http \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"jsonrpc":"2.0","id":"stream-1","method":"stream"}'

📚 参考文档

📄 许可证

麻省理工学院