Skip to content
mcp-cli-scripts logo

MCP CLI Scripts Pattern

mcp-cli-scripts

Build CLI scripts alongside MCP servers for terminal environments. File I/O, batch processing, caching, richer output formats. Templates for TypeScript scripts and SCRIPTS.md. Use when: MCP companion scripts, batch processing, saving results to files, CLI API wrappers. Troubleshoot: context too ...

SKILL.md

Full skill instructions

MCP CLI Scripts Pattern

Status: Production Ready Last Updated: 2026-01-09 Dependencies: tsx (dev dependency) Current Versions: [email protected]


Why CLI Scripts Alongside MCP Servers?

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.

AspectRemote MCP (Claude.ai)CLI Scripts (Claude Code)
ContextResults flow through model context windowResults stay local, only relevant parts shared
File SystemNo accessFull read/​write access
Batch OperationsOne call at a timeCan process files of inputs
CachingStatelessCan cache results locally
OutputJSON to modelJSON, CSV, table, file, or stdout
ChainingModel orchestratesScripts can pipe/​chain directly

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.md

The 5 Design Principles

1. One Script Per Tool

Each script does one thing well, matching an MCP tool but with extended capabilities.

2. JSON Output by Default

Scripts output JSON to stdout for easy parsing. Claude Code can read and use the results.

// 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:");

3. Extended Capabilities for Local Use

CLI scripts can offer features that don't make sense for remote MCP:

// 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 limit

4. Consistent Argument Patterns

Use consistent patterns across all scripts:

# Standard 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

5. Shebang and Direct Execution

Scripts should be directly executable:

#!/​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
 */

Critical Rules

Always Do

✅ Use #!/​usr/​bin/​env npx tsx 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: { success: false, error: "..." }

Never Do

❌ Use console.log() for prose output (use structured JSON) ❌ Use different argument patterns per script ❌ Forget to document the script in SCRIPTS.md ❌ Use node or ts-node in shebang (tsx handles ESM+TypeScript)


When to Use Scripts vs 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

Shared Code Between MCP and Scripts

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 core

However, keeping them separate is also fine - the scripts may evolve to have capabilities the MCP can't support, and that's okay.


Using Bundled Resources

Templates (templates/)

script-template.ts: Complete TypeScript script template with argument parsing, JSON output, and file I/​O patterns.

# Copy 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.

# Copy to your project
cp ~/​.claude/​skills/​mcp-cli-scripts/​templates/​SCRIPTS-TEMPLATE.md SCRIPTS.md

Rules (rules/)

mcp-cli-scripts.md: Correction rules for script files. Copy to .claude/​rules/ in projects:

cp ~/​.claude/​skills/​mcp-cli-scripts/​rules/​mcp-cli-scripts.md .claude/​rules/

Dependencies

Required:

Add to package.json:

{
  "devDependencies": {
    "tsx": "^4.21.0"
  }
}

Official Documentation


Package Versions (Verified 2026-01-09)

{
  "devDependencies": {
    "tsx": "^4.21.0"
  }
}

Complete Setup Checklist

  • Create scripts/ directory in MCP server project
  • 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

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View