mcp配置ts
用于发现、添加、验证和同步MCP服务器配置的类型库和CLI。
](https://www.npmjs.com/package/mcp-config-ts) ](https://www.npmjs.com/package/mcp-config-ts)  ](https://nodejs.org) 
______________________________________________________________________
描述
mcp-config-ts 管理 .mcp.json MCP兼容工具(Claude Code、Claude Desktop、Cursor、Windsurf、Cline)用于连接到MCP服务器的配置文件。它同时提供了编程的TypeScript API和CLI(mcp-config)对于整个配置生命周期:加载和解析配置文件,添加和删除服务器条目,在多个严格级别上验证配置,以及跨项目同步服务器。
该库处理两种MCP传输类型-- 标准 (通过以下命令生成的子进程 npx 或 node)以及 超文本传输协议 (URL上的远程服务器)--并在从磁盘加载配置时自动推断传输类型。配置文件中的非MCP键在加载/保存往返过程中会被保留,因此特定于工具的设置(如Claude Desktop首选项)永远不会丢失。
安装
npm install mcp-config-ts或者直接使用npx运行CLI:
npx mcp-config-ts validate要求: Node.js>=18
快速开始
import {
loadConfig,
saveConfig,
validateConfig,
addServer,
removeServer,
getServer,
listServers,
createManager,
} from 'mcp-config-ts';
// Load a config file (synchronous)
const config = loadConfig('.mcp.json');
// Validate the config
const result = await validateConfig(config, { level: 3 });
console.log(result.valid); // true or false
console.log(result.completenessScore); // 0-100
// Add a server (mutates config in place)
addServer(config, 'my-server', {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir'],
});
// Save the config (synchronous, creates parent dirs automatically)
saveConfig(config);
// Remove a server
removeServer(config, 'my-server');
// List all server names (sorted alphabetically)
const names = listServers(config); // ['filesystem', 'github', ...]
// Get a single server entry
const entry = getServer(config, 'github'); // ServerEntry | undefined特性
- 加载并解析
.mcp.json具有自动传输类型推断(stdio与HTTP)的文件。 - 往返安全 --配置文件中的非MCP密钥在加载和保存操作中都会被保留。
- 多级验证 --检查JSON语法(级别1)、模式结构(级别2)和传输一致性,包括URL格式和命令检查(级别3)。
- 完整性评分 --0-100分,反映配置质量,减去错误(-30)和警告(-10)。
- 服务器CRUD --使用键入的错误处理添加、删除、获取、列出和检查服务器条目的存在。
- 有礼貌的经理 --
createManager()提供了一个高级接口,封装了加载/保存/验证/修改操作。 - 键入错误 --所有错误条件都抛出具有机器可读性的特定错误子类
code用于程序化处理的属性。 - 零运行时依赖关系 --只有Node.js内置模块(
fs,path,os,crypto).
API 参考
loadConfig(configPath?: string): MCPConfig
同步加载和解析MCP配置文件。
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
configPath | string | '.mcp.json' (从cwd解析) | 配置文件的路径 |
退货: MCPConfig --解析后的配置对象。
行为:
- 同步读取文件并将其解析为JSON。
- 推断
type: 'stdio'对于带有a的条目command现场,type: 'http'对于带有a的条目url现场。 - 无
mcpServers密钥保存在config._otherKeys用于往返写作。 - 如果
mcpServers缺失,返回空servers物体(不投掷)。
投掷:
ConfigNotFoundError--文件不存在或无法读取。ConfigParseError--文件内容不是有效的JSON。
const config = loadConfig('/path/to/project/.mcp.json');
console.log(config.filePath); // absolute path
console.log(config.servers); // Record______________________________________________________________________
saveConfig(config: MCPConfig): void
写一个 MCPConfig 对象同步到磁盘。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
config | MCPConfig | 要写入的配置对象(使用 config.filePath 作为目的地) |
行为:
- 自动创建父目录(
mkdirSync随着recursive: true). - 剥去
type每个服务器条目中的字段(传输类型是推断的,不存储在磁盘上)。 - 合并
_otherKeys返回到输出中,因此保留了非MCP字段。 - 使用2空格缩进和尾随换行符写入JSON。
addServer(config, 'new-server', { type: 'stdio', command: 'node', args: ['server.js'] });
saveConfig(config); // writes to config.filePath______________________________________________________________________
validateConfig(config: MCPConfig, options?: { level?: 1 | 2 | 3 }): Promise
验证 MCPConfig object并返回a ValidationResult.
参数:
| 参数 | 类型 | 默认值 | 说明 | ||
|---|---|---|---|---|---|
config | MCPConfig | -- | 要验证的配置对象 | ||
options.level | `1 \ | 2 \ | 3` | 3 | 验证严格程度 |
验证级别:
| 级别 | 检查 |
|---|---|
| 1 | 仅JSON语法 |
| 2 | JSON语法+模式结构(存在mcpServers,条目有效) |
| 3 | 所有检查,包括URL格式验证和非空命令警告 |
退货: Promise 具有以下形状:
interface ValidationResult {
valid: boolean; // true only when no error-severity checks fail
configPath: string; // path to the validated config file
checks: ValidationCheck[]; // individual check results
summary: {
total: number;
passed: number;
failed: number;
warnings: number;
};
completenessScore: number; // 0-100
}完整性得分: 从100开始,每个错误严重性故障减少30个,每个警告严重性故障降低10个,固定为\[0,100\]。
const result = await validateConfig(config, { level: 2 });
if (!result.valid) {
for (const check of result.checks.filter(c => !c.passed)) {
console.error(`[${check.severity}] ${check.id}: ${check.message}`);
}
}______________________________________________________________________
validateJsonSyntax(filePath: string): ValidationCheck
检查文件是否包含有效的JSON。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
filePath | string | 要检查的文件的绝对路径 |
退货: A. ValidationCheck 随着 id: 'json-syntax' 和 severity: 'error'.
______________________________________________________________________
validateSchema(config: MCPConfig): ValidationCheck[]
对解析后的配置运行架构级验证检查。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
config | MCPConfig | 要验证的已解析配置 |
退货: 一系列 ValidationCheck 对象包括:
| 检查ID | 严重性 | 描述 |
|---|---|---|
has-mcp-servers | error | mcpServers密钥存在并且是一个对象 |
server-entries-valid | 错误 | 所有条目都具有有效的传输类型 |
no-empty-names | 警告 | 没有空字符串的服务器名称 |
url-format | 警告 | 所有HTTP服务器URL都以开头 http:// 或 https:// |
command-non-empty | 警告 | 所有stdio服务器命令都是非空字符串 |
______________________________________________________________________
addServer(config: MCPConfig, name: string, entry: ServerEntry): void
将服务器条目添加到配置中。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
config | MCPConfig | 要更改的配置 |
name | string | 服务器名称(键入 mcpServers) |
entry | ServerEntry | 要添加的服务器条目 |
投掷: ServerExistsError 如果具有该名称的服务器已存在。
______________________________________________________________________
removeServer(config: MCPConfig, name: string): void
从配置中删除服务器条目。
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
config | MCPConfig | 要更改的配置 |
name | string | 要删除的服务器名称 |
投掷: ServerNotFoundError 如果服务器不存在。
______________________________________________________________________
getServer(config: MCPConfig, name: string): ServerEntry | undefined
返回给定名称的服务器条目,或 undefined 如果没有找到。
______________________________________________________________________
listServers(config: MCPConfig): string[]
返回配置中所有服务器名称的排序数组。
______________________________________________________________________
createManager(options?: ManagerOptions): ConfigManager
创建一个有状态的配置管理器,在单个配置文件上封装加载、保存、验证和CRUD操作。
参数:
| 参数 | 类型 | 默认值 | 说明 | ||||
|---|---|---|---|---|---|---|---|
options.configPath | string | '.mcp.json' | 配置文件的路径 | ||||
options.validationLevel | `1 \ | 2 \ | 3 \ | 4 \ | 5` | -- | 默认验证级别 |
重要提示: 呼叫 manager.load() 在任何其他方法之前。突变(add, remove)在记忆中,直到 manager.save() 被称为。
ConfigMgr方法
| 方法 | 签名 | 描述 | |
|---|---|---|---|
load | (): Promise | 从磁盘加载配置 | |
save | (): Promise | 将当前配置保存到磁盘 | |
getConfig | (): MCPConfig | 返回加载的配置对象 | |
list | (): string[] | 返回服务器名称的排序数组 | |
get | `(name: string): ServerEntry \ | undefined` | 按名称返回服务器条目 |
has | (name: string): boolean | 检查服务器是否存在 | |
add | (name: string, entry: ServerEntry): void | 添加服务器(throws ServerExistsError 如果存在) | |
addFromRegistry | (name: string, envValues?: Record): void | 从内置注册表添加服务器 | |
remove | (name: string): void | 删除服务器(throws ServerNotFoundError 如果缺失) | |
validate | (options?: { level?: 1-5 }): Promise | 验证当前配置 |
const manager = createManager({ configPath: '.mcp.json' });
await manager.load();
manager.add('github', {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! },
});
const result = await manager.validate();
console.log(result.completenessScore);
await manager.save();配置
配置文件格式
MCP配置文件是JSON文件,具有顶级 mcpServers 按键:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"],
"env": {}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxxxxxxxxxxx"
}
},
"remote-api": {
"url": "https://mcp.example.com/api",
"headers": {
"Authorization": "Bearer token"
}
}
}
}Stdio服务器输入字段
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
command | string | 是 | 可执行文件可运行(npx, node, uvx, docker) |
args | string[] | 否 | 传递给命令的参数 |
env | Record | 否 | 子流程的环境变量 |
cwd | string | 否 | 子流程的工作目录 |
disabled | boolean | 否 | 如果为true,则服务器已配置但未启动 |
HTTP服务器输入字段
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
url | string | 是 | MCP服务器HTTP端点的URL |
headers | Record | 否 | 随请求一起发送的HTTP标头 |
disabled | boolean | 否 | 如果为true,则服务器已配置但未连接 |
配置文件位置
| 位置 | 作用域 | 使用者 | 路径 |
|---|---|---|---|
| 项目配置 | 每个项目 | 克劳德代码 | ` |
| /.mcp.json` | |||
| 克劳德桌面 | 全球 | 克劳德桌面 | ~/.claude/claude_desktop_config.json |
| 游标 | 每个用户 | 游标IDE | ~/.cursor/mcp.json |
| Windsurf | 每位用户 | Windsurf | ~/.codeium/windsurf/mcp_config.json |
| Cline | 每位用户 | Cline(VS代码) | ~/.cline/mcp_settings.json |
所有位置都使用相同的 mcpServers 格式。包含其他非MCP密钥(如Claude Desktop配置)的文件得到了安全处理——在加载和保存操作中保留了额外的密钥。
错误处理
所有错误都会扩展 MCPConfigError,其本身延伸 Error每个错误都有一个 code 用于程序匹配的字符串属性。
| 错误类别 | 代码 | 抛出时 |
|---|---|---|
MCPConfigError | *(变化)* | 所有包错误的基类 |
ConfigNotFoundError | CONFIG_NOT_FOUND | loadConfig() 当文件不存在时 |
ConfigParseError | CONFIG_PARSE_ERROR | loadConfig() 当文件不是有效的JSON时 |
ServerExistsError | SERVER_EXISTS | addServer() / manager.add() 当名字被取下时 |
ServerNotFoundError | SERVER_NOT_FOUND | removeServer() / manager.remove() 当名字缺失时 |
ValidationError | VALIDATION_ERROR | 当验证在关键级别失败时 |
错误属性
import { ConfigNotFoundError, ConfigParseError, MCPConfigError } from 'mcp-config-ts';
try {
loadConfig('/missing/.mcp.json');
} catch (err) {
if (err instanceof ConfigNotFoundError) {
console.error(err.code); // 'CONFIG_NOT_FOUND'
console.error(err.configPath); // '/missing/.mcp.json'
}
}
try {
loadConfig('/bad-json/.mcp.json');
} catch (err) {
if (err instanceof ConfigParseError) {
console.error(err.code); // 'CONFIG_PARSE_ERROR'
console.error(err.configPath); // '/bad-json/.mcp.json'
console.error(err.parseError); // original SyntaxError, if available
}
}捕获所有包错误
try {
// any mcp-config-ts operation
} catch (err) {
if (err instanceof MCPConfigError) {
console.error(`[${err.code}] ${err.message}`);
}
}高级用法
往返保护
当使用包含非MCP密钥的配置文件(如Claude Desktop的全局配置)时,库会自动保留这些密钥:
// Original file: { "theme": "dark", "mcpServers": { ... } }
const config = loadConfig('claude_desktop_config.json');
addServer(config, 'new-server', { type: 'stdio', command: 'node', args: ['srv.js'] });
saveConfig(config);
// Written file still contains "theme": "dark"状态配置管理器
这 ConfigManager 当您需要对同一配置文件执行多个操作时,它很有用:
const manager = createManager({ configPath: '.mcp.json' });
await manager.load();
// Check before mutating
if (!manager.has('github')) {
manager.add('github', {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! },
});
}
// Validate before saving
const result = await manager.validate({ level: 3 });
if (result.valid) {
await manager.save();
} else {
console.error('Validation failed:', result.summary);
}CI中的验证
将配置验证作为CI管道的一部分运行,以便在错误配置到达主分支之前将其捕获:
import { loadConfig, validateConfig } from 'mcp-config-ts';
const config = loadConfig('.mcp.json');
const result = await validateConfig(config, { level: 3 });
if (!result.valid) {
console.error(`Validation failed (score: ${result.completenessScore}/100)`);
for (const check of result.checks.filter(c => !c.passed)) {
console.error(` [${check.severity}] ${check.id}: ${check.message}`);
}
process.exit(1);
}程序化配置生成
以编程方式为项目脚手架或自动化构建配置文件:
import { saveConfig } from 'mcp-config-ts';
import type { MCPConfig } from 'mcp-config-ts';
const config: MCPConfig = {
servers: {
filesystem: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'],
},
github: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! },
},
},
filePath: '/path/to/project/.mcp.json',
};
saveConfig(config);CLI命令
该软件包附带了一个CLI,可以通过以下方式访问 mcp-config:
mcp-config validate [--config
] [--level ] [--format json]
Validate the MCP config file. Exits with code 1 if validation fails.
mcp-config add [--command ] [--args ] [--url ] [--env KEY=VAL]
Add a server to the config. Supports registry lookup by name.
mcp-config list [--all] [--format json]
List servers in the config. Use --all to scan all known config locations.
mcp-config sync [--strategy skip|overwrite|merge-env] [--dry-run]
Sync servers from one config to another.
mcp-config search [--npm] [--limit ]
Search for MCP servers in the built-in registry and npm.
mcp-config doctor [--check-npm] [--check-env] [--format json]
Run comprehensive diagnostics on the config.
mcp-config init [--with ] [--force]
Create a new .mcp.json config file.全局选项: --config , --format human|json, --quiet, --version, --help
TypeScript
这个包是用TypeScript编写的,附带了完整的类型声明(dist/index.d.ts).所有公共类型都从包入口点导出:
import type {
MCPConfig,
StdioServerEntry,
HttpServerEntry,
ServerEntry,
ValidationCheck,
ValidationResult,
SyncOptions,
SyncResult,
ServerInfo,
DiscoverOptions,
ManagerOptions,
ConfigManager,
RegistryEntry,
} from 'mcp-config-ts';类型摘要
| 类型 | 描述 | |
|---|---|---|
MCPConfig | 解析MCP配置 servers, filePath,可选 _otherKeys | |
StdioServerEntry | stdio传输的服务器条目(command, args, env, cwd, disabled) | |
HttpServerEntry | HTTP传输的服务器条目(url, headers, disabled) | |
ServerEntry | 联盟 `StdioServerEntry \ | HttpServerEntry` |
ValidationCheck | 个人验证检查结果(id, severity, passed, message) | |
ValidationResult | 完整验证结果 valid, checks, summary, completenessScore | |
SyncOptions | 同步配置的选项(source, target, conflictStrategy, dryRun) | |
SyncResult | 同步操作的结果(added, updated, skipped, errors, changed) | |
ServerInfo | 可发现的MCP服务器信息(name, npmPackage, category, source) | |
DiscoverOptions | 服务器发现选项(searchNpm, limit) | |
ManagerOptions | 选项 createManager() (configPath, validationLevel) | |
ConfigManager | 有状态的配置管理器界面 load, save, add, remove, validate | |
RegistryEntry | 内置服务器注册表项,带有配置模板和env-var元数据 |
许可证
麻省理工学院
