mcp-cli-scripts
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP CLI Scripts Pattern
MCP CLI 脚本模式
Status: Production Ready
Last Updated: 2026-01-09
Dependencies: tsx (dev dependency)
Current Versions: tsx@4.21.0
状态:已就绪可用于生产环境
最后更新:2026-01-09
依赖项:tsx(开发依赖)
当前版本:tsx@4.21.0
Why CLI Scripts Alongside MCP Servers?
为何要在MCP服务器旁开发CLI脚本?
When building MCP servers, also create companion CLI scripts that provide the same (and often extended) functionality for use with Claude Code in terminal environments.
| Aspect | Remote MCP (Claude.ai) | CLI Scripts (Claude Code) |
|---|---|---|
| Context | Results flow through model context window | Results stay local, only relevant parts shared |
| File System | No access | Full read/write access |
| Batch Operations | One call at a time | Can process files of inputs |
| Caching | Stateless | Can cache results locally |
| Output | JSON to model | JSON, CSV, table, file, or stdout |
| Chaining | Model orchestrates | Scripts can pipe/chain directly |
在构建MCP服务器时,同时创建配套的CLI脚本,为终端环境下的Claude Code提供相同(且通常功能更丰富)的能力。
| 维度 | 远程MCP(Claude.ai) | CLI脚本(Claude Code) |
|---|---|---|
| 上下文 | 结果通过模型上下文窗口流转 | 结果本地留存,仅共享相关部分 |
| 文件系统 | 无访问权限 | 完全读写权限 |
| 批量操作 | 单次调用处理一个任务 | 可处理文件中的批量输入 |
| 缓存 | 无状态 | 可在本地缓存结果 |
| 输出 | 向模型返回JSON | 支持JSON、CSV、表格、文件或标准输出 |
| 链式调用 | 由模型编排 | 脚本可直接管道/链式调用 |
Directory Structure
目录结构
mcp-{name}/
├── src/
│ └── index.ts # MCP server (for Claude.ai, remote clients)
├── scripts/
│ ├── {tool-name}.ts # One script per tool
│ ├── {another-tool}.ts
│ └── _shared.ts # Shared auth/config helpers (optional)
├── SCRIPTS.md # Documents available scripts for Claude Code
├── package.json
└── README.mdmcp-{name}/
├── src/
│ └── index.ts # MCP服务器(供Claude.ai及远程客户端使用)
├── scripts/
│ ├── {tool-name}.ts # 每个工具对应一个脚本
│ ├── {another-tool}.ts
│ └── _shared.ts # 共享的认证/配置辅助代码(可选)
├── SCRIPTS.md # 为Claude Code提供可用脚本的文档
├── package.json
└── README.mdThe 5 Design Principles
5项设计原则
1. One Script Per Tool
1. 一脚本一工具
Each script does one thing well, matching an MCP tool but with extended capabilities.
每个脚本专注做好一件事,与MCP工具功能匹配但具备扩展能力。
2. JSON Output by Default
2. 默认输出JSON
Scripts output JSON to stdout for easy parsing. Claude Code can read and use the results.
typescript
// Good - structured output
console.log(JSON.stringify({ success: true, data: result }, null, 2));
// Avoid - unstructured text (unless --format text requested)
console.log("Found 5 results:");脚本默认向标准输出输出JSON,方便Claude Code解析和使用结果。
typescript
// 推荐 - 结构化输出
console.log(JSON.stringify({ success: true, data: result }, null, 2));
// 避免 - 非结构化文本(除非指定--format text)
console.log("找到5条结果:");3. Extended Capabilities for Local Use
3. 为本地使用提供扩展功能
CLI scripts can offer features that don't make sense for remote MCP:
typescript
// Input/Output files
--input data.csv // Batch process from file
--output results.json // Save results to file
--append // Append to existing file
// Caching
--cache // Use local cache
--cache-ttl 3600 // Cache for 1 hour
--no-cache // Force fresh request
// Output formats
--format json|csv|table // Different output formats
--quiet // Suppress non-essential output
--verbose // Extra debugging info
// Batch operations
--batch // Process multiple items
--concurrency 5 // Parallel processing limitCLI脚本可提供远程MCP不支持的功能:
typescript
// 输入/输出文件
--input data.csv // 从文件批量处理
--output results.json // 将结果保存至文件
--append // 追加至现有文件
// 缓存
--cache // 使用本地缓存
--cache-ttl 3600 // 缓存有效期1小时
--no-cache // 强制刷新请求
// 输出格式
--format json|csv|table // 不同输出格式
--quiet // 抑制非必要输出
--verbose // 额外调试信息
// 批量操作
--batch // 处理多个项目
--concurrency 5 // 并行处理限制4. Consistent Argument Patterns
4. 一致的参数模式
Use consistent patterns across all scripts:
bash
undefined所有脚本使用统一的参数模式:
bash
undefinedStandard patterns
标准模式
--input <file> # Read input from file
--output <file> # Write output to file
--format <type> # Output format
--profile <name> # Auth profile (for multi-account)
--verbose # Debug output
--help # Show usage
undefined--input <file> // 从文件读取输入
--output <file> // 将输出写入文件
--format <type> // 输出格式
--profile <name> // 认证配置文件(多账户场景)
--verbose // 调试输出
--help // 显示使用说明
undefined5. Shebang and Direct Execution
5. Shebang与直接执行
Scripts should be directly executable:
typescript
#!/usr/bin/env npx tsx
/**
* Brief description of what this script does
*
* Usage:
* npx tsx scripts/tool-name.ts <required-arg>
* npx tsx scripts/tool-name.ts --option value
*
* Examples:
* npx tsx scripts/tool-name.ts 12345
* npx tsx scripts/tool-name.ts --input batch.csv --output results.json
*/脚本应支持直接执行:
typescript
#!/usr/bin/env npx tsx
/**
* 本脚本功能简述
*
* 使用方法:
* npx tsx scripts/tool-name.ts <必填参数>
* npx tsx scripts/tool-name.ts --option value
*
* 示例:
* npx tsx scripts/tool-name.ts 12345
* npx tsx scripts/tool-name.ts --input batch.csv --output results.json
*/Critical Rules
关键规则
Always Do
必须遵守
✅ Use shebang (not node or ts-node)
✅ Output JSON to stdout by default
✅ Use consistent argument patterns across all scripts
✅ Document scripts in SCRIPTS.md
✅ Handle errors with structured JSON:
#!/usr/bin/env npx tsx{ success: false, error: "..." }✅ 使用作为shebang(而非node或ts-node)
✅ 默认向标准输出输出JSON
✅ 所有脚本使用一致的参数模式
✅ 在SCRIPTS.md中记录脚本
✅ 使用结构化JSON处理错误:
#!/usr/bin/env npx tsx{ success: false, error: "..." }Never Do
严禁操作
❌ Use for prose output (use structured JSON)
❌ Use different argument patterns per script
❌ Forget to document the script in SCRIPTS.md
❌ Use or in shebang (tsx handles ESM+TypeScript)
console.log()nodets-node❌ 使用输出散文式内容(应使用结构化JSON)
❌ 不同脚本使用不同的参数模式
❌ 忘记在SCRIPTS.md中记录脚本
❌ 在shebang中使用或(tsx可处理ESM+TypeScript)
console.log()nodets-nodeWhen to Use Scripts vs MCP
脚本与MCP的适用场景对比
Use CLI scripts when:
- Working in terminal/Claude Code environment
- Need to save results to files
- Processing batch inputs from files
- Chaining multiple operations
- Need caching for repeated lookups
- Want richer output formats
Use MCP tools when:
- In Claude.ai web interface
- Simple one-off lookups
- No file I/O needed
- Building conversational flows
使用CLI脚本的场景:
- 工作在终端/Claude Code环境
- 需要将结果保存至文件
- 处理来自文件的批量输入
- 链式调用多个操作
- 需要缓存重复查询结果
- 想要更丰富的输出格式
使用MCP工具的场景:
- 在Claude.ai网页界面中
- 简单的一次性查询
- 无需文件I/O
- 构建对话流程
Shared Code Between MCP and Scripts
MCP与脚本之间的共享代码
If you want to share logic between MCP and scripts, extract to a core module:
src/
├── core/
│ ├── lookup.ts # Pure function, no I/O assumptions
│ └── index.ts # Export all core functions
├── mcp/
│ └── index.ts # MCP handlers, import from core
└── cli/
└── lookup.ts # CLI wrapper, import from coreHowever, keeping them separate is also fine - the scripts may evolve to have capabilities the MCP can't support, and that's okay.
如果希望在MCP和脚本之间共享逻辑,可提取至核心模块:
src/
├── core/
│ ├── lookup.ts // 纯函数,无I/O假设
│ └── index.ts // 导出所有核心函数
├── mcp/
│ └── index.ts // MCP处理器,从core导入
└── cli/
└── lookup.ts // CLI封装,从core导入不过,保持两者独立也完全可行——脚本可能会发展出MCP无法支持的功能,这是正常的。
Using Bundled Resources
使用捆绑资源
Templates (templates/)
模板(templates/)
script-template.ts: Complete TypeScript script template with argument parsing, JSON output, and file I/O patterns.
bash
undefinedscript-template.ts:完整的TypeScript脚本模板,包含参数解析、JSON输出和文件I/O模式。
bash
undefinedCopy to your project
复制到你的项目中
cp ~/.claude/skills/mcp-cli-scripts/templates/script-template.ts scripts/new-tool.ts
**SCRIPTS-TEMPLATE.md**: Template for documenting available scripts in an MCP server repo.
```bashcp ~/.claude/skills/mcp-cli-scripts/templates/script-template.ts scripts/new-tool.ts
**SCRIPTS-TEMPLATE.md**:用于在MCP服务器仓库中记录可用脚本的模板。
```bashCopy to your project
复制到你的项目中
cp ~/.claude/skills/mcp-cli-scripts/templates/SCRIPTS-TEMPLATE.md SCRIPTS.md
undefinedcp ~/.claude/skills/mcp-cli-scripts/templates/SCRIPTS-TEMPLATE.md SCRIPTS.md
undefinedRules (rules/)
规则(rules/)
mcp-cli-scripts.md: Correction rules for script files. Copy to in projects:
.claude/rules/bash
cp ~/.claude/skills/mcp-cli-scripts/rules/mcp-cli-scripts.md .claude/rules/mcp-cli-scripts.md:脚本文件的校验规则。复制到项目的目录:
.claude/rules/bash
cp ~/.claude/skills/mcp-cli-scripts/rules/mcp-cli-scripts.md .claude/rules/Dependencies
依赖项
Required:
- tsx@4.21.0 - TypeScript execution without compilation
Add to package.json:
json
{
"devDependencies": {
"tsx": "^4.21.0"
}
}必填:
- tsx@4.21.0 - 无需编译即可执行TypeScript
添加至package.json:
json
{
"devDependencies": {
"tsx": "^4.21.0"
}
}Official Documentation
官方文档
- tsx: https://github.com/privatenumber/tsx
- Node.js CLI: https://nodejs.org/api/cli.html
- tsx: https://github.com/privatenumber/tsx
- Node.js CLI: https://nodejs.org/api/cli.html
Package Versions (Verified 2026-01-09)
完整设置清单
json
{
"devDependencies": {
"tsx": "^4.21.0"
}
}- 在MCP服务器项目中创建目录
scripts/ - 将tsx添加至开发依赖
- 从模板创建首个脚本
- 从模板创建SCRIPTS.md
- 测试脚本:
npx tsx scripts/tool-name.ts --help - 验证JSON输出格式
- 在SCRIPTS.md中记录所有脚本
Complete Setup Checklist
—
- Create directory in MCP server project
scripts/ - Add tsx to devDependencies
- Create first script from template
- Create SCRIPTS.md from template
- Test script:
npx tsx scripts/tool-name.ts --help - Verify JSON output format
- Document all scripts in SCRIPTS.md
—