关于 MCP Framework
MCP Framework 是用 TypeScript 构建 MCP 服务的框架,面向需要快速搭建自定义 MCP 服务的开发者。它支持基于目录的工具、资源和提示词自动发现,并提供命令行工具用于创建项目和校验工具定义。
主要功能
- 01按目录自动发现并加载工具、资源和提示词
- 02支持 stdio、SSE 和 HTTP Stream 传输
- 03基于官方 MCP SDK 构建
- 04SSE 端点支持 OAuth 2.1、JWT 和 API Key 认证
- 05命令行工具用于创建项目和添加组件
适用场景
- 01使用 TypeScript 快速创建自定义 MCP 服务
- 02为工具的 Zod 参数模式校验描述信息并集成到 CI/CD 中
- 03将自建 MCP 服务接入 Claude Desktop 等客户端
MCP 相关
该框架用于开发 MCP 服务,可将工具、资源和提示词暴露给 MCP 客户端,并通过 stdio、SSE 或 HTTP Stream 与客户端通信。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
MCP 框架
MCP-Framework 是一个用于在 TypeScript 中优雅地构建 Model Context Protocol(MCP)服务的框架。
MCP-Framework 开箱即提供架构,并根据目录自动发现工具、资源和提示词。使用我们强大的 MCP 抽象,以优雅的方式定义工具、资源或提示词。我们的 CLI 让你轻松上手,构建自己的 MCP 服务。
功能
- 🛠️ 自动发现并加载工具、资源和提示词
- 支持多种传输方式(stdio、SSE、HTTP Stream)
- TypeScript 优先的开发体验,提供完整的类型安全
- 基于官方 MCP SDK 构建
- 易于使用的工具、提示词和资源基类
- 开箱即用的 SSE 端点身份验证(OAuth 2.1、JWT、API Key)
使用 MCP Framework 构建的项目
以下项目和服务使用 MCP Framework 构建:
一种加密货币打赏服务,可让 AI 助手直接通过聊天界面帮助用户向内容创作者发送加密货币打赏。该 MCP 服务支持:
- 检查用户的钱包类型
- 为用户/Agent 准备加密货币打赏,供其完成 有关各种客户端(Cursor、Sage、Claude Desktop)的设置说明,请参阅其 MCP 服务文档。
支持我们的工作
在此阅读完整文档
使用 mcp-framework 创建仓库
使用 CLI(推荐)
# Install the framework globally
npm install -g mcp-framework
# Create a new MCP server project
mcp create my-mcp-server
# Navigate to your project
cd my-mcp-server
# Your server is ready to use!
CLI 用法
该框架提供了功能强大的 CLI,用于管理 MCP 服务项目:
创建项目
# Create a new project
mcp create <your project name here>
# Create a new project with the new EXPERIMENTAL HTTP transport
Heads up: This will set cors allowed origin to "*", modify it in the index if you wish
mcp create <your project name here> --http --port 1337 --cors
选项:
--http:使用 HTTP 传输,而非默认的 stdio
--port :指定 HTTP 端口(默认值:8080)
--cors:启用允许所有来源(*)访问的 CORS
添加工具
# Add a new tool
mcp add tool price-fetcher
构建与验证
该框架提供全面的验证,确保工具文档完善且功能正常:
# Build with automatic validation (recommended)
npm run build
# Build with custom validation settings
MCP_SKIP_TOOL_VALIDATION=false npm run build # Force validation (default)
MCP_SKIP_TOOL_VALIDATION=true npm run build # Skip validation (not recommended)
验证工具
# Validate all tools have proper descriptions (for Zod schemas)
mcp validate
此命令会检查所有使用 Zod schema 的工具是否为每个字段都添加了描述。构建期间会自动运行验证,你也可以单独运行:
- ✅ 构建期间:
npm run build会自动验证工具 - ✅ 单独运行:使用
mcp validate手动验证 - ✅ 开发期间:使用
defineSchema()助手函数,即时获取反馈 - ✅ 运行时:服务启动时会验证工具
验证错误示例:
❌ Tool validation failed:
❌ PriceFetcher.js: Missing descriptions for fields in price_fetcher: symbol, currency.
All fields must have descriptions when using Zod object schemas.
Use .describe() on each field, e.g., z.string().describe("Field description")
将验证集成到 CI/CD:
{
"scripts": {
"build": "tsc && mcp-build",
"test": "jest && mcp validate",
"prepack": "npm run build && mcp validate"
}
}
添加提示词
# Add a new prompt
mcp add prompt price-analysis
添加资源
# Add a new resource
mcp add resource market-data
开发工作流
-
创建项目:
mcp create my-mcp-server cd my-mcp-server -
添加工具:
mcp add tool data-fetcher mcp add tool data-processor mcp add tool report-generator -
通过自动验证定义工具 schema:
// tools/DataFetcher.ts import { MCPTool, MCPInput as AddToolInput } from "mcp-framework";
import { z } from "zod";
const AddToolSchema = z.object({ a: z.number().describe("First number to add"), b: z.number().describe("Second number to add"), });
class AddTool extends MCPTool { name = "add"; description = "Add tool description"; schema = AddToolSchema;
async execute(input: AddToolInput) {
const result = input.a + input.b;
return Result: ${result};
}
}
export default AddTool;
4. **通过自动验证进行构建:**
```bash
npm run build # Automatically validates schemas and compiles
-
可选:单独运行验证:
mcp validate # Check all tools independently -
测试服务:
node dist/index.js # Server validates tools on startup -
添加到 MCP 客户端(参见下方的 Claude Desktop 示例)
专业提示:
- 开发期间使用
defineSchema(),即时获取反馈 - 构建过程会自动发现缺少描述的情况
- 服务启动时会在接受连接前验证所有工具
- 使用 TypeScript 的
MCPInput<this>自动补全功能,提升开发体验
与 Claude Desktop 搭配使用
本地开发
将此配置添加到 Claude Desktop 配置文件中:
MacOS:~/Library/Application Support/Claude/claude_desktop_config.json
Windows:%APPDATA%/Claude/claude_desktop_config.json
{
"mcpServers": {
"${projectName}": {
"command": "node",
"args":["/absolute/path/to/${projectName}/dist/index.js"]
}
}
}
发布后
将此配置添加到 Claude Desktop 配置文件中:
MacOS:~/Library/Application Support/Claude/claude_desktop_config.json
Windows:%APPDATA%/Claude/claude_desktop_config.json
{
"mcpServers": {
"${projectName}": {
"command": "npx",
"args": ["${projectName}"]
}
}
}
构建与测试
- 修改工具
- 运行
npm run build进行编译 - 服务启动时会自动加载工具
环境变量
该框架支持使用以下环境变量进行配置:
| 变量 | 描述 | 默认值 |
|---|---|---|
| MCP_ENABLE_FILE_LOGGING | 启用文件日志记录(true/false) | false |
| MCP_LOG_DIRECTORY | 存储日志文件的目录 | logs |
| MCP_DEBUG_CONSOLE | 在控制台显示调试级别的消息(true/false) | false |
使用示例:
# Enable file logging
MCP_ENABLE_FILE_LOGGING=true node dist/index.js
# Specify a custom log directory
MCP_ENABLE_FILE_LOGGING=true MCP_LOG_DIRECTORY=my-logs node dist/index.js
# Enable debug messages in console
MCP_DEBUG_CONSOLE=true node dist/index.js
快速开始
定义工具
MCP Framework 使用 Zod 模式定义工具输入,提供类型安全、验证和自动文档:
import { MCPTool, MCPInput } from "mcp-framework";
import { z } from "zod";
const AddToolSchema = z.object({
a: z.number().describe("First number to add"),
b: z.number().describe("Second number to add"),
});
class AddTool extends MCPTool {
name = "add";
description = "Add tool description";
schema = AddToolSchema;
async execute(input: MCPInput<this>) {
const result = input.a + input.b;
return `Result: ${result}`;
}
}
export default AddTool;
主要优点:
- ✅ 单一事实来源 - 在同一处定义类型和验证
- ✅ 自动类型推断 - TypeScript 类型根据你的模式自动推断
- ✅ 丰富的验证功能 - 利用 Zod 强大的验证功能
- ✅ 必需的描述 - 框架强制要求提供文档
- ✅ 更好的 IDE 支持 - 完整的自动补全和类型检查
- ✅ 代码更简洁 - 无需重复定义类型
高级 Zod 模式功能
该框架支持 Zod 的所有功能:
import { MCPTool, MCPInput } from "mcp-framework";
import { z } from "zod";
const AdvancedSchema = z.object({
// String constraints and formats
email: z.string().email().describe("User email address"),
name: z.string().min(2).max(50).describe("User name"),
website: z.string().url().optional().describe("Optional website URL"),
// Number constraints
age: z.number().int().positive().max(120).describe("User age"),
rating: z.number().min(1).max(5).describe("Rating from 1 to 5"),
// Arrays and objects
tags: z.array(z.string()).describe("List of tags"),
metadata: z.object({
priority: z.enum(['low', 'medium', 'high']).describe("Task priority"),
dueDate: z.string().optional().describe("Due date in ISO format")
}).describe("Additional metadata"),
// Default values
status: z.string().default('pending').describe("Current status"),
// Unions and enums
category: z.union([
z.literal('personal'),
z.literal('work'),
z.literal('other')
]).describe("Category type")
});
class AdvancedTool extends MCPTool {
name = "advanced_tool";
description = "Tool demonstrating advanced Zod features";
schema = AdvancedSchema;
async execute(input: MCPInput<this>) {
// TypeScript automatically knows all the types!
const { email, name, website, age, rating, tags, metadata, status, category } = input;
console.log(input.name.toUpperCase()); // ✅ TypeScript knows this is valid
console.log(input.age.toFixed(2)); // ✅ Number methods available
console.log(input.tags.length); // ✅ Array methods available
console.log(input.website?.includes("https")); // ✅ Optional handling
return `Processed user: ${name}`;
}
}
自动类型推断
MCPInput<this> 类型会根据你的模式自动推断正确的输入类型,无需手动定义类型:
class MyTool extends MCPTool {
schema = z.object({
name: z.string().describe("User name"),
age: z.number().optional().describe("User age"),
tags: z.array(z.string()).describe("User tags")
});
async execute(input: MCPInput<this>) {
// TypeScript automatically knows:
// input.name is string
// input.age is number | undefined
// input.tags is string[]
console.log(input.name.toUpperCase()); // ✅ TypeScript knows this is valid
console.log(input.age?.toFixed(2)); // ✅ Handles optional correctly
console.log(input.tags.length); // ✅ Array methods available
}
}
不再需要重复的接口或泛型类型参数!
模式验证与描述
所有模式字段都必须包含描述。这可确保工具文档完善,并为 MCP 客户端提供更好的用户体验。
该框架会在多个层级验证描述:
1. 构建时验证(推荐)
npm run build # Automatically validates during compilation
2. 开发时验证
使用 defineSchema 辅助函数,即时获得反馈:
import { defineSchema } from "mcp-framework";
// This will throw an error immediately if descriptions are missing
const MySchema = defineSchema({
name: z.string(), // ❌ Error: Missing description
age: z.number().describe("User age") // ✅ Good
});
3. 独立验证
mcp validate # Check all tools for proper descriptions
4. 运行时验证
服务会在启动时自动验证工具。
跳过验证(不推荐):
# Skip during build
MCP_SKIP_TOOL_VALIDATION=true npm run build
# Skip during development
NODE_ENV=production npm run dev
设置服务
import { MCPServer } from "mcp-framework";
const server = new MCPServer();
// OR (mutually exclusive!) with SSE transport
const server = new MCPServer({
transport: {
type: "sse",
options: {
port: 8080 // Optional (default: 8080)
}
}
});
// Start the server
await server.start();
传输配置
stdio 传输(默认)
如果未提供传输配置,则默认使用 stdio 传输:
const server = new MCPServer();
// or explicitly:
const server = new MCPServer({
transport: { type: "stdio" }
});
SSE 传输
使用服务器发送事件(SSE)传输:
const server = new MCPServer({
transport: {
type: "sse",
options: {
port: 8080, // Optional (default: 8080)
endpoint: "/sse", // Optional (default: "/sse")
messageEndpoint: "/messages", // Optional (default: "/messages")
cors: {
allowOrigin: "*", // Optional (default: "*")
allowMethods: "GET, POST, OPTIONS", // Optional (default: "GET, POST, OPTIONS")
allowHeaders: "Content-Type, Authorization, x-api-key", // Optional (default: "Content-Type, Authorization, x-api-key")
exposeHeaders: "Content-Type, Authorization, x-api-key", // Optional (default: "Content-Type, Authorization, x-api-key")
maxAge: "86400" // Optional (default: "86400")
}
}
}
});
HTTP Stream 传输
使用 HTTP Stream 传输:
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080, // Optional (default: 8080)
endpoint: "/mcp", // Optional (default: "/mcp")
responseMode: "batch", // Optional (default: "batch"), can be "batch" or "stream"
batchTimeout: 30000, // Optional (default: 30000ms) - timeout for batch responses
maxMessageSize: "4mb", // Optional (default: "4mb") - maximum message size
// Session configuration
session: {
enabled: true, // Optional (default: true)
headerName: "Mcp-Session-Id", // Optional (default: "Mcp-Session-Id")
allowClientTermination: true, // Optional (default: true)
},
// Stream resumability (for missed messages)
resumability: {
enabled: false, // Optional (default: false)
historyDuration: 300000, // Optional (default: 300000ms = 5min) - how long to keep message history
},
// CORS configuration
cors: {
allowOrigin: "*" // Other CORS options use defaults
}
}
}
});
响应模式
HTTP Stream 传输支持两种响应模式:
-
批处理模式(默认):收集响应并作为单个 JSON-RPC 响应发送。适用于典型的请求-响应模式,并且对大多数使用场景来说效率更高。
-
流模式:每个请求都会打开一个持久的 SSE 连接,所有响应都通过该连接发送。适用于长时间运行的操作,或服务需要针对单个请求发送多条消息的场景。
你可以根据具体需求配置响应模式:
// For batch mode (default):
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
responseMode: "batch"
}
}
});
// For stream mode:
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
responseMode: "stream"
}
}
});
HTTP Stream 传输功能
- 会话管理:自动跟踪和管理会话
- 流恢复:可选支持在连接丢失后恢复流
- 批处理:支持 JSON-RPC 批量请求/响应
- 全面的错误处理:提供包含 JSON-RPC 错误代码的详细错误响应
身份验证
MCP Framework 为 SSE 端点提供可选的身份验证。你可以选择 JWT、API Key、OAuth 2.1 身份验证,或自行实现自定义身份验证提供程序。
JWT 身份验证
import { MCPServer, JWTAuthProvider } from "mcp-framework";
import { Algorithm } from "jsonwebtoken";
const server = new MCPServer({
transport: {
type: "sse",
options: {
auth: {
provider: new JWTAuthProvider({
secret: process.env.JWT_SECRET,
algorithms: ["HS256" as Algorithm], // Optional (default: ["HS256"])
headerName: "Authorization" // Optional (default: "Authorization")
}),
endpoints: {
sse: true, // Protect SSE endpoint (default: false)
messages: true // Protect message endpoint (default: true)
}
}
}
}
});
客户端必须在 Authorization 标头中包含有效的 JWT 令牌:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
API Key 身份验证
import { MCPServer, APIKeyAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "sse",
options: {
auth: {
provider: new APIKeyAuthProvider({
keys: [process.env.API_KEY],
headerName: "X-API-Key" // Optional (default: "X-API-Key")
})
}
}
}
});
客户端必须在 X-API-Key 标头中包含有效的 API Key:
X-API-Key: your-api-key
OAuth 2.1 身份验证
MCP Framework 根据 MCP 规范(2025-06-18)支持 OAuth 2.1 身份验证,包括受保护资源元数据(RFC 9728)以及通过 JWKS 支持进行适当的令牌验证。
OAuth 身份验证适用于 SSE 和 HTTP Stream 传输,并支持两种验证策略:
JWT 验证(推荐,性能更佳)
JWT 验证会从授权服务器的 JWKS 端点获取公钥,并在本地验证令牌。这是速度最快的选项,因为每次请求都不需要与身份验证服务器进行往返通信。
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [
process.env.OAUTH_AUTHORIZATION_SERVER
],
resource: process.env.OAUTH_RESOURCE,
validation: {
type: 'jwt',
jwksUri: process.env.OAUTH_JWKS_URI,
audience: process.env.OAUTH_AUDIENCE,
issuer: process.env.OAUTH_ISSUER,
algorithms: ['RS256', 'ES256'] // Optional (default: ['RS256', 'ES256'])
}
}),
endpoints: {
initialize: true, // Protect session initialization
messages: true // Protect MCP messages
}
}
}
}
});
环境变量:
OAUTH_AUTHORIZATION_SERVER=https://auth.example.com
OAUTH_RESOURCE=https://mcp.example.com
OAUTH_JWKS_URI=https://auth.example.com/.well-known/jwks.json
OAUTH_AUDIENCE=https://mcp.example.com
OAUTH_ISSUER=https://auth.example.com
令牌内省(推荐,便于集中控制)
令牌内省通过调用授权服务器的内省端点来验证令牌。这种方式便于集中控制,在需要实时撤销令牌时很有用。
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "sse",
options: {
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [
process.env.OAUTH_AUTHORIZATION_SERVER
],
resource: process.env.OAUTH_RESOURCE,
validation: {
type: 'introspection',
audience: process.env.OAUTH_AUDIENCE,
issuer: process.env.OAUTH_ISSUER,
introspection: {
endpoint: process.env.OAUTH_INTROSPECTION_ENDPOINT,
clientId: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_CLIENT_SECRET
}
}
})
}
}
}
});
环境变量:
OAUTH_AUTHORIZATION_SERVER=https://auth.example.com
OAUTH_RESOURCE=https://mcp.example.com
OAUTH_AUDIENCE=https://mcp.example.com
OAUTH_ISSUER=https://auth.example.com
OAUTH_INTROSPECTION_ENDPOINT=https://auth.example.com/oauth/introspect
OAUTH_CLIENT_ID=mcp-server
OAUTH_CLIENT_SECRET=your-client-secret
OAuth 功能
- 符合 RFC 9728:在
/.well-known/oauth-protected-resource自动提供受保护资源元数据端点 - RFC 6750 WWW-Authenticate 标头:提供带质询标头的规范 OAuth 错误响应
- JWKS 密钥缓存:公钥缓存 15 分钟(可配置)
- 令牌内省缓存:内省结果缓存 5 分钟(可配置)
- 安全性:自动拒绝查询字符串中的令牌
- 声明提取:通过
AuthResult在工具处理程序中获取访问令牌声明
常用 OAuth 提供商
OAuth 提供商适用于任何符合 RFC 的 OAuth 2.1 授权服务器:
- Auth0:使用 Auth0 租户的 JWKS URI 和颁发者
- Okta:使用 Okta 授权服务器配置
- AWS Cognito:使用 Cognito 用户池的 JWKS 端点
- Azure AD / Entra ID:使用 Microsoft Entra ID 端点
- 自定义:任何符合 OAuth 2.1 的授权服务器
如需特定提供商的详细设置指南,请参阅 OAuth 设置指南。
客户端用法
客户端必须在 Authorization 标头中包含有效的 OAuth 访问令牌:
# Make a request with OAuth token
curl -X POST http://localhost:8080/mcp \
-H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..." \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
# Discover OAuth configuration
curl http://localhost:8080/.well-known/oauth-protected-resource
安全最佳实践
- 在生产环境中始终使用 HTTPS — OAuth 令牌绝不应通过未加密的连接传输
- 验证受众声明 — 防止令牌在不同服务之间重复使用
- 使用短期令牌 — 降低令牌泄露时的风险
- 启用令牌内省缓存 — 在保障安全的同时减轻授权服务器的负载
- 监控令牌错误 — 跟踪身份验证失败的尝试,以获取安全洞察
自定义身份验证
你可以通过实现 AuthProvider 接口来实现自己的身份验证提供商:
import { AuthProvider, AuthResult } from "mcp-framework";
import { IncomingMessage } from "node:http";
class CustomAuthProvider implements AuthProvider {
async authenticate(req: IncomingMessage): Promise<boolean | AuthResult> {
// Implement your custom authentication logic
return true;
}
getAuthError() {
return {
status: 401,
message: "Authentication failed"
};
}
}
文档 MCP 服务(@mcpframework/docs)
从任意 Fumadocs 站点或包含 llms.txt 的站点启动 MCP 文档服务,为 AI Agent 提供搜索、浏览和检索文档的工具。
快速入门(CLI)
# Scaffold a new docs MCP server project
npx create-docs-mcp my-api-docs
cd my-api-docs
# Configure your docs site URL
cp .env.example .env
# Edit .env → set DOCS_BASE_URL=https://docs.myapi.com
# Build and run
npm run build
npm start
快速入门(编程方式)
import { DocsServer, FumadocsRemoteSource } from "@mcpframework/docs";
const source = new FumadocsRemoteSource({
baseUrl: "https://docs.myapi.com",
});
const server = new DocsServer({
source,
name: "my-api-docs",
version: "1.0.0",
});
server.start();
源适配器
| 适配器 | 适用场景 | 搜索 |
|---|---|---|
FumadocsRemoteSource | Fumadocs 站点 | 原生 Orama 搜索,失败时回退 |
LlmsTxtSource | 任意包含 llms.txt 的站点 | 本地文本匹配 |
自定义 DocSource | 任意文档后端 | 由你实现 |
内置 MCP 工具
| 工具 | 描述 |
|---|---|
search_docs | 按关键字或短语搜索文档 |
get_page | 获取页面的完整 Markdown 内容 |
list_sections | 浏览文档树结构 |
添加到 MCP 客户端
# Claude Code
claude mcp add my-api-docs -- node /path/to/my-api-docs/dist/index.js
# Or with environment variable
claude mcp add my-api-docs -e DOCS_BASE_URL=https://docs.myapi.com -- node /path/to/my-api-docs/dist/index.js
如需 Claude Desktop / Cursor 配置和完整文档,请参阅 @mcpframework/docs README。
许可证
MIT
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。