@tscodex/mcp-sdk
基于模型上下文协议创建LLM工具的TypeScript SDK
](https://www.npmjs.com/package/@tscodex/mcp-sdk) 
网站: tscodex.com
______________________________________________________________________
🎯 关于项目
@tscodex/mcp-sdk 是一个TypeScript SDK,用于快速创建MCP(模型上下文协议)服务器。该项目是构建LLM工具的基础,其中第一个工具是 MCP经理 --用于管理具有可视界面的MCP服务器的桌面应用程序。
TSCodex生态系统
┌─────────────────────────────────────────────────────────────┐
│ TSCodex Ecosystem │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ MCP SDK │───▶│ MCP Manager │───▶│ Cursor Bridge│ │
│ │ (Core) │ │ (Desktop) │ │ (Extension) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ └───────────────────┴────────────────────┘ │
│ │ │
│ ┌───────▼────────┐ │
│ │ MCP Servers │ │
│ │ (Examples) │ │
│ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘快速链接
📦 MCP经理 --用于管理MCP服务器的桌面应用程序\ 🌉 光标桥 --游标/VS代码扩展名
______________________________________________________________________
💡 项目本质
TSCodex 是创建LLM工具的平台。SDK提供了通过HTTP快速创建MCP服务器的核心功能,而不需要MCP Manager。服务器可以通过以下方式运行 npx,直接传递ENV参数。
主要特点
- ✅ 快速发展 --在几分钟内创建MCP服务器
- ✅ HTTP传输 --用于集成的标准HTTP
- ✅ 安全型API --使用TypeBox进行完整打字
- ✅ 灵活配置 --扩展和本地设置支持
- ✅ 安全 --内置保护机制
- ✅ 人工智能集成 --AI提供商的即用型客户端
- ✅ 多工作空间 --支持多个工作区
运作原理
┌─────────────────┐
│ MCP Server │ ← Built on SDK
│ (npm package) │
└────────┬────────┘
│
├───▶ Run via npx (standalone)
│ └─▶ Pass ENV parameters
│
└───▶ Run via MCP Manager
├─▶ Visual configuration
├─▶ Secrets management
├─▶ Access control
└─▶ Usage statistics______________________________________________________________________
🚀 MCP Manager——生态系统中的第一个工具
MCP经理 是一个管理MCP服务器的桌面应用程序,允许配置它们、传递机密、授权、AI代理以及为MCP创建动态工具/资源。
为什么选择MCP经理?
使用Cursor时,每个打开的项目都需要自己的工作区。例如 @tscodex/mcp图像 服务器处理图像,并需要当前项目根目录的路径。MCP管理器启用:
- 一台服务器,多个工作区 --一台服务器可以处理不同的项目
- 自动配准 --Cursor Bridge按项目路径自动注册工作区
- 代理 --每个工作区都有自己的服务器代理
- 完美封装 --工作空间之间完全隔离
工作区结构
┌─────────────────────────────────────────────────────────────┐
│ MCP Manager │
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Server │─────────▶│ Workspace A │ │
│ │ (Images) │ │ /project/foo │ │
│ └──────────────┘ └───────────────┘ │
│ │ │
│ │ ┌──────────────┐ │
│ └────────▶│ Workspace B │ │
│ │ /project/bar│ │
│ └──────────────┘ │
│ │
│ SDK receives headers from current workspace │
│ and allows one server to be used with different WS │
└─────────────────────────────────────────────────────────────┘MCP管理器功能
🎨 视觉界面
MCP Manager为服务器管理提供了一个功能齐全的UI:
- 元数据视图 --显示工具、资源、提示
- JSON配置模式 --自动设置检测
- UI配置 --便于配置的表格
- 生命周期管理 --启动、停止、重新启动服务器
🔐 秘密管理(3级)
┌─────────────────────────────────────────┐
│ Global Secrets │ ← Level 1
│ (Applied to all workspaces) │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Workspace Secrets │ ← Level 2
│ (Override global) │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Server Secrets │ ← Level 3
│ (Highest priority) │
└─────────────────────────────────────────┘安全:
- 存储在操作系统钥匙串中的秘密(Windows凭据存储区、macOS钥匙串、Linux GNOME钥匙圈)
- 从不以纯文本形式存储
- 仅通过环境变量传递
🛡️ 权限系统
灵活的门禁系统:
| 类别 | 控件 |
|---|---|
| 环境 | 系统环境变量 |
| 上下文 | 工作区/会话信息 |
| 秘密 | 可用密钥 |
| AI访问 | 访问AI代理 |
环境配置示例:
- ✅ 允许路径--
PATH,PATHEXT - ✅ 允许回家--
HOME,USERPROFILE - ✅ 允许节点--
NODE_*,npm_* - ⚙️ 自定义允许列表--特定变量
机密配置示例:
- 🔒 无——秘密不会传递
- 📋 Allowlist--仅指定密钥
- 🔓 所有——商店里的所有秘密
🤖 AI 代理
MCP Manager为MCP服务器提供了一个与OpenAI兼容的代理:
工作原理:
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ MCP Server │───▶│ AI Proxy │───▶│ AI Provider │
│ │ │ (Manager) │ │ (OpenAI/etc) │
└──────────────┘ └──────────────┘ └──────────────┘
│ │ │
│ │ │
└─▶ MCP_AI_PROXY_URL │ │
└─▶ MCP_AI_PROXY_TOKEN │
│
Keys are NOT passed
to server directly!特征:
- 支持任何与OpenAI兼容的API(OpenAI、OpenRouter、Ollama等)
- 通过基本URL和API密钥进行配置
- 服务器级别的访问控制
- 型号限制(允许的型号)
- 速率限制(每分钟最大请求数)
- 令牌统计 --使用完全透明
SDK中的用法:
import { getAIClient } from '@tscodex/mcp-sdk';
const ai = getAIClient();
if (await ai.isAvailable()) {
const result = await ai.complete('Summarize this text...');
}🛠️ MCP工具--动态服务器
MCP管理器包括一个内置 MCP工具服务器 它允许创建工具、资源和提示,而无需编写单独的包。
工具类型:
- 静态 --返回固定内容
- 超文本传输协议 --执行HTTP请求
- 函数 --执行JavaScript代码
人工智能辅助生成:
- ✨ 人工智能 创建工具/资源时的按钮
- 从自然语言生成定义
- 用于表单填写的AI代理集成
HTTP工具示例:
{
"name": "get_weather",
"description": "Get weather for a city",
"executor": {
"type": "http",
"method": "GET",
"url": "https://api.weather.com/v1/weather?city={{city}}&key={{SECRET_WEATHER_KEY}}"
}
}函数执行器中的可用上下文:
async (params, context) => {
// Request parameters
const { param1, param2 } = params;
// Session context
context.session.workspaceId; // Current workspace ID
context.session.projectRoot; // Project path
context.session.clientType; // Client type (cursor, claude-code)
// Request context
context.request.timestamp; // Unix timestamp
context.request.requestId; // Unique request ID
// Utilities
await context.utils.fetch(url, options);
context.utils.log(message);
return { result: "..." };
}📊 统计和监测
- AI使用 --请求和令牌总数
- 每台服务器故障 --每台服务器的统计数据
- 请求历史 --所有AI请求的日志
- 透明度 --资源使用情况的完全可见性
______________________________________________________________________
🌉 游标桥集成IDE
光标桥 是Cursor/VS Code的扩展,提供与MCP Manager的无缝集成。
桥梁特征
- 自动配准 --按项目路径在MCP Manager中自动注册工作区
- 同步 --将光标与MCP管理器同步
- 自动配置 --在本地注册MCP服务器代理
mcp.json - 完美封装 --工作空间之间完全隔离
运作原理
┌─────────────────┐
│ Cursor/VS Code │
│ (project open) │
└────────┬────────┘
│
│ 1. Bridge detects project path
▼
┌─────────────────┐
│ Cursor Bridge │
│ (Extension) │
└────────┬────────┘
│
│ 2. Registers workspace in MCP Manager
│ 3. Gets list of available servers
│ 4. Updates mcp.json
▼
┌─────────────────┐
│ MCP Manager │
│ (Desktop App) │
└─────────────────┘______________________________________________________________________
📦 SDK安装
npm install @tscodex/mcp-sdk要求:
- Node.js>=18.0.0
- TypeScript>=5.0.0
______________________________________________________________________
🚀 快速开始
最小服务器
import { McpServer, Type } from '@tscodex/mcp-sdk';
const server = new McpServer({
name: 'hello-server',
version: '1.0.0',
description: 'Simple hello world MCP server'
});
// Define schema with TypeBox
const HelloSchema = Type.Object({
name: Type.Optional(Type.String({
description: 'Name to greet',
default: 'World'
}))
});
// Register tool with automatic type inference
server.addTool({
name: 'hello-world',
description: 'Greet someone with a personalized message',
schema: HelloSchema,
handler: async (params, context) => {
// params is automatically typed as { name?: string }
const name = params.name || 'World';
return {
content: [{
type: 'text',
text: `Hello, ${name}!`
}]
};
}
});
// Initialize and start
await server.initialize();
await server.start();
console.log(`Server running on port ${server.serverPort}`);运行服务器
独立(通过npx):
npx @tscodex/mcp-imagesENV参数:
MCP_PORT=3848 MCP_PROJECT_ROOT=/path/to/project npx @tscodex/mcp-images通过MCP经理:
- 安装MCP管理器
- 通过UI添加服务器
- 配置工作区
- 启动服务器
______________________________________________________________________
📚 核心SDK功能
1.类型安全配置
import { McpServer, Type, Static } from '@tscodex/mcp-sdk';
const ConfigSchema = Type.Object({
apiKey: Type.String({ minLength: 10 }),
timeout: Type.Number({ default: 5000 }),
enabled: Type.Boolean({ default: true })
});
type Config = Static;
const server = new McpServer({
name: 'api-server',
version: '1.0.0',
description: 'API integration server',
configSchema: ConfigSchema,
loadConfig: async () => {
// Extension config is passed via process.env.MCP_CONFIG
const extensionConfig = process.env.MCP_CONFIG
? JSON.parse(process.env.MCP_CONFIG)
: {};
return {
timeout: 5000,
enabled: true,
...extensionConfig // Extension config takes priority
};
}
});
// Access configuration in handlers
server.addTool({
name: 'api-call',
schema: Type.Object({}),
handler: async (params, context) => {
// context.config contains full configuration including secrets
const timeout = context.config.timeout;
const apiKey = context.config.apiKey;
// ...
}
});2.身份验证和授权
import { McpServer, Type, Static } from '@tscodex/mcp-sdk';
enum Roles {
ADMIN = 'admin',
USER = 'user'
}
const SessionSchema = Type.Object({
email: Type.String({ format: 'email' }),
role: Type.Enum(Roles)
});
type Session = Static;
const server = new McpServer({
name: 'secure-server',
version: '1.0.0',
description: 'Server with role-based access',
auth: {
roles: {
admin: (session, context) => {
const allowedAdmins = context.config.adminEmails || [];
return session.role === Roles.ADMIN &&
allowedAdmins.includes(session.email);
},
user: async (session, context) => {
return session.role === Roles.USER;
}
},
sessionSchema: SessionSchema,
requireSession: true,
loadSession: async (token, context) => {
// Validate token and fetch user data
const response = await fetch(`${context.config.apiUrl}/validate-token`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` }
});
return await response.json() as Session;
}
}
});
// Tools with access control
server.addTool({
name: 'delete-file',
description: 'Delete a file (admin only)',
schema: Type.Object({ path: Type.String() }),
access: [Roles.ADMIN], // Only admins can use
handler: async (params, context) => {
// context.session is typed as Session
console.log(`Admin ${context.session.email} deleted ${params.path}`);
// ...
}
});3.资源和提示
// Register resource (URI automatically prefixed with server ID)
server.addResource({
uri: 'about', // Becomes: hello-server://about
name: 'About',
description: 'Server information',
handler: async (uri, context) => {
return {
contents: [{
uri,
mimeType: 'text/plain',
text: 'Server information...'
}]
};
}
});
// Register prompt
server.addPrompt({
name: 'explain-topic',
description: 'Explain a topic',
arguments: Type.Object({
topic: Type.String({ description: 'Topic to explain' })
}),
handler: async (params, context) => {
return {
messages: [{
role: 'user',
content: {
type: 'text',
text: `Explain ${params.topic}`
}
}]
};
}
});4.AI客户端
SDK提供了一个即用型客户端,用于通过MCP Manager与AI提供商合作:
import { getAIClient } from '@tscodex/mcp-sdk';
const ai = getAIClient();
// Always check availability before using
if (await ai.isAvailable()) {
// Simple completion
const result = await ai.complete('Summarize this text...');
// Or full chat API
const response = await ai.chat({
messages: [{ role: 'user', content: 'Hello!' }],
temperature: 0.7,
});
}工具中的用法:
server.addTool({
name: 'summarize',
description: 'Summarize text using AI',
schema: Type.Object({
text: Type.String({ description: 'Text to summarize' }),
}),
handler: async ({ text }) => {
// Graceful degradation when AI is not available
if (!await ai.isAvailable()) {
return {
content: [{ type: 'text', text: 'AI summarization is not available' }],
isError: true,
};
}
const summary = await ai.completeWithSystem(
'You are a helpful assistant that creates concise summaries.',
`Please summarize the following text:\n\n${text}`
);
return {
content: [{ type: 'text', text: summary }],
};
},
});5.多工作空间支持
SDK支持通过HTTP标头处理多个工作区:
server.addTool({
name: 'list-files',
schema: Type.Object({}),
handler: async (params, context) => {
// projectRoot automatically reflects per-request header
// or falls back to server-level MCP_PROJECT_ROOT
const root = context.projectRoot;
// workspaceId is available for logging/caching (optional)
const wsId = context.workspaceId;
if (!root) {
return { content: [{ type: 'text', text: 'No project root configured' }] };
}
// Files are resolved relative to the correct workspace
const files = await fs.readdir(root);
return {
content: [{ type: 'text', text: files.join('\n') }]
};
}
});HTTP标头:
X-MCP-Project-Root--工作区项目根目录的路径X-MCP-Workspace-Id--工作区标识符(可选)
______________________________________________________________________
🔀 按请求上下文(多工作区支持)
当多个工作区共享单个MCP服务器进程时,SDK支持 按请求上下文 通过HTTP标头。这允许每个请求都有自己的 projectRoot 和 workspaceId.
运作原理
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Workspace A │ │ MCP Gateway │ │ MCP Server │
│ /projects/foo │────▶│ (Proxy Layer) │────▶│ (Shared) │
└─────────────────┘ │ │ │ │
│ Adds headers: │ │ Reads via │
┌─────────────────┐ │ X-MCP-Project- │ │ AsyncLocal │
│ Workspace B │────▶│ Root │ │ Storage │
│ /projects/bar │ │ X-MCP-Workspace│ │ │
└─────────────────┘ │ -Id │ │ │
└─────────────────┘ └─────────────────┘上下文优先级
projectRoot 按以下优先级解决:
- 按请求标头 (
X-MCP-Project-Root)--最高优先级 - 服务器级环境 (
MCP_PROJECT_ROOT) - 未定义 如果两者都没有设置
______________________________________________________________________
🌐 扩展集成
SDK旨在与Cursor/VCode扩展无缝协作。
元数据模式(--meta 旗帜)
SDK支持元数据模式进行扩展集成。当开始时 --meta 或 --metadata 标志:
- 服务器仅向输出JSON元数据
stdout(无日志) - 所有日志都被重定向到
stderr - 服务器在输出元数据后退出(不启动HTTP服务器)
- 可用于扩展在不启动服务器的情况下发现服务器功能
用途:
node dist/index.js --meta
# or
node dist/index.js --metadata环境变量
扩展通过环境变量自动传递配置:
MCP_PORT-服务器端口(默认:3848)MCP_HOST-服务器主机(默认值:“0.0.0.0”)MCP_PROJECT_ROOT-工作区根目录MCP_CONFIG-配置为JSON字符串MCP_AUTH_TOKEN-身份验证令牌(用于启用身份验证的服务器)MCP_PATH-MCP端点路径(默认值:“/MCP”)MCP_AI_PROXY_URL-AI代理端点URL(用于AI客户端)MCP_AI_PROXY_TOKEN-AI代理身份验证令牌(用于AI客户端)
重要提示: 只有具有以下条件的环境变量 MCP_ 前缀被加载到应用程序配置中(通过 loadConfig).这可以防止意外暴露系统环境变量。
扩展端点
SDK会自动为扩展创建端点:
GET /health-使用服务器信息进行健康检查GET /gateway/metadata-获取服务器元数据(工具、资源、提示、配置模式)POST /gateway/config/project-root-更新项目根目录GET /gateway/config/current-获取当前配置(仅限公共)POST /gateway/config-动态更新配置(深度合并)
______________________________________________________________________
🔐 安全
内置保护机制
- ✅ 输入验证 --所有参数的TypeBox架构
- ✅ 路径消毒 --防止路径遍历攻击
- ✅ 速率限制 --请求速率限制
- ✅ 请求大小验证 --防御DoS攻击
- ✅ 秘密管理 --安全的秘密存储
- ✅ 权限系统 --精细的访问控制
最佳实践
- 始终验证用户输入 使用TypeBox模式
- 使用
safePath()用于文件操作以防止路径遍历 - 启用速率限制 用于生产服务器
- 对文件名进行消毒 使用
sanitizeFilename() - 验证请求大小 防止DoS攻击
- 使用HTTPS 生产中(在运输级别配置)
- 实施正确的身份验证 用于敏感操作
______________________________________________________________________
📖 api参考
McpServer
主服务器类。
构造函数
interface McpServerOptions {
// REQUIRED
name: string; // Unique server name (must start with Latin letter)
version: string; // Version (semver)
description: string; // Server description
// OPTIONAL
id?: string; // Server ID for resource prefix (auto-generated from name)
configSchema?: TSchema; // TypeBox schema for configuration
loadConfig?: () => Promise; // Load local configuration
auth?: AuthConfig; // Authentication config
mcpPath?: string; // MCP endpoint path (default: '/mcp')
corsOptions?: CorsOptions; // CORS configuration
httpOptions?: ServerHttpOptions; // HTTP server options
securityOptions?: ServerSecurityOptions; // Security options
handlerOptions?: ServerHandlerOptions; // Handler timeout options
errorHandler?: ErrorHandler; // Error handler
logger?: Logger; // Custom logger
}方法
// Initialization
await server.initialize(): Promise;
await server.start(): Promise;
await server.stop(): Promise;
// Tool registration
server.addTool(config: ToolConfig): void;
// Resource registration
server.addResource(config: ResourceConfig): void;
// Prompt registration
server.addPrompt(config: PromptConfig): void;
// Access methods
server.getConfig(): TConfig;
server.getProjectRoot(): string | undefined;
server.getSession(): TSession | undefined;
server.getTools(): string[];
server.getResources(): string[];
server.getPrompts(): string[];
server.getMetadata(): ServerMetadata; // Get server metadata
// Properties
server.serverId: string; // Server ID (resource prefix)
server.serverPort: number; // Server port
server.serverHost: string; // Server host
server.running: boolean; // Is server running______________________________________________________________________
📝 例子
检查 examples/ 完整示例目录:
- basic-server.ts -最小服务器设置
- 带配置ts -配置管理
- with-auth.ts -身份验证和授权
- 带手柄 -自定义错误处理
- file-server.ts -文件操作示例
- with-ai-client.ts -AI客户端集成示例
运行示例:
tsx examples/basic-server.ts
tsx examples/with-config.ts
tsx examples/with-auth.ts______________________________________________________________________
🏗️ 建筑
初始化流程
1. Extension starts process
↓ (env vars: MCP_PORT, MCP_HOST, MCP_PROJECT_ROOT, MCP_CONFIG, MCP_AUTH_TOKEN)
2. new McpServer(options)
- Reads port/host/projectRoot from env vars
- Creates HTTP Server
- Creates MCP Server instance
3. server.initialize()
- Loads configuration from MCP_CONFIG
- Calls loadConfig() for local settings
- Merges configurations (Extension takes priority)
- Validates via configSchema
- Loads session if auth is configured
- Filters tools/resources/prompts by access
- Sets up Extension endpoints
- Registers MCP handlers
4. server.addTool/addResource/addPrompt
- Register functionality
5. server.start()
- Starts HTTP Server
- Sets up graceful shutdown handlers
6. Server running
- Handles MCP requests
- Provides Extension endpoints
- Configuration and session available via context项目结构
@tscodex/mcp-sdk/
├── src/
│ ├── server.ts # McpServer class
│ ├── types.ts # TypeScript types
│ ├── config.ts # Configuration management
│ ├── transport.ts # HTTP transport
│ ├── security.ts # Security utilities
│ ├── extension.ts # Extension types
│ ├── ai-client.ts # AI Client
│ └── index.ts # Main exports
├── examples/ # Example servers
└── dist/ # Compiled output______________________________________________________________________
🍎 平台说明
视窗
- ✅ 全力支持
- ✅ 使用Windows凭据存储区获取机密
- ✅ 无需额外设置
macOS
- ⚠️ 需要代码签名 用于分配
- ✅ 使用钥匙链获取秘密
- 📝 开发人员可以自己生成签名,因为所有必要的资源都可用
- 📧 如果有人想帮助签名或合作,请联系我
Linux
- ✅ 全力支持
- ✅ 需要
libsecret-1-devGNOME钥匙圈或KDE钱包 - 📦 安装:
sudo apt install libsecret-1-dev gnome-keyring
______________________________________________________________________
🔗 链接
主要项目
示例服务器
- @tscodex/mcp图像 --图像处理、股票搜索、人工智能生成
- @tscodex/mcp服务器示例 --SDK示例和最佳实践
文档
______________________________________________________________________
📄 许可证
MIT© 生命
______________________________________________________________________
🤝 协作
如果你想帮助这个项目,特别是在macOS的代码签名或其他方面,请联系我!
______________________________________________________________________
版本: 0.0.6\ 状态:生产就绪
