@alcyone-labs/arg-parser 1.2.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +456 -1301
- package/dist/assets/.dxtignore.template +38 -0
- package/dist/assets/logo_1_small.jpg +0 -0
- package/dist/assets/tsdown.dxt.config.ts +37 -0
- package/dist/index.cjs +5871 -3847
- package/dist/index.cjs.map +1 -1
- package/dist/index.min.mjs +9877 -7956
- package/dist/index.min.mjs.map +1 -1
- package/dist/index.mjs +5854 -3838
- package/dist/index.mjs.map +1 -1
- package/dist/src/config/ConfigurationManager.d.ts +74 -0
- package/dist/src/config/ConfigurationManager.d.ts.map +1 -0
- package/dist/src/config/plugins/ConfigPlugin.d.ts +60 -0
- package/dist/src/config/plugins/ConfigPlugin.d.ts.map +1 -0
- package/dist/src/config/plugins/ConfigPluginRegistry.d.ts +72 -0
- package/dist/src/config/plugins/ConfigPluginRegistry.d.ts.map +1 -0
- package/dist/src/config/plugins/TomlConfigPlugin.d.ts +30 -0
- package/dist/src/config/plugins/TomlConfigPlugin.d.ts.map +1 -0
- package/dist/src/config/plugins/YamlConfigPlugin.d.ts +29 -0
- package/dist/src/config/plugins/YamlConfigPlugin.d.ts.map +1 -0
- package/dist/src/config/plugins/index.d.ts +5 -0
- package/dist/src/config/plugins/index.d.ts.map +1 -0
- package/dist/src/core/ArgParser.d.ts +332 -0
- package/dist/src/core/ArgParser.d.ts.map +1 -0
- package/dist/src/{ArgParserBase.d.ts → core/ArgParserBase.d.ts} +84 -3
- package/dist/src/core/ArgParserBase.d.ts.map +1 -0
- package/dist/src/core/FlagManager.d.ts.map +1 -0
- package/dist/src/{types.d.ts → core/types.d.ts} +29 -0
- package/dist/src/core/types.d.ts.map +1 -0
- package/dist/src/dxt/DxtGenerator.d.ts +115 -0
- package/dist/src/dxt/DxtGenerator.d.ts.map +1 -0
- package/dist/src/index.d.ts +10 -6
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/mcp/ArgParserMcp.d.ts +21 -0
- package/dist/src/mcp/ArgParserMcp.d.ts.map +1 -0
- package/dist/src/mcp/mcp-integration.d.ts +83 -0
- package/dist/src/mcp/mcp-integration.d.ts.map +1 -0
- package/dist/src/mcp/mcp-notifications.d.ts +138 -0
- package/dist/src/mcp/mcp-notifications.d.ts.map +1 -0
- package/dist/src/mcp/mcp-prompts.d.ts +132 -0
- package/dist/src/mcp/mcp-prompts.d.ts.map +1 -0
- package/dist/src/mcp/mcp-resources.d.ts +133 -0
- package/dist/src/mcp/mcp-resources.d.ts.map +1 -0
- package/dist/src/testing/fuzzy-test-cli.d.ts +5 -0
- package/dist/src/testing/fuzzy-test-cli.d.ts.map +1 -0
- package/dist/src/{fuzzy-tester.d.ts → testing/fuzzy-tester.d.ts} +1 -1
- package/dist/src/testing/fuzzy-tester.d.ts.map +1 -0
- package/package.json +31 -17
- package/dist/src/ArgParser.d.ts +0 -148
- package/dist/src/ArgParser.d.ts.map +0 -1
- package/dist/src/ArgParserBase.d.ts.map +0 -1
- package/dist/src/FlagManager.d.ts.map +0 -1
- package/dist/src/fuzzy-test-cli.d.ts +0 -5
- package/dist/src/fuzzy-test-cli.d.ts.map +0 -1
- package/dist/src/fuzzy-tester.d.ts.map +0 -1
- package/dist/src/mcp-integration.d.ts +0 -31
- package/dist/src/mcp-integration.d.ts.map +0 -1
- package/dist/src/types.d.ts.map +0 -1
- /package/dist/src/{FlagManager.d.ts → core/FlagManager.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -1,1499 +1,655 @@
|
|
|
1
1
|
# ArgParser - Type-Safe Command Line Argument Parser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A modern, type-safe command line argument parser with built-in MCP (Model Context Protocol) integration and automatic Claude Desktop Extension (DXT) generation.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Features Overview](#features-overview)
|
|
8
|
+
- [Installation](#installation)
|
|
9
|
+
- [Quick Start: The Unified `addTool` API](#quick-start-the-unified-addtool-api)
|
|
10
|
+
- [How to Run It](#how-to-run-it)
|
|
11
|
+
- [Setting Up System-Wide CLI Access](#setting-up-system-wide-cli-access)
|
|
12
|
+
- [Parsing Command-Line Arguments](#parsing-command-line-arguments)
|
|
13
|
+
- [Cannonical Usage Pattern](#cannonical-usage-pattern)
|
|
14
|
+
- [Top-level await](#top-level-await)
|
|
15
|
+
- [Promise-based parsing](#promise-based-parsing)
|
|
16
|
+
- [Migrating from v1.x to the v2.0 `addTool` API](#migrating-from-v1x-to-the-v20-addtool-api)
|
|
17
|
+
- [Before v2.0: Separate Definitions](#before-v20-separate-definitions)
|
|
18
|
+
- [After v2.0: The Unified `addTool()` Method](#after-v20-the-unified-addtool-method)
|
|
19
|
+
- [Core Concepts](#core-concepts)
|
|
20
|
+
- [Defining Flags](#defining-flags)
|
|
21
|
+
- [Type Handling and Validation](#type-handling-and-validation)
|
|
22
|
+
- [Hierarchical CLIs (Sub-Commands)](#hierarchical-clis-sub-commands)
|
|
23
|
+
- [MCP Exposure Control](#mcp-exposure-control)
|
|
24
|
+
- [Flag Inheritance (`inheritParentFlags`)](#flag-inheritance-inheritparentflags)
|
|
25
|
+
- [MCP & Claude Desktop Integration](#mcp--claude-desktop-integration)
|
|
26
|
+
- [Automatic MCP Server Mode (`--s-mcp-serve`)](#automatic-mcp-server-mode---s-mcp-serve)
|
|
27
|
+
- [MCP Transports](#mcp-transports)
|
|
28
|
+
- [Automatic Console Safety](#automatic-console-safety)
|
|
29
|
+
- [Generating DXT Packages (`--s-build-dxt`)](#generating-dxt-packages---s-build-dxt)
|
|
30
|
+
- [Logo Configuration](#logo-configuration)
|
|
31
|
+
- [How DXT Generation Works](#how-dxt-generation-works)
|
|
32
|
+
- [System Flags & Configuration](#system-flags--configuration)
|
|
33
|
+
- [Changelog](#changelog)
|
|
34
|
+
- [Backlog](#backlog)
|
|
35
|
+
|
|
36
|
+
## Features Overview
|
|
37
|
+
|
|
38
|
+
- **Unified Tool Architecture**: Define tools once with `addTool()` and they automatically function as both CLI subcommands and MCP tools.
|
|
39
|
+
- **Type-safe flag definitions** with full TypeScript support and autocompletion.
|
|
40
|
+
- **Automatic MCP Integration**: Transform any CLI into a compliant MCP server with a single command (`--s-mcp-serve`).
|
|
41
|
+
- **Console Safe**: `console.log` and other methods
|
|
42
|
+
are automatically handled in MCP mode to prevent protocol contamination, requiring no changes to your code.
|
|
43
|
+
- **DXT Package Generation**: Generate complete, ready-to-install Claude Desktop Extension (`.dxt`) packages with the `--s-build-dxt` command.
|
|
44
|
+
- **Hierarchical Sub-commands**: Create complex, nested sub-command structures (e.g., `git commit`, `docker container ls`) with flag inheritance.
|
|
45
|
+
- **Configuration Management**: Easily load (`--s-with-env`) and save (`--s-save-to-env`) configurations from/to `.env`, `.json`, `.yaml`, and `.toml` files.
|
|
46
|
+
- **Automatic Help & Error Handling**: Context-aware help text and user-friendly error messages are generated automatically.
|
|
47
|
+
- **Debugging Tools**: Built-in system flags like `--s-debug` and `--s-debug-print` for easy troubleshooting.
|
|
4
48
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
## What's New in v1.2.0
|
|
8
|
-
|
|
9
|
-
### **Critical MCP Fixes & Improvements**
|
|
10
|
-
|
|
11
|
-
- **Fixed MCP Output Schema Support**: Resolved the critical issue where MCP tools with output schemas failed with `"Tool has an output schema but no structured content was provided"` error
|
|
12
|
-
- **Enhanced Handler Context**: Added `isMcp` flag to handler context, enabling proper MCP mode detection in handlers
|
|
13
|
-
- **Improved Response Format**: MCP tools now correctly return both `content` and `structuredContent` fields as required by the JSON-RPC 2.0 specification
|
|
14
|
-
- **Better Integration**: Handlers can now reliably detect when they're being called from MCP mode vs CLI mode
|
|
49
|
+
---
|
|
15
50
|
|
|
16
|
-
|
|
51
|
+
## Installation
|
|
17
52
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
53
|
+
```bash
|
|
54
|
+
# Using PNPM (recommended)
|
|
55
|
+
pnpm add @alcyone-labs/arg-parser
|
|
21
56
|
```
|
|
22
57
|
|
|
23
|
-
|
|
24
|
-
```json
|
|
25
|
-
{
|
|
26
|
-
"jsonrpc": "2.0",
|
|
27
|
-
"id": 3,
|
|
28
|
-
"result": {
|
|
29
|
-
"content": [{"type": "text", "text": "..."}],
|
|
30
|
-
"structuredContent": { /* validated against output schema */ }
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
```
|
|
58
|
+
---
|
|
34
59
|
|
|
35
|
-
|
|
60
|
+
## Quick Start: The Unified `addTool` API
|
|
36
61
|
|
|
37
|
-
|
|
62
|
+
The modern way to build with ArgParser is using the `.addTool()` method. It creates a single, self-contained unit that works as both a CLI subcommand and an MCP tool.
|
|
38
63
|
|
|
39
64
|
```typescript
|
|
65
|
+
import { ArgParser } from "@alcyone-labs/arg-parser";
|
|
66
|
+
|
|
67
|
+
// Use ArgParser.withMcp to enable MCP and DXT features
|
|
40
68
|
const cli = ArgParser.withMcp({
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
69
|
+
appName: "My Awesome CLI",
|
|
70
|
+
appCommandName: "mycli",
|
|
71
|
+
description: "A tool that works in both CLI and MCP mode",
|
|
72
|
+
mcp: {
|
|
73
|
+
serverInfo: { name: "my-awesome-mcp-server", version: "1.0.0" },
|
|
74
|
+
},
|
|
75
|
+
})
|
|
76
|
+
// Define a tool that works everywhere
|
|
77
|
+
.addTool({
|
|
78
|
+
name: "greet",
|
|
79
|
+
description: "A tool to greet someone",
|
|
80
|
+
flags: [
|
|
81
|
+
{
|
|
82
|
+
name: "name",
|
|
83
|
+
type: "string",
|
|
84
|
+
mandatory: true,
|
|
85
|
+
options: ["--name"],
|
|
86
|
+
description: "Name to greet",
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: "style",
|
|
90
|
+
type: "string",
|
|
91
|
+
enum: ["formal", "casual"],
|
|
92
|
+
defaultValue: "casual",
|
|
93
|
+
description: "Greeting style",
|
|
94
|
+
},
|
|
95
|
+
],
|
|
96
|
+
handler: async (ctx) => {
|
|
97
|
+
// Use console.log freely - it's automatically safe in MCP mode!
|
|
98
|
+
console.log(`Greeting ${ctx.args.name} in a ${ctx.args.style} style...`);
|
|
99
|
+
|
|
100
|
+
const greeting =
|
|
101
|
+
ctx.args.style === "formal"
|
|
102
|
+
? `Good day, ${ctx.args.name}.`
|
|
103
|
+
: `Hey ${ctx.args.name}!`;
|
|
104
|
+
|
|
105
|
+
console.log(greeting);
|
|
106
|
+
return { success: true, greeting, name: ctx.args.name };
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// parse() is async and works with both sync and async handlers
|
|
111
|
+
async function main() {
|
|
112
|
+
try {
|
|
113
|
+
await cli.parse(process.argv.slice(2));
|
|
114
|
+
} catch (error) {
|
|
115
|
+
console.error("Error:", error.message);
|
|
116
|
+
process.exit(1);
|
|
50
117
|
}
|
|
51
|
-
}
|
|
52
|
-
```
|
|
118
|
+
}
|
|
53
119
|
|
|
54
|
-
|
|
120
|
+
main();
|
|
55
121
|
|
|
56
|
-
|
|
122
|
+
// Export if you want to test, use the CLI programmatically
|
|
123
|
+
// or use the --s-enable-fuzzing system flag to run fuzzy tests on your CLI
|
|
124
|
+
export default cli;
|
|
125
|
+
```
|
|
57
126
|
|
|
58
|
-
|
|
59
|
-
- **System Flags**: Built-in `--s-debug-print`, `--s-with-env`, `--s-save-to-env`, `--s-enable-fuzzy`, and `--s-save-DXT` for enhanced debugging, configuration, testing, and MCP distribution
|
|
60
|
-
- **Environment Loading**: Load configuration from `.env`, `.yaml`, `.json`, and `.toml` files
|
|
61
|
-
- **Enhanced Debugging**: Comprehensive runtime debugging and configuration export tools
|
|
127
|
+
## How to Run It
|
|
62
128
|
|
|
63
|
-
|
|
129
|
+
```bash
|
|
130
|
+
# This assumes `mycli` is your CLI's entry point
|
|
64
131
|
|
|
65
|
-
|
|
66
|
-
|
|
132
|
+
# 1. As a standard CLI subcommand
|
|
133
|
+
mycli greet --name Jane --style formal
|
|
67
134
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
appCommandName: "my-tool",
|
|
71
|
-
description: "A powerful CLI that can also run as an MCP server",
|
|
72
|
-
handler: async (ctx) => ({ result: "success", args: ctx.args }),
|
|
73
|
-
})
|
|
74
|
-
.addFlags([
|
|
75
|
-
{ name: "input", options: ["--input", "-i"], type: "string", mandatory: true },
|
|
76
|
-
{ name: "verbose", options: ["--verbose", "-v"], type: "boolean", flagOnly: true },
|
|
77
|
-
])
|
|
78
|
-
.addMcpSubCommand("serve", {
|
|
79
|
-
name: "my-mcp-server",
|
|
80
|
-
version: "1.1.0",
|
|
81
|
-
description: "Expose this CLI as an MCP server",
|
|
82
|
-
}, {
|
|
83
|
-
// Optional: Configure default transports (CLI flags take precedence)
|
|
84
|
-
defaultTransports: [
|
|
85
|
-
{ type: "stdio" },
|
|
86
|
-
{ type: "sse", port: 3001, host: "0.0.0.0" }
|
|
87
|
-
]
|
|
88
|
-
});
|
|
135
|
+
# 2. As an MCP server, exposing the 'greet' tool
|
|
136
|
+
mycli --s-mcp-serve
|
|
89
137
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
// Use as MCP server with CLI override: my-tool serve --transport sse --port 3002
|
|
93
|
-
// Use with multiple transports: my-tool serve --transports '[{"type":"stdio"},{"type":"sse","port":3001}]'
|
|
138
|
+
# 3. Generate a DXT package for Claude Desktop (2-steps)
|
|
139
|
+
mycli --s-build-dxt ./my-dxt-package
|
|
94
140
|
```
|
|
95
141
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
### **Core CLI Features**
|
|
99
|
-
- **Type Safety:** Define expected argument types (string, number, boolean, array, custom functions) and get type-safe parsed results
|
|
100
|
-
- **Declarative API:** Configure your CLI structure, flags, and sub-commands using a clear, declarative syntax
|
|
101
|
-
- **Automatic Help Generation:** Generate comprehensive and contextual help text based on your parser configuration
|
|
102
|
-
- **Hierarchical Commands:** Easily define nested sub-commands to create complex command structures (e.g., `git commit`, `docker container ls`)
|
|
103
|
-
- **Handler Execution:** Associate handler functions with commands and have them executed automatically upon successful parsing
|
|
104
|
-
- **Validation:** Define custom validation rules for flag values with enum support and custom validators
|
|
105
|
-
- **Conditional Requirements:** Make flags mandatory based on the presence or values of other arguments
|
|
106
|
-
- **Default Values:** Specify default values for flags if they are not provided on the command line
|
|
107
|
-
- **Flag Inheritance:** Share common flags between parent and child commands with an intuitive inheritance mechanism
|
|
108
|
-
- **Error Handling:** Built-in, user-friendly error reporting for common parsing issues, with an option to handle errors manually
|
|
109
|
-
|
|
110
|
-
### **MCP Integration (v1.1.0+)**
|
|
111
|
-
- **Automatic MCP Server Creation:** Transform any CLI into an MCP server with a single method call
|
|
112
|
-
- **Multiple Transport Support:** Run stdio, SSE, and HTTP transports simultaneously on different ports
|
|
113
|
-
- **Type-Safe Tool Generation:** Automatically generate MCP tools with Zod schema validation from CLI definitions
|
|
114
|
-
- **Flexible Configuration:** Support for single transport or complex multi-transport JSON configurations
|
|
115
|
-
|
|
116
|
-
### **System & Configuration Features (v1.1.0+)**
|
|
117
|
-
- **Environment Loading:** Load configuration from `.env`, `.yaml`, `.json`, and `.toml` files with `--s-with-env`
|
|
118
|
-
- **Configuration Export:** Save current configuration to various formats with `--s-save-to-env`
|
|
119
|
-
- **Advanced Debugging:** Runtime debugging with `--s-debug` and configuration inspection with `--s-debug-print`
|
|
120
|
-
- **CLI Precedence:** Command line arguments always override file configuration
|
|
142
|
+
Read more on generating the DXT package here: [Generating DXT Packages](#generating-dxt-packages---s-build-dxt)
|
|
121
143
|
|
|
122
|
-
|
|
144
|
+
### Setting Up System-Wide CLI Access
|
|
123
145
|
|
|
124
|
-
|
|
146
|
+
To make your CLI available system-wide as a binary command, you need to configure the `bin` field in your `package.json` and use package linking:
|
|
125
147
|
|
|
126
|
-
|
|
127
|
-
pnpm add @alcyone-labs/arg-parser
|
|
128
|
-
# or
|
|
129
|
-
npm install @alcyone-labs/arg-parser
|
|
130
|
-
# or
|
|
131
|
-
yarn add @alcyone-labs/arg-parser
|
|
132
|
-
# or
|
|
133
|
-
bun add @alcyone-labs/arg-parser
|
|
134
|
-
# or
|
|
135
|
-
deno install npm:@alcyone-labs/arg-parser
|
|
136
|
-
```
|
|
148
|
+
**1. Configure your package.json:**
|
|
137
149
|
|
|
138
|
-
|
|
150
|
+
```json
|
|
151
|
+
{
|
|
152
|
+
"name": "my-cli-app",
|
|
153
|
+
"version": "1.0.0",
|
|
154
|
+
"type": "module",
|
|
155
|
+
"bin": {
|
|
156
|
+
"mycli": "./cli.js"
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
```
|
|
139
160
|
|
|
140
|
-
|
|
161
|
+
**2. Make your CLI file executable:**
|
|
141
162
|
|
|
142
163
|
```bash
|
|
143
|
-
|
|
144
|
-
# or
|
|
145
|
-
npm install @modelcontextprotocol/sdk express
|
|
164
|
+
chmod +x cli.js
|
|
146
165
|
```
|
|
147
166
|
|
|
148
|
-
**
|
|
167
|
+
**3. Add a shebang to your CLI file:**
|
|
149
168
|
|
|
150
|
-
|
|
169
|
+
```javascript
|
|
170
|
+
#!/usr/bin/env node
|
|
171
|
+
# or #!/usr/bin/env bun for native typescript runtime
|
|
151
172
|
|
|
152
|
-
|
|
173
|
+
import { ArgParser } from '@alcyone-labs/arg-parser';
|
|
153
174
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
175
|
+
const cli = ArgParser.withMcp({
|
|
176
|
+
appName: "My CLI",
|
|
177
|
+
appCommandName: "mycli",
|
|
178
|
+
// ... your configuration
|
|
179
|
+
});
|
|
158
180
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
bun ./dist/your-cli.js --flag value
|
|
181
|
+
// Parse command line arguments
|
|
182
|
+
await cli.parse(process.argv.slice(2));
|
|
162
183
|
```
|
|
163
184
|
|
|
164
|
-
|
|
165
|
-
```bash
|
|
166
|
-
# Using tsx for TypeScript
|
|
167
|
-
npx tsx your-cli.ts --flag value
|
|
185
|
+
**4. Link the package globally:**
|
|
168
186
|
|
|
169
|
-
|
|
170
|
-
|
|
187
|
+
```bash
|
|
188
|
+
# Using npm
|
|
189
|
+
npm link
|
|
171
190
|
|
|
172
|
-
#
|
|
173
|
-
|
|
174
|
-
node your-cli.js --flag value
|
|
175
|
-
```
|
|
191
|
+
# Using pnpm
|
|
192
|
+
pnpm link --global
|
|
176
193
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
# Run with required permissions
|
|
180
|
-
deno run --unstable-sloppy-imports --allow-read --allow-write --allow-env your-cli.ts --flag value
|
|
194
|
+
# Using bun
|
|
195
|
+
bun link
|
|
181
196
|
|
|
182
|
-
#
|
|
183
|
-
|
|
197
|
+
# Using yarn
|
|
198
|
+
yarn link
|
|
184
199
|
```
|
|
185
200
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
Install the library and use it in your projects:
|
|
201
|
+
**5. Use your CLI from anywhere:**
|
|
189
202
|
|
|
190
203
|
```bash
|
|
191
|
-
#
|
|
192
|
-
|
|
204
|
+
# Now you can run your CLI from any directory
|
|
205
|
+
mycli --help
|
|
206
|
+
mycli greet --name "World"
|
|
193
207
|
|
|
194
|
-
#
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
const { ArgParser } = require('@alcyone-labs/arg-parser');
|
|
208
|
+
# Or use with npx/pnpx if you prefer
|
|
209
|
+
npx mycli --help
|
|
210
|
+
pnpx mycli greet --name "World"
|
|
198
211
|
```
|
|
199
212
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
Examples are provided as TypeScript source files for educational purposes. Run them directly with your preferred runtime:
|
|
213
|
+
**To unlink later:**
|
|
203
214
|
|
|
204
215
|
```bash
|
|
205
|
-
#
|
|
206
|
-
|
|
216
|
+
# Using npm
|
|
217
|
+
npm unlink --global my-cli-app
|
|
218
|
+
|
|
219
|
+
# Using pnpm
|
|
220
|
+
pnpm unlink --global
|
|
207
221
|
|
|
208
|
-
#
|
|
209
|
-
|
|
222
|
+
# Using bun
|
|
223
|
+
bun unlink
|
|
210
224
|
|
|
211
|
-
#
|
|
212
|
-
|
|
225
|
+
# Using yarn
|
|
226
|
+
yarn unlink
|
|
213
227
|
```
|
|
214
228
|
|
|
215
|
-
|
|
229
|
+
---
|
|
216
230
|
|
|
217
|
-
##
|
|
231
|
+
## Parsing Command-Line Arguments
|
|
218
232
|
|
|
219
|
-
|
|
233
|
+
ArgParser's `parse()` method is async and automatically handles both synchronous and asynchronous handlers:
|
|
220
234
|
|
|
221
|
-
|
|
235
|
+
### Cannonical Usage Pattern
|
|
222
236
|
|
|
223
237
|
```typescript
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const parser = new ArgParser({
|
|
227
|
-
appName: "Data Processor",
|
|
228
|
-
appCommandName: "data-proc", // Used in help text and error messages
|
|
229
|
-
description: "A tool for processing data phases",
|
|
238
|
+
const cli = ArgParser.withMcp({
|
|
239
|
+
appName: "My CLI",
|
|
230
240
|
handler: async (ctx) => {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}).addFlags([
|
|
235
|
-
{
|
|
236
|
-
name: "phase",
|
|
237
|
-
options: ["--phase"],
|
|
238
|
-
type: "string", // Use "string", "number", "boolean", or native types
|
|
239
|
-
mandatory: true,
|
|
240
|
-
enum: ["chunking", "pairing", "analysis"],
|
|
241
|
-
description: "Processing phase to execute",
|
|
242
|
-
},
|
|
243
|
-
{
|
|
244
|
-
name: "batch",
|
|
245
|
-
options: ["-b", "--batch-number"],
|
|
246
|
-
type: "number",
|
|
247
|
-
mandatory: (args) => args.phase !== "analysis", // Conditional requirement
|
|
248
|
-
defaultValue: 0,
|
|
249
|
-
description: "Batch number (required except for analysis phase)",
|
|
241
|
+
// Works with both sync and async operations
|
|
242
|
+
const result = await someAsyncOperation(ctx.args.input);
|
|
243
|
+
return { success: true, result };
|
|
250
244
|
},
|
|
251
|
-
|
|
252
|
-
name: "verbose",
|
|
253
|
-
options: ["-v", "--verbose"],
|
|
254
|
-
flagOnly: true, // This flag does not expect a value
|
|
255
|
-
description: "Enable verbose logging",
|
|
256
|
-
},
|
|
257
|
-
]);
|
|
245
|
+
});
|
|
258
246
|
|
|
259
|
-
//
|
|
260
|
-
|
|
261
|
-
|
|
247
|
+
// parse() is async and works with both sync and async handlers
|
|
248
|
+
async function main() {
|
|
249
|
+
try {
|
|
250
|
+
const result = await cli.parse(process.argv.slice(2));
|
|
251
|
+
// Handler results are automatically awaited and merged
|
|
252
|
+
console.log(result.success); // true
|
|
253
|
+
} catch (error) {
|
|
254
|
+
console.error("Error:", error.message);
|
|
255
|
+
process.exit(1);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
262
258
|
```
|
|
263
259
|
|
|
264
|
-
###
|
|
260
|
+
### Top-level await
|
|
265
261
|
|
|
266
|
-
|
|
262
|
+
Works in ES modules or Node.js >=18 with top-level await
|
|
267
263
|
|
|
268
|
-
```
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
console.log("Processing data with phase:", ctx.args.phase);
|
|
277
|
-
return { success: true, phase: ctx.args.phase, batch: ctx.args.batch };
|
|
278
|
-
},
|
|
279
|
-
})
|
|
280
|
-
.addFlags([
|
|
281
|
-
{
|
|
282
|
-
name: "phase",
|
|
283
|
-
options: ["--phase"],
|
|
284
|
-
type: "string",
|
|
285
|
-
mandatory: true,
|
|
286
|
-
enum: ["chunking", "pairing", "analysis"],
|
|
287
|
-
description: "Processing phase to execute",
|
|
288
|
-
},
|
|
289
|
-
{
|
|
290
|
-
name: "batch",
|
|
291
|
-
options: ["-b", "--batch-number"],
|
|
292
|
-
type: "number",
|
|
293
|
-
defaultValue: 0,
|
|
294
|
-
description: "Batch number for processing",
|
|
295
|
-
},
|
|
296
|
-
])
|
|
297
|
-
.addMcpSubCommand("serve", {
|
|
298
|
-
name: "data-processor-mcp",
|
|
299
|
-
version: "1.1.0",
|
|
300
|
-
description: "Data Processor MCP Server",
|
|
301
|
-
});
|
|
302
|
-
|
|
303
|
-
// Use as CLI: data-proc --phase chunking --batch 5
|
|
304
|
-
// Use as MCP server: data-proc serve
|
|
305
|
-
// Use with custom transport: data-proc serve --transport sse --port 3001
|
|
264
|
+
```javascript
|
|
265
|
+
try {
|
|
266
|
+
const result = await cli.parse(process.argv.slice(2));
|
|
267
|
+
console.log("Success:", result);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
console.error("Error:", error.message);
|
|
270
|
+
process.exit(1);
|
|
271
|
+
}
|
|
306
272
|
```
|
|
307
273
|
|
|
308
|
-
|
|
274
|
+
### Promise-based parsing
|
|
309
275
|
|
|
310
|
-
|
|
276
|
+
If you need synchronous contexts, you can simply rely on promise-based APIs
|
|
311
277
|
|
|
312
|
-
|
|
278
|
+
```javascript
|
|
279
|
+
cli
|
|
280
|
+
.parse(process.argv.slice(2))
|
|
281
|
+
.then((result) => {
|
|
282
|
+
console.log("Success:", result);
|
|
283
|
+
})
|
|
284
|
+
.catch((error) => {
|
|
285
|
+
console.error("Error:", error.message);
|
|
286
|
+
process.exit(1);
|
|
287
|
+
});
|
|
288
|
+
```
|
|
313
289
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
```
|
|
290
|
+
---
|
|
291
|
+
|
|
292
|
+
## Migrating from v1.x to the v2.0 `addTool` API
|
|
318
293
|
|
|
319
|
-
2.
|
|
320
|
-
```typescript
|
|
321
|
-
const cli = ArgParser.withMcp({
|
|
322
|
-
appName: "My Tool",
|
|
323
|
-
appCommandName: "my-tool",
|
|
324
|
-
handler: async (ctx) => ({ result: "success", args: ctx.args }),
|
|
325
|
-
})
|
|
326
|
-
.addFlags([/* your flags */])
|
|
327
|
-
.addMcpSubCommand("serve", {
|
|
328
|
-
name: "my-mcp-server",
|
|
329
|
-
version: "1.0.0",
|
|
330
|
-
});
|
|
331
|
-
```
|
|
294
|
+
Version 2.0 introduces the `addTool()` method to unify CLI subcommand and MCP tool creation. This simplifies development by removing boilerplate and conditional logic.
|
|
332
295
|
|
|
333
|
-
|
|
334
|
-
```bash
|
|
335
|
-
# CLI usage
|
|
336
|
-
my-tool --input data.txt --verbose
|
|
296
|
+
### Before v2.0: Separate Definitions
|
|
337
297
|
|
|
338
|
-
|
|
339
|
-
my-tool serve
|
|
298
|
+
Previously, you had to define CLI handlers and MCP tools separately, often with conditional logic inside the handler to manage different output formats.
|
|
340
299
|
|
|
341
|
-
|
|
342
|
-
|
|
300
|
+
```javascript
|
|
301
|
+
const cli = ArgParser.withMcp({
|
|
302
|
+
appName: "My Awesome CLI",
|
|
303
|
+
appCommandName: "mycli",
|
|
304
|
+
description: "A tool that works in both CLI and MCP mode",
|
|
305
|
+
mcp: {
|
|
306
|
+
serverInfo: { name: "my-awesome-mcp-server", version: "1.0.0" },
|
|
307
|
+
},
|
|
308
|
+
});
|
|
343
309
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
310
|
+
// Old way: Separate CLI subcommands and MCP tools
|
|
311
|
+
cli
|
|
312
|
+
.addSubCommand({
|
|
313
|
+
name: "search",
|
|
314
|
+
handler: async (ctx) => {
|
|
315
|
+
// Manual MCP detection was required
|
|
316
|
+
if (ctx.isMcp) {
|
|
317
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }] };
|
|
318
|
+
} else {
|
|
319
|
+
console.log("Search results...");
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
},
|
|
323
|
+
})
|
|
324
|
+
// And a separate command to start the server
|
|
325
|
+
.addMcpSubCommand("serve", {
|
|
326
|
+
/* MCP config */
|
|
327
|
+
});
|
|
328
|
+
```
|
|
347
329
|
|
|
348
|
-
###
|
|
330
|
+
### After v2.0: The Unified `addTool()` Method
|
|
349
331
|
|
|
350
|
-
|
|
351
|
-
- **`sse`**: Server-Sent Events over HTTP for web applications
|
|
352
|
-
- **`streamable-http`**: HTTP with streaming support for advanced integrations
|
|
332
|
+
Now, a single `addTool()` definition creates both the CLI subcommand and the MCP tool. Console output is automatically managed, flags are converted to MCP schemas, and the server is started with a universal system flag.
|
|
353
333
|
|
|
354
|
-
|
|
334
|
+
```javascript
|
|
335
|
+
const cli = ArgParser.withMcp({
|
|
336
|
+
appName: "My Awesome CLI",
|
|
337
|
+
appCommandName: "mycli",
|
|
338
|
+
description: "A tool that works in both CLI and MCP mode",
|
|
339
|
+
mcp: {
|
|
340
|
+
serverInfo: { name: "my-awesome-mcp-server", version: "1.0.0" },
|
|
341
|
+
},
|
|
342
|
+
});
|
|
355
343
|
|
|
356
|
-
|
|
344
|
+
// New way: A single tool definition for both CLI and MCP
|
|
345
|
+
cli.addTool({
|
|
346
|
+
name: "search",
|
|
347
|
+
description: "Search for items",
|
|
348
|
+
flags: [
|
|
349
|
+
{ name: "query", type: "string", mandatory: true },
|
|
350
|
+
{ name: "apiKey", type: "string", env: "API_KEY" }, // For DXT integration
|
|
351
|
+
],
|
|
352
|
+
handler: async (ctx) => {
|
|
353
|
+
// No more MCP detection! Use console.log freely.
|
|
354
|
+
console.log(`Searching for: ${ctx.args.query}`);
|
|
355
|
+
const results = await performSearch(ctx.args.query, ctx.args.apiKey);
|
|
356
|
+
console.log(`Found ${results.length} results`);
|
|
357
|
+
return { success: true, results };
|
|
358
|
+
},
|
|
359
|
+
});
|
|
357
360
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
{"type":"stdio"},
|
|
361
|
-
{"type":"sse","port":3001,"path":"/sse"},
|
|
362
|
-
{"type":"streamable-http","port":3002,"path":"/mcp","host":"0.0.0.0"}
|
|
363
|
-
]'
|
|
361
|
+
// CLI usage: mycli search --query "test"
|
|
362
|
+
// MCP usage: mycli --s-mcp-serve
|
|
364
363
|
```
|
|
365
364
|
|
|
366
|
-
|
|
365
|
+
**Benefits of Migrating:**
|
|
366
|
+
|
|
367
|
+
- **Less Code**: A single definition replaces two or more complex ones.
|
|
368
|
+
- **Simpler Logic**: No more manual MCP mode detection or response formatting.
|
|
369
|
+
- **Automatic Schemas**: Flags are automatically converted into the `input_schema` for MCP tools.
|
|
370
|
+
- **Automatic Console Safety**: `console.log` is automatically redirected in MCP mode.
|
|
367
371
|
|
|
368
|
-
|
|
369
|
-
- **Type-safe schemas** using Zod validation
|
|
370
|
-
- **Automatic documentation** from flag descriptions
|
|
371
|
-
- **Enum validation** for restricted values
|
|
372
|
-
- **Error handling** with detailed messages
|
|
372
|
+
---
|
|
373
373
|
|
|
374
374
|
## Core Concepts
|
|
375
375
|
|
|
376
376
|
### Defining Flags
|
|
377
377
|
|
|
378
|
-
Flags are defined using the
|
|
378
|
+
Flags are defined using the `IFlag` interface within the `flags` array of a tool or command.
|
|
379
379
|
|
|
380
380
|
```typescript
|
|
381
381
|
interface IFlag {
|
|
382
|
-
name: string; // Internal name
|
|
383
|
-
options: string[]; //
|
|
384
|
-
type:
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
mandatory?: boolean | ((args: TParsedArgs) => boolean); // Whether the flag is required, or a function that determines this
|
|
394
|
-
defaultValue?: any; // Default value if the flag is not provided
|
|
395
|
-
default?: any; // Alias for defaultValue
|
|
396
|
-
flagOnly?: boolean; // If true, the flag does not consume the next argument as its value (e.g., `--verbose`)
|
|
397
|
-
allowMultiple?: boolean; // If true, the flag can be provided multiple times (values are collected in an array)
|
|
398
|
-
enum?: any[]; // Array of allowed values. Parser validates input against this list.
|
|
399
|
-
validate?: (value: any) => boolean | string | void; // Custom validation function
|
|
400
|
-
required?: boolean | ((args: any) => boolean); // Alias for mandatory
|
|
382
|
+
name: string; // Internal name (e.g., 'verbose')
|
|
383
|
+
options: string[]; // Command-line options (e.g., ['--verbose', '-v'])
|
|
384
|
+
type: "string" | "number" | "boolean" | "array" | "object" | Function;
|
|
385
|
+
description?: string; // Help text
|
|
386
|
+
mandatory?: boolean | ((args: any) => boolean); // Whether the flag is required
|
|
387
|
+
defaultValue?: any; // Default value if not provided
|
|
388
|
+
flagOnly?: boolean; // A flag that doesn't consume a value (like --help)
|
|
389
|
+
enum?: any[]; // An array of allowed values
|
|
390
|
+
validate?: (value: any, parsedArgs?: any) => boolean | string | void; // Custom validation function
|
|
391
|
+
allowMultiple?: boolean; // Allow the flag to be provided multiple times
|
|
392
|
+
env?: string; // Links the flag to an environment variable for DXT packages, will automatically generate user_config entries in the DXT manifest and fill the flag value to the ENV value if found (process.env)
|
|
401
393
|
}
|
|
402
394
|
```
|
|
403
395
|
|
|
404
396
|
### Type Handling and Validation
|
|
405
397
|
|
|
406
|
-
ArgParser handles type conversion
|
|
398
|
+
ArgParser automatically handles type conversion and validation:
|
|
407
399
|
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
type: Number, // Automatically converts value to a number
|
|
413
|
-
})
|
|
414
|
-
.addFlag({
|
|
415
|
-
name: "data",
|
|
416
|
-
options: ["--data"],
|
|
417
|
-
type: JSON.parse, // Use a function to parse complex types like JSON strings
|
|
418
|
-
description: "JSON data to process"
|
|
419
|
-
})
|
|
420
|
-
.addFlag({
|
|
421
|
-
name: "environment",
|
|
422
|
-
options: ["--env"],
|
|
423
|
-
type: "string",
|
|
424
|
-
enum: ["dev", "staging", "prod"], // Validate value against this list
|
|
425
|
-
description: "Deployment environment",
|
|
426
|
-
})
|
|
427
|
-
.addFlag({
|
|
428
|
-
name: "id",
|
|
429
|
-
options: ["--id"],
|
|
430
|
-
type: "string",
|
|
431
|
-
validate: (value) => /^[a-f0-9]+$/.test(value), // Custom validation function
|
|
432
|
-
description: "Hexadecimal ID",
|
|
433
|
-
})
|
|
434
|
-
.addFlag({
|
|
435
|
-
name: "config",
|
|
436
|
-
options: ["-c"],
|
|
437
|
-
allowMultiple: true,
|
|
438
|
-
type: path => require(path), // Load config from path (example)
|
|
439
|
-
description: "Load multiple configuration files"
|
|
440
|
-
})
|
|
441
|
-
```
|
|
442
|
-
|
|
443
|
-
### Mandatory Flags
|
|
444
|
-
|
|
445
|
-
Flags can be made mandatory using the `mandatory` property, or its alias "required". This can be a boolean or a function that receives the currently parsed arguments and returns a boolean.
|
|
446
|
-
|
|
447
|
-
```typescript
|
|
448
|
-
.addFlag({
|
|
449
|
-
name: "input",
|
|
450
|
-
options: ["--in"],
|
|
451
|
-
type: String,
|
|
452
|
-
mandatory: true, // Always mandatory
|
|
453
|
-
description: "Input file path",
|
|
454
|
-
})
|
|
455
|
-
.addFlag({
|
|
456
|
-
name: "output",
|
|
457
|
-
options: ["--out"],
|
|
458
|
-
type: String,
|
|
459
|
-
mandatory: (args) => args.format === "json", // Mandatory only if --format is "json"
|
|
460
|
-
description: "Output file path (required for JSON output)",
|
|
461
|
-
})
|
|
462
|
-
```
|
|
400
|
+
- **String flags**: `--name value` or `--name="quoted value"`
|
|
401
|
+
- **Number flags**: `--count 42` (automatically parsed)
|
|
402
|
+
- **Boolean flags**: `--verbose` (presence implies `true`)
|
|
403
|
+
- **Array flags**: `--tags tag1,tag2,tag3` or multiple `--tag value1 --tag value2` (requires `allowMultiple: true`)
|
|
463
404
|
|
|
464
|
-
|
|
405
|
+
### Hierarchical CLIs (Sub-Commands)
|
|
465
406
|
|
|
466
|
-
|
|
407
|
+
While `addTool()` is the recommended way to create subcommands that are also MCP-compatible, you can use `.addSubCommand()` for traditional CLI hierarchies.
|
|
467
408
|
|
|
468
|
-
|
|
409
|
+
> **Note**: By default, subcommands created with `.addSubCommand()` are exposed to MCP as tools. If you want to create CLI-only subcommands, set `includeSubCommands: false` when adding tools.
|
|
469
410
|
|
|
470
411
|
```typescript
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
options: ["-
|
|
474
|
-
type: Number,
|
|
475
|
-
defaultValue: 3000, // Default port is 3000 if -p or --port is not used
|
|
476
|
-
description: "Server port",
|
|
477
|
-
})
|
|
478
|
-
```
|
|
479
|
-
|
|
480
|
-
### Flag-Only Flags
|
|
481
|
-
|
|
482
|
-
Flags that do not expect a value (like `--verbose` or `--force`) should have `flagOnly: true`. When `flagOnly` is false (the default), the parser expects the next argument to be the flag's value.
|
|
483
|
-
|
|
484
|
-
```typescript
|
|
485
|
-
.addFlag({
|
|
486
|
-
name: "verbose",
|
|
487
|
-
options: ["-v"],
|
|
488
|
-
type: Boolean, // Typically boolean for flag-only flags
|
|
489
|
-
flagOnly: true,
|
|
490
|
-
description: "Enable verbose output",
|
|
491
|
-
})
|
|
492
|
-
```
|
|
493
|
-
|
|
494
|
-
### Alias Properties
|
|
495
|
-
|
|
496
|
-
For convenience, `ArgParser` supports aliases for some flag properties:
|
|
497
|
-
|
|
498
|
-
- `default` is an alias for `defaultValue`.
|
|
499
|
-
- `required` is an alias for `mandatory`.
|
|
500
|
-
If both the original property and its alias are provided, the original property (`defaultValue`, `mandatory`) takes precedence.
|
|
501
|
-
|
|
502
|
-
## Hierarchical CLIs (Sub-Commands)
|
|
503
|
-
|
|
504
|
-
ArgParser excels at building CLIs with nested commands, like `git clone` or `docker build`.
|
|
505
|
-
|
|
506
|
-
### Defining Sub-Commands
|
|
507
|
-
|
|
508
|
-
Define sub-commands using the `subCommands` option in the `ArgParser` constructor or the `.addSubCommand(subCommand)` method. Each sub-command requires a `name`, `description`, and a dedicated `ArgParser` instance for its own flags and nested sub-commands.
|
|
509
|
-
|
|
510
|
-
Note that each flag name set is debounced to make sure there are no duplicates, but the flags are sandboxed within their respective sub-commands. So it's ok to use the same flag on different sub-commands.
|
|
511
|
-
|
|
512
|
-
```typescript
|
|
513
|
-
import {
|
|
514
|
-
ArgParser,
|
|
515
|
-
HandlerContext,
|
|
516
|
-
ISubCommand,
|
|
517
|
-
} from "@alcyone-labs/arg-parser";
|
|
518
|
-
|
|
519
|
-
const deployParser = new ArgParser().addFlags([
|
|
520
|
-
{ name: "target", options: ["-t"], type: String, mandatory: true },
|
|
521
|
-
]);
|
|
522
|
-
|
|
523
|
-
const monitorLogsParser = new ArgParser().addFlags([
|
|
524
|
-
{ name: "follow", options: ["-f"], flagOnly: true, type: Boolean },
|
|
412
|
+
// Create a parser for a nested command
|
|
413
|
+
const logsParser = new ArgParser().addFlags([
|
|
414
|
+
{ name: "follow", options: ["-f"], type: "boolean", flagOnly: true },
|
|
525
415
|
]);
|
|
526
416
|
|
|
417
|
+
// This creates a command group: `my-cli monitor`
|
|
527
418
|
const monitorParser = new ArgParser().addSubCommand({
|
|
528
419
|
name: "logs",
|
|
529
|
-
description: "Show logs",
|
|
530
|
-
parser:
|
|
531
|
-
handler: ({ args }) => {
|
|
532
|
-
console.log(`Showing logs... Follow: ${args.follow}`);
|
|
533
|
-
},
|
|
420
|
+
description: "Show application logs",
|
|
421
|
+
parser: logsParser,
|
|
422
|
+
handler: ({ args }) => console.log(`Following logs: ${args.follow}`),
|
|
534
423
|
});
|
|
535
424
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
description: "
|
|
540
|
-
|
|
541
|
-
{
|
|
542
|
-
name: "deploy",
|
|
543
|
-
description: "Deploy resources",
|
|
544
|
-
parser: deployParser,
|
|
545
|
-
handler: ({ args }) => {
|
|
546
|
-
console.log(`Deploying to ${args.target}`);
|
|
547
|
-
},
|
|
548
|
-
},
|
|
549
|
-
{
|
|
550
|
-
name: "monitor",
|
|
551
|
-
description: "Monitoring commands",
|
|
552
|
-
parser: monitorParser,
|
|
553
|
-
},
|
|
554
|
-
],
|
|
425
|
+
// Attach the command group to the main CLI
|
|
426
|
+
const cli = new ArgParser().addSubCommand({
|
|
427
|
+
name: "monitor",
|
|
428
|
+
description: "Monitoring commands",
|
|
429
|
+
parser: monitorParser,
|
|
555
430
|
});
|
|
556
431
|
|
|
557
|
-
//
|
|
558
|
-
// my-cli deploy -t production
|
|
559
|
-
// my-cli monitor logs -f
|
|
560
|
-
```
|
|
561
|
-
|
|
562
|
-
### Handler Execution
|
|
563
|
-
|
|
564
|
-
A core feature is associating handler functions with commands. Handlers are functions (`(ctx: HandlerContext) => void`) that contain the logic to be executed when a specific command (root or sub-command) is successfully parsed and matched.
|
|
565
|
-
|
|
566
|
-
Handlers can be defined in the `ISubCommand` object or set/updated later using the `.setHandler()` method on the command's parser instance.
|
|
567
|
-
|
|
568
|
-
**By default, after successful parsing, ArgParser will execute the handler associated with the _final command_ matched in the argument chain.** For example, running `my-cli service start` will execute the handler for the `start` command, not `my-cli` or `service`.
|
|
569
|
-
|
|
570
|
-
If you need to parse arguments but _prevent_ handler execution, you can pass the `skipHandlers: true` option to the `parse()` method:
|
|
571
|
-
|
|
572
|
-
```typescript
|
|
573
|
-
const args = parser.parse(process.argv.slice(2), { skipHandlers: true });
|
|
574
|
-
// Handlers will NOT be executed, you can inspect 'args' and decide what to do
|
|
575
|
-
```
|
|
576
|
-
|
|
577
|
-
### Handler Context
|
|
578
|
-
|
|
579
|
-
Handler functions receive a single argument, a `HandlerContext` object, containing information about the parsing result and the command chain:
|
|
580
|
-
|
|
581
|
-
```typescript
|
|
582
|
-
type HandlerContext = {
|
|
583
|
-
args: TParsedArgs<any>; // Arguments parsed by and defined for the FINAL command's parser
|
|
584
|
-
parentArgs?: TParsedArgs<any>; // Combined arguments from PARENT parsers (less relevant with inheritParentFlags)
|
|
585
|
-
commandChain: string[]; // Array of command names from root to final command
|
|
586
|
-
};
|
|
432
|
+
// Usage: my-cli monitor logs -f
|
|
587
433
|
```
|
|
588
434
|
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
### Setting Handlers with `.setHandler()`
|
|
592
|
-
|
|
593
|
-
You can define or override a parser instance's handler after its creation:
|
|
435
|
+
#### MCP Exposure Control
|
|
594
436
|
|
|
595
437
|
```typescript
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
myCommandParser.setHandler((ctx) => {
|
|
599
|
-
console.log(`Executing handler for ${ctx.commandChain.join(" -> ")}`);
|
|
600
|
-
// ... command logic ...
|
|
601
|
-
});
|
|
602
|
-
|
|
603
|
-
// You can also retrieve a sub-parser and set its handler:
|
|
604
|
-
const subParser = cli.getSubCommand("deploy")?.parser;
|
|
605
|
-
if (subParser) {
|
|
606
|
-
subParser.setHandler((ctx) => {
|
|
607
|
-
console.log("Overridden deploy handler!");
|
|
608
|
-
// ... new deploy logic ...
|
|
609
|
-
});
|
|
610
|
-
}
|
|
611
|
-
```
|
|
612
|
-
|
|
613
|
-
### Accessing Sub-Parsers with `.getSubCommand()`
|
|
438
|
+
// By default, subcommands are exposed to MCP
|
|
439
|
+
const mcpTools = parser.toMcpTools(); // Includes all subcommands
|
|
614
440
|
|
|
615
|
-
|
|
441
|
+
// To exclude subcommands from MCP (CLI-only)
|
|
442
|
+
const mcpToolsOnly = parser.toMcpTools({ includeSubCommands: false });
|
|
616
443
|
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
// Access the parser instance:
|
|
622
|
-
const deployParserInstance = deploySubCommand.parser;
|
|
623
|
-
// Add a flag specifically to the deploy command after initial setup:
|
|
624
|
-
deployParserInstance.addFlag({
|
|
625
|
-
name: "force",
|
|
626
|
-
options: ["--force"],
|
|
627
|
-
flagOnly: true,
|
|
628
|
-
type: Boolean,
|
|
629
|
-
});
|
|
630
|
-
}
|
|
444
|
+
// Name conflicts: You cannot have both addSubCommand("name") and addTool({ name: "name" })
|
|
445
|
+
// This will throw an error:
|
|
446
|
+
parser.addSubCommand({ name: "process", parser: subParser });
|
|
447
|
+
parser.addTool({ name: "process", handler: async () => {} }); // ❌ Error: Sub-command 'process' already exists
|
|
631
448
|
```
|
|
632
449
|
|
|
633
450
|
### Flag Inheritance (`inheritParentFlags`)
|
|
634
451
|
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
If a flag with the same name exists in both the parent and the child, the child's definition takes precedence. The built-in `--help` flag is never inherited.
|
|
452
|
+
To share common flags (like `--verbose` or `--config`) across sub-commands, set `inheritParentFlags: true` in the sub-command's parser.
|
|
638
453
|
|
|
639
454
|
```typescript
|
|
640
455
|
const parentParser = new ArgParser().addFlags([
|
|
641
|
-
{ name: "verbose", options: ["-v"], type:
|
|
642
|
-
{ name: "config", options: ["-c"], type: String }, // Common config flag
|
|
456
|
+
{ name: "verbose", options: ["-v"], type: "boolean" },
|
|
643
457
|
]);
|
|
644
458
|
|
|
459
|
+
// This child parser will automatically have the --verbose flag
|
|
645
460
|
const childParser = new ArgParser({ inheritParentFlags: true }).addFlags([
|
|
646
|
-
{ name: "
|
|
647
|
-
{ name: "config", options: ["--child-config"], type: Number }, // Override config flag
|
|
461
|
+
{ name: "target", options: ["-t"], type: "string" },
|
|
648
462
|
]);
|
|
649
463
|
|
|
650
|
-
parentParser.addSubCommand({
|
|
651
|
-
name: "child",
|
|
652
|
-
description: "A child command",
|
|
653
|
-
parser: childParser,
|
|
654
|
-
});
|
|
655
|
-
|
|
656
|
-
// The 'child' parser now effectively has flags: --help, -v, -l, --child-config
|
|
657
|
-
// Running `parent child -v -l value --child-config 123` will parse all these flags.
|
|
464
|
+
parentParser.addSubCommand({ name: "deploy", parser: childParser });
|
|
658
465
|
```
|
|
659
466
|
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
ArgParser provides robust automatic help generation.
|
|
663
|
-
|
|
664
|
-
### Global Help Flag (`--help`, `-h`)
|
|
665
|
-
|
|
666
|
-
A `--help` (and `-h`) flag is automatically added to every parser instance (root and sub-commands). When this flag is encountered during parsing:
|
|
667
|
-
|
|
668
|
-
1. ArgParser stops processing arguments.
|
|
669
|
-
2. Generates and prints the help text relevant to the current command/sub-command context.
|
|
670
|
-
3. Exits the process with code 0.
|
|
671
|
-
|
|
672
|
-
This behavior is triggered automatically unless `skipHelpHandling: true` is passed to the `parse()` method.
|
|
673
|
-
|
|
674
|
-
```bash
|
|
675
|
-
# Shows help for the root command
|
|
676
|
-
my-cli --help
|
|
677
|
-
|
|
678
|
-
# Shows help for the 'deploy' sub-command
|
|
679
|
-
my-cli deploy --help
|
|
680
|
-
```
|
|
681
|
-
|
|
682
|
-
### `helpText()` Method
|
|
683
|
-
|
|
684
|
-
You can manually generate the help text for any parser instance at any time using the `helpText()` method. This returns a string containing the formatted help output.
|
|
685
|
-
|
|
686
|
-
```typescript
|
|
687
|
-
console.log(parser.helpText());
|
|
688
|
-
```
|
|
689
|
-
|
|
690
|
-
### Auto-Help on Empty Invocation
|
|
691
|
-
|
|
692
|
-
For the root command, if you invoke the script **without any arguments** and the root parser **does not have a handler defined**, ArgParser will automatically display the root help text and exit cleanly (code 0). This provides immediate guidance for users who just type the script name.
|
|
693
|
-
|
|
694
|
-
If the root parser _does_ have a handler, it's assumed that the handler will manage the empty invocation case, and auto-help will not trigger.
|
|
695
|
-
|
|
696
|
-
## Error Handling
|
|
697
|
-
|
|
698
|
-
ArgParser includes built-in error handling for common parsing errors like missing mandatory flags, invalid types, or unknown commands.
|
|
699
|
-
|
|
700
|
-
By default (`handleErrors: true`):
|
|
701
|
-
|
|
702
|
-
1. A descriptive, colored error message is printed to `stderr`.
|
|
703
|
-
2. A suggestion to use `--help` is included, showing the correct command path.
|
|
704
|
-
3. The process exits with status code 1.
|
|
705
|
-
|
|
706
|
-
```typescript
|
|
707
|
-
// Example (assuming 'data-proc' is appCommandName and 'phase' is mandatory)
|
|
708
|
-
// Running `data-proc` would output:
|
|
709
|
-
|
|
710
|
-
// Error: Missing mandatory flags: phase
|
|
711
|
-
//
|
|
712
|
-
// Try 'data-proc --help' for usage details.
|
|
713
|
-
```
|
|
714
|
-
|
|
715
|
-
You can disable this behavior by setting `handleErrors: false` in the `ArgParser` constructor options. When disabled, ArgParser will throw an `ArgParserError` exception on parsing errors, allowing you to catch and handle them programmatically.
|
|
716
|
-
|
|
717
|
-
```typescript
|
|
718
|
-
import { ArgParser, ArgParserError } from "@alcyone-labs/arg-parser";
|
|
719
|
-
|
|
720
|
-
const parser = new ArgParser({
|
|
721
|
-
appCommandName: "my-app",
|
|
722
|
-
handleErrors: false, // Disable default handling
|
|
723
|
-
});
|
|
724
|
-
|
|
725
|
-
try {
|
|
726
|
-
const args = parser.parse(process.argv.slice(2));
|
|
727
|
-
// Process args if parsing succeeded
|
|
728
|
-
} catch (error) {
|
|
729
|
-
if (error instanceof ArgParserError) {
|
|
730
|
-
console.error(`\nCustom Parse Error: ${error.message}`);
|
|
731
|
-
// Implement custom logic (e.g., logging, different exit codes)
|
|
732
|
-
process.exit(1);
|
|
733
|
-
} else {
|
|
734
|
-
// Handle unexpected errors
|
|
735
|
-
console.error("An unexpected error occurred:", error);
|
|
736
|
-
process.exit(1);
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
```
|
|
740
|
-
|
|
741
|
-
## Environment Configuration Export
|
|
742
|
-
|
|
743
|
-
ArgParser includes a built-in system flag `--s-save-to-env` that allows you to export the current parser's configuration and parsed arguments to various file formats. This is useful for creating configuration templates, documenting CLI usage, or generating environment files for deployment.
|
|
744
|
-
|
|
745
|
-
### Usage
|
|
746
|
-
|
|
747
|
-
```bash
|
|
748
|
-
# Export to .env format (default for no extension)
|
|
749
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.env
|
|
750
|
-
|
|
751
|
-
# Export to YAML format
|
|
752
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.yaml
|
|
753
|
-
|
|
754
|
-
# Export to JSON format
|
|
755
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.json
|
|
756
|
-
|
|
757
|
-
# Export to TOML format
|
|
758
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.toml
|
|
759
|
-
```
|
|
760
|
-
|
|
761
|
-
### Supported Formats
|
|
762
|
-
|
|
763
|
-
The format is automatically detected based on the file extension:
|
|
764
|
-
|
|
765
|
-
- **`.env`** (or no extension): Bash environment variable format
|
|
766
|
-
- **`.yaml` / `.yml`**: YAML format
|
|
767
|
-
- **`.json` / `.jsonc`**: JSON format with metadata
|
|
768
|
-
- **`.toml` / `.tml`**: TOML format
|
|
769
|
-
|
|
770
|
-
### Behavior
|
|
771
|
-
|
|
772
|
-
- **Works at any parser level**: Can be used with root commands or sub-commands
|
|
773
|
-
- **Includes inherited flags**: Shows flags from the current parser and all parent parsers in the chain
|
|
774
|
-
- **Comments optional flags**: Flags that are optional and not set are commented out but still documented
|
|
775
|
-
- **Preserves values**: Set flags show their actual values, unset flags show default values or are commented out
|
|
776
|
-
- **Rich documentation**: Each flag includes its description, options, type, and constraints
|
|
777
|
-
|
|
778
|
-
### Example Output
|
|
779
|
-
|
|
780
|
-
For a CLI with flags `--verbose`, `--output file.txt`, and `--count 5`:
|
|
781
|
-
|
|
782
|
-
**`.env` format:**
|
|
783
|
-
```bash
|
|
784
|
-
# Environment configuration generated by ArgParser
|
|
785
|
-
# Format: Bash .env style
|
|
786
|
-
|
|
787
|
-
# verbose: Enable verbose output
|
|
788
|
-
# Options: -v, --verbose
|
|
789
|
-
# Type: Boolean
|
|
790
|
-
# Default: false
|
|
791
|
-
VERBOSE="true"
|
|
792
|
-
|
|
793
|
-
# output: Output file path
|
|
794
|
-
# Options: -o, --output
|
|
795
|
-
# Type: String
|
|
796
|
-
OUTPUT="file.txt"
|
|
797
|
-
|
|
798
|
-
# count: Number of items to process
|
|
799
|
-
# Options: -c, --count
|
|
800
|
-
# Type: Number
|
|
801
|
-
# Default: 10
|
|
802
|
-
COUNT="5"
|
|
803
|
-
```
|
|
804
|
-
|
|
805
|
-
**`.yaml` format:**
|
|
806
|
-
```yaml
|
|
807
|
-
# Environment configuration generated by ArgParser
|
|
808
|
-
# Format: YAML
|
|
809
|
-
|
|
810
|
-
# verbose: Enable verbose output
|
|
811
|
-
# Options: -v, --verbose
|
|
812
|
-
# Type: Boolean
|
|
813
|
-
# Default: false
|
|
814
|
-
|
|
815
|
-
verbose: true
|
|
816
|
-
output: "file.txt"
|
|
817
|
-
count: 5
|
|
818
|
-
```
|
|
819
|
-
|
|
820
|
-
## System Flags (v1.1.0+)
|
|
821
|
-
|
|
822
|
-
ArgParser includes several built-in system flags that provide debugging, configuration management, and introspection capabilities. These flags are processed before normal argument parsing and will cause the program to exit after execution.
|
|
823
|
-
|
|
824
|
-
### **Overview**
|
|
825
|
-
|
|
826
|
-
System flags use the `--s-*` pattern and provide powerful development and deployment tools:
|
|
827
|
-
|
|
828
|
-
- **`--s-debug`**: Runtime debugging with step-by-step parsing analysis
|
|
829
|
-
- **`--s-with-env <file>`**: Load configuration from files (`.env`, `.yaml`, `.json`, `.toml`)
|
|
830
|
-
- **`--s-save-to-env <file>`**: Export current configuration to various formats
|
|
831
|
-
- **`--s-debug-print`**: Export complete parser configuration for inspection
|
|
832
|
-
- **`--s-enable-fuzzy`**: Enable fuzzy testing mode (dry-run with no side effects)
|
|
833
|
-
- **`--s-save-DXT [dir]`**: Generate DXT packages for MCP servers (Desktop Extensions)
|
|
834
|
-
|
|
835
|
-
### `--s-save-to-env <file>`
|
|
836
|
-
|
|
837
|
-
Exports the current parser's configuration and parsed arguments to various file formats.
|
|
838
|
-
|
|
839
|
-
```bash
|
|
840
|
-
# Export to .env format (default for no extension)
|
|
841
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.env
|
|
842
|
-
|
|
843
|
-
# Export to YAML format
|
|
844
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.yaml
|
|
845
|
-
|
|
846
|
-
# Export to JSON format
|
|
847
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.json
|
|
848
|
-
|
|
849
|
-
# Export to TOML format
|
|
850
|
-
your-cli --flag1 value1 --flag2 --s-save-to-env config.toml
|
|
851
|
-
```
|
|
852
|
-
|
|
853
|
-
**Features:**
|
|
854
|
-
- Works at any parser level (root command or sub-commands)
|
|
855
|
-
- Includes inherited flags from parent parsers in the chain
|
|
856
|
-
- Comments out optional flags that are not set
|
|
857
|
-
- Rich documentation for each flag (description, options, type, constraints)
|
|
858
|
-
- Automatic format detection based on file extension
|
|
859
|
-
|
|
860
|
-
### `--s-with-env <file>`
|
|
861
|
-
|
|
862
|
-
Loads configuration from a file and merges it with command line arguments. CLI arguments take precedence over file configuration.
|
|
863
|
-
|
|
864
|
-
```bash
|
|
865
|
-
# Load from .env format (default for no extension)
|
|
866
|
-
your-cli --s-with-env config.env
|
|
867
|
-
|
|
868
|
-
# Load from YAML format
|
|
869
|
-
your-cli --s-with-env config.yaml
|
|
870
|
-
|
|
871
|
-
# Load from JSON format
|
|
872
|
-
your-cli --s-with-env config.json
|
|
873
|
-
|
|
874
|
-
# Load from TOML format
|
|
875
|
-
your-cli --s-with-env config.toml
|
|
876
|
-
|
|
877
|
-
# Combine with CLI arguments (CLI args override file config)
|
|
878
|
-
your-cli --s-with-env config.yaml --verbose --output override.txt
|
|
879
|
-
```
|
|
880
|
-
|
|
881
|
-
**Supported Formats:**
|
|
882
|
-
|
|
883
|
-
The format is automatically detected based on the file extension:
|
|
884
|
-
|
|
885
|
-
- **`.env`** (or no extension): Dotenv format with `KEY=value` pairs
|
|
886
|
-
- **`.yaml` / `.yml`**: YAML format
|
|
887
|
-
- **`.json` / `.jsonc`**: JSON format (metadata is ignored if present)
|
|
888
|
-
- **`.toml` / `.tml`**: TOML format
|
|
889
|
-
|
|
890
|
-
**Behavior:**
|
|
891
|
-
|
|
892
|
-
- **File validation**: Checks if the file exists and can be parsed
|
|
893
|
-
- **Type conversion**: Automatically converts values to match flag types (boolean, number, string, array)
|
|
894
|
-
- **Enum validation**: Validates values against allowed enum options
|
|
895
|
-
- **CLI precedence**: Command line arguments override file configuration
|
|
896
|
-
- **Error handling**: Exits with error code 1 if file cannot be loaded or parsed
|
|
897
|
-
- **Flag matching**: Only loads values for flags that exist in the current parser chain
|
|
898
|
-
|
|
899
|
-
**Example Configuration Files:**
|
|
900
|
-
|
|
901
|
-
**.env format:**
|
|
902
|
-
```bash
|
|
903
|
-
VERBOSE=true
|
|
904
|
-
OUTPUT=file.txt
|
|
905
|
-
COUNT=5
|
|
906
|
-
TAGS=tag1,tag2,tag3
|
|
907
|
-
```
|
|
908
|
-
|
|
909
|
-
**YAML format:**
|
|
910
|
-
```yaml
|
|
911
|
-
verbose: true
|
|
912
|
-
output: file.txt
|
|
913
|
-
count: 5
|
|
914
|
-
tags:
|
|
915
|
-
- tag1
|
|
916
|
-
- tag2
|
|
917
|
-
- tag3
|
|
918
|
-
```
|
|
919
|
-
|
|
920
|
-
**JSON format:**
|
|
921
|
-
```json
|
|
922
|
-
{
|
|
923
|
-
"verbose": true,
|
|
924
|
-
"output": "file.txt",
|
|
925
|
-
"count": 5,
|
|
926
|
-
"tags": ["tag1", "tag2", "tag3"]
|
|
927
|
-
}
|
|
928
|
-
```
|
|
929
|
-
|
|
930
|
-
### `--s-debug-print`
|
|
931
|
-
|
|
932
|
-
Prints the complete parser configuration to a JSON file and console for debugging complex parser setups.
|
|
933
|
-
|
|
934
|
-
```bash
|
|
935
|
-
your-cli --s-debug-print
|
|
936
|
-
```
|
|
937
|
-
|
|
938
|
-
**Output:**
|
|
939
|
-
- Creates `ArgParser.full.json` with the complete parser structure
|
|
940
|
-
- Shows all flags, sub-commands, handlers, and configuration
|
|
941
|
-
- Useful for debugging complex parser hierarchies
|
|
942
|
-
- Human-readable console output with syntax highlighting
|
|
943
|
-
|
|
944
|
-
### `--s-debug`
|
|
945
|
-
|
|
946
|
-
Provides detailed runtime debugging information showing how arguments are parsed step-by-step.
|
|
947
|
-
|
|
948
|
-
```bash
|
|
949
|
-
your-cli --flag1 value1 sub-command --flag2 value2 --s-debug
|
|
950
|
-
```
|
|
951
|
-
|
|
952
|
-
**Output:**
|
|
953
|
-
- Shows command chain identification process
|
|
954
|
-
- Step-by-step argument parsing simulation
|
|
955
|
-
- Final parser identification
|
|
956
|
-
- Accumulated arguments at each level
|
|
957
|
-
- Remaining arguments after parsing
|
|
958
|
-
- Complete static configuration of the final parser
|
|
959
|
-
|
|
960
|
-
**Useful for:**
|
|
961
|
-
- Understanding complex command chains
|
|
962
|
-
- Debugging argument parsing issues
|
|
963
|
-
- Seeing how flags are inherited between parsers
|
|
964
|
-
- Troubleshooting sub-command resolution
|
|
965
|
-
|
|
966
|
-
### Usage Notes
|
|
967
|
-
|
|
968
|
-
- System flags are processed before normal argument parsing
|
|
969
|
-
- They cause the program to exit after execution (exit code 0 for success)
|
|
970
|
-
- Can be used with any combination of regular flags and sub-commands
|
|
971
|
-
- Particularly useful during development and debugging
|
|
972
|
-
|
|
973
|
-
## Debugging
|
|
974
|
-
|
|
975
|
-
### Programmatic Debugging
|
|
976
|
-
|
|
977
|
-
The `printAll(filePath?: string)` method is useful for debugging complex parser configurations programmatically. It recursively outputs the structure, options, flags, and handlers of a parser instance and its sub-commands.
|
|
978
|
-
|
|
979
|
-
- `parser.printAll()`: Prints a colored, human-readable output to the console.
|
|
980
|
-
- `parser.printAll('./config.json')`: Writes the configuration as a pretty-printed JSON file.
|
|
981
|
-
- `parser.printAll('./config.log')`: Writes a plain text version to a file.
|
|
982
|
-
|
|
983
|
-
```typescript
|
|
984
|
-
import { ArgParser } from "@alcyone-labs/arg-parser";
|
|
985
|
-
|
|
986
|
-
const parser = new ArgParser({ appName: "Debug App" })
|
|
987
|
-
.addFlags([
|
|
988
|
-
/* ... */
|
|
989
|
-
])
|
|
990
|
-
.addSubCommand(/* ... */);
|
|
991
|
-
|
|
992
|
-
parser.printAll(); // Output to console
|
|
993
|
-
```
|
|
994
|
-
|
|
995
|
-
### Runtime Debugging
|
|
996
|
-
|
|
997
|
-
For runtime debugging, use the system flags documented above:
|
|
467
|
+
---
|
|
998
468
|
|
|
999
|
-
|
|
1000
|
-
- `--s-debug`: Show step-by-step argument parsing process
|
|
1001
|
-
- `--s-save-to-env <file>`: Export current configuration to various formats
|
|
1002
|
-
- `--s-with-env <file>`: Load configuration from file and merge with CLI arguments
|
|
469
|
+
## MCP & Claude Desktop Integration
|
|
1003
470
|
|
|
1004
|
-
### `--s-
|
|
471
|
+
### Automatic MCP Server Mode (`--s-mcp-serve`)
|
|
1005
472
|
|
|
1006
|
-
|
|
473
|
+
You don't need to write any server logic. Run your application with the `--s-mcp-serve` flag, and ArgParser will automatically start a compliant MCP server, exposing all tools defined with `.addTool()` and subcommands created with `.addSubCommand()` (unless `includeSubCommands: false` is set).
|
|
1007
474
|
|
|
1008
475
|
```bash
|
|
1009
|
-
#
|
|
1010
|
-
|
|
1011
|
-
```
|
|
1012
|
-
|
|
1013
|
-
**Features:**
|
|
1014
|
-
- **Automatic execution prevention**: No need for complex conditional logic in your CLI code
|
|
1015
|
-
- **Zero boilerplate**: Simply export your CLI with `export default cli` and call `cli.parse()`
|
|
1016
|
-
- Disables error handling to allow error collection
|
|
1017
|
-
- Skips mandatory flag validation for comprehensive testing
|
|
1018
|
-
- **Prevents handler function execution** (no side effects)
|
|
1019
|
-
- **Logs what each handler would receive** for testing visibility
|
|
1020
|
-
- Recursively applies to all subcommand parsers
|
|
1021
|
-
- Safe for testing production CLIs with database operations, file modifications, or API calls
|
|
1022
|
-
|
|
1023
|
-
**Example Output:**
|
|
1024
|
-
```
|
|
1025
|
-
[--s-enable-fuzzy] handler() skipped for command chain: (root)
|
|
1026
|
-
Input args: [--s-enable-fuzzy --input test.txt --format json]
|
|
1027
|
-
Parsed args: {"input":"test.txt","format":"json"}
|
|
1028
|
-
```
|
|
1029
|
-
|
|
1030
|
-
**Use Cases:**
|
|
1031
|
-
- Fuzzy testing CLI argument parsing
|
|
1032
|
-
- Validating CLI configuration without executing business logic
|
|
1033
|
-
- Testing complex command hierarchies safely
|
|
1034
|
-
- Automated testing of CLI interfaces
|
|
1035
|
-
|
|
1036
|
-
These system flags are particularly useful when you need to debug a CLI application without modifying the source code.
|
|
1037
|
-
|
|
1038
|
-
## Fuzzy Testing
|
|
1039
|
-
|
|
1040
|
-
ArgParser includes comprehensive fuzzy testing capabilities to automatically test CLI configurations and catch edge cases that manual testing might miss. The fuzzy testing utility systematically explores command paths and generates various flag combinations to ensure robustness.
|
|
1041
|
-
|
|
1042
|
-
### **Quick Start**
|
|
1043
|
-
|
|
1044
|
-
Test any ArgParser configuration using the built-in fuzzy testing CLI:
|
|
476
|
+
# This single command starts a fully compliant MCP server
|
|
477
|
+
my-cli-app --s-mcp-serve
|
|
1045
478
|
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
bun src/fuzzy-test-cli.ts --file examples/getting-started.ts
|
|
1049
|
-
|
|
1050
|
-
# Test with custom options and save results
|
|
1051
|
-
bun src/fuzzy-test-cli.ts \
|
|
1052
|
-
--file examples/getting-started.ts \
|
|
1053
|
-
--output test-results.json \
|
|
1054
|
-
--format json \
|
|
1055
|
-
--max-depth 3 \
|
|
1056
|
-
--random-tests 20 \
|
|
1057
|
-
--verbose
|
|
479
|
+
# You can also override transports and ports using system flags
|
|
480
|
+
my-cli-app --s-mcp-serve --s-mcp-transport sse --s-mcp-port 3001
|
|
1058
481
|
```
|
|
1059
482
|
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
### **System Flag Integration**
|
|
483
|
+
### MCP Transports
|
|
1063
484
|
|
|
1064
|
-
|
|
485
|
+
You can define the transports directly in the .withMcp() settings, or override them via the `--s-mcp-transport(s)` flags.
|
|
1065
486
|
|
|
1066
487
|
```bash
|
|
1067
|
-
#
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
# The fuzzy testing CLI automatically uses this flag
|
|
1071
|
-
bun src/fuzzy-test-cli.ts --file your-cli.ts
|
|
1072
|
-
```
|
|
1073
|
-
|
|
1074
|
-
**Fuzzy mode features:**
|
|
1075
|
-
- **Zero boilerplate**: No conditional logic needed - just `export default cli` and `cli.parse()`
|
|
1076
|
-
- **Automatic prevention**: System automatically prevents CLI execution during fuzzy testing
|
|
1077
|
-
- **Dry-run execution**: Prevents handler function execution (no side effects)
|
|
1078
|
-
- **Error collection**: Disables error handling to collect all parsing errors
|
|
1079
|
-
- **Argument logging**: Shows what each handler would receive for testing visibility
|
|
1080
|
-
- **Safe testing**: Test production CLIs with database operations, file modifications, or API calls
|
|
1081
|
-
|
|
1082
|
-
### **Testing Capabilities**
|
|
1083
|
-
|
|
1084
|
-
The fuzzy tester automatically tests:
|
|
488
|
+
# Single transport
|
|
489
|
+
my-tool --s-mcp-serve --s-mcp-transport stdio
|
|
1085
490
|
|
|
1086
|
-
|
|
1087
|
-
-
|
|
1088
|
-
- **Random combinations**: Pseudo-random flag combinations for edge cases
|
|
1089
|
-
- **Command paths**: All subcommand combinations up to configurable depth
|
|
1090
|
-
- **Performance**: Execution timing for different input complexities
|
|
491
|
+
# Multiple transports via JSON
|
|
492
|
+
my-tool --s-mcp-serve --s-mcp-transports '[{"type":"stdio"},{"type":"sse","port":3001}]'
|
|
1091
493
|
|
|
1092
|
-
|
|
494
|
+
# Single transport with custom options
|
|
495
|
+
my-tool --s-mcp-serve --s-mcp-transport sse --s-mcp-port 3000 --s-mcp-host 0.0.0.0
|
|
1093
496
|
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
497
|
+
# Multiple transports (configured via --s-mcp-serve system flag)
|
|
498
|
+
const cli = ArgParser.withMcp({
|
|
499
|
+
appName: 'multi-tool',
|
|
500
|
+
appCommandName: 'multi-tool',
|
|
501
|
+
mcp: {
|
|
502
|
+
serverInfo: {
|
|
503
|
+
name: 'multi-tool-mcp',
|
|
504
|
+
version: '1.0.0'
|
|
505
|
+
},
|
|
506
|
+
transports: [
|
|
507
|
+
// Can be a single string...
|
|
508
|
+
"stdio",
|
|
509
|
+
// or one of the other transport types supported by @modelcontextprotocol/sdk
|
|
510
|
+
{ type: "sse", port: 3000, host: "0.0.0.0" },
|
|
511
|
+
{ type: "websocket", port: 3001, path: "/ws" }
|
|
512
|
+
]
|
|
513
|
+
}
|
|
1104
514
|
});
|
|
1105
|
-
|
|
1106
|
-
const report = await tester.runFuzzyTest();
|
|
1107
|
-
console.log(`Success rate: ${(report.successfulTests / report.totalTests * 100).toFixed(1)}%`);
|
|
1108
515
|
```
|
|
1109
516
|
|
|
1110
|
-
###
|
|
517
|
+
### Automatic Console Safety
|
|
1111
518
|
|
|
1112
|
-
|
|
519
|
+
A major challenge in MCP is preventing `console.log` from corrupting the JSON-RPC communication over `STDOUT`. ArgParser solves this automatically.
|
|
1113
520
|
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
# Machine-readable JSON
|
|
1119
|
-
bun src/fuzzy-test-cli.ts --file my-cli.ts --format json --output results.json
|
|
1120
|
-
|
|
1121
|
-
# Documentation-friendly Markdown
|
|
1122
|
-
bun src/fuzzy-test-cli.ts --file my-cli.ts --format markdown --output report.md
|
|
1123
|
-
```
|
|
521
|
+
- **How it works**: When `--s-mcp-serve` is active, ArgParser hijacks the global `console` object.
|
|
522
|
+
- **What it does**: It redirects `console.log`, `.info`, `.warn`, and `.debug` to `STDERR` with a prefix, making them visible for debugging without interfering with the protocol. `console.error` is preserved on `STDERR` as expected.
|
|
523
|
+
- **Your benefit**: You can write `console.log` statements freely in your handlers. They will work as expected in CLI mode and be safely handled in MCP mode with **zero code changes**.
|
|
1124
524
|
|
|
1125
|
-
|
|
525
|
+
### Generating DXT Packages (`--s-build-dxt`)
|
|
1126
526
|
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
Generates Desktop Extension (DXT) packages for all MCP servers defined in your ArgParser instance. DXT files are zip archives containing a manifest.json and server files, enabling single-click installation of MCP servers in compatible applications like Claude Desktop.
|
|
527
|
+
A Desktop Extension (`.dxt`) is a standardized package for installing your tools into Claude Desktop. ArgParser automates this process.
|
|
1130
528
|
|
|
1131
529
|
```bash
|
|
1132
|
-
# Generate DXT
|
|
1133
|
-
|
|
530
|
+
# 1. Generate the DXT package contents into a directory
|
|
531
|
+
my-cli-app --s-build-dxt ./my-dxt-package
|
|
1134
532
|
|
|
1135
|
-
#
|
|
1136
|
-
|
|
533
|
+
# The output folder contains everything needed: manifest.json, entry point, etc.
|
|
534
|
+
# A default logo will be applied if you don't provide one.
|
|
1137
535
|
|
|
1138
|
-
#
|
|
1139
|
-
|
|
1140
|
-
```
|
|
536
|
+
# 2. (Optional) Pack the folder into a .dxt file for distribution
|
|
537
|
+
npx @anthropic-ai/dxt pack ./my-dxt-package
|
|
1141
538
|
|
|
1142
|
-
|
|
1143
|
-
-
|
|
1144
|
-
- **Multiple servers**: Generates separate DXT files for each MCP server
|
|
1145
|
-
- **Complete tool listing**: Includes all MCP tools in the manifest
|
|
1146
|
-
- **Proper metadata**: Uses actual server names, versions, and descriptions
|
|
1147
|
-
- **Ready to install**: Generated DXT files work with DXT-compatible applications
|
|
539
|
+
# 3. (Optional) Sign the DXT package
|
|
540
|
+
npx @anthropic-ai/dxt sign ./my-dxt-package.dxt
|
|
1148
541
|
|
|
1149
|
-
|
|
1150
|
-
```
|
|
1151
|
-
your-server.dxt (ZIP file)
|
|
1152
|
-
├── manifest.json # Server metadata and tool definitions
|
|
1153
|
-
└── server/
|
|
1154
|
-
└── index.js # Server entry point
|
|
542
|
+
# Then drag & drop the .dxt file into Claude Desktop to install it, in the Settings > Extensions screen.
|
|
1155
543
|
```
|
|
1156
544
|
|
|
1157
|
-
|
|
1158
|
-
```
|
|
1159
|
-
🔧 Generating DXT packages for 2 MCP server(s)...
|
|
1160
|
-
✓ Generated: primary-server.dxt
|
|
1161
|
-
Server: primary-server v1.0.0
|
|
1162
|
-
Tools: 3 tool(s)
|
|
1163
|
-
✓ Generated: analytics-server.dxt
|
|
1164
|
-
Server: analytics-server v2.1.0
|
|
1165
|
-
Tools: 5 tool(s)
|
|
1166
|
-
|
|
1167
|
-
✅ DXT package generation completed!
|
|
1168
|
-
Output directory: /path/to/dxt-packages
|
|
1169
|
-
```
|
|
1170
|
-
|
|
1171
|
-
**Use Cases:**
|
|
1172
|
-
- **Distribution**: Package MCP servers for easy sharing and installation
|
|
1173
|
-
- **Development**: Create test packages during MCP server development
|
|
1174
|
-
- **Deployment**: Generate production-ready DXT files for distribution
|
|
1175
|
-
- **Integration**: Prepare MCP servers for Claude Desktop or other DXT-compatible applications
|
|
1176
|
-
|
|
1177
|
-
## Changelog
|
|
1178
|
-
|
|
1179
|
-
### v1.2.0 (2025-01-02)
|
|
1180
|
-
|
|
1181
|
-
**🔧 Critical MCP Fixes & Improvements**
|
|
1182
|
-
|
|
1183
|
-
- **Fixed MCP Output Schema Support**: Resolved the critical issue where MCP tools with output schemas failed with `"Tool has an output schema but no structured content was provided"` error
|
|
1184
|
-
- **Enhanced Handler Context**: Added `isMcp` flag to handler context for proper MCP mode detection
|
|
1185
|
-
- **Improved Response Format**: MCP tools now correctly return both `content` and `structuredContent` fields as required by JSON-RPC 2.0
|
|
1186
|
-
- **Better Integration**: Handlers can reliably detect when they're being called from MCP mode vs CLI mode
|
|
1187
|
-
|
|
1188
|
-
**What was broken before v1.2.0:**
|
|
1189
|
-
- MCP servers would fail when tools had output schemas defined
|
|
1190
|
-
- Handlers couldn't reliably detect MCP execution context
|
|
1191
|
-
- Response format didn't comply with MCP specification for structured content
|
|
1192
|
-
|
|
1193
|
-
**What works now:**
|
|
1194
|
-
- ✅ MCP tools with output schemas work correctly
|
|
1195
|
-
- ✅ Proper JSON-RPC 2.0 response format with both `content` and `structuredContent`
|
|
1196
|
-
- ✅ Handler context includes `isMcp` flag for mode detection
|
|
1197
|
-
- ✅ Full compatibility with MCP clients and the Model Context Protocol specification
|
|
1198
|
-
|
|
1199
|
-
### v1.1.0 (2024-12-XX)
|
|
1200
|
-
|
|
1201
|
-
**Major Features**
|
|
1202
|
-
- MCP (Model Context Protocol) Integration with multiple transport support
|
|
1203
|
-
- System Flags: `--s-debug-print`, `--s-with-env`, `--s-save-to-env`, `--s-enable-fuzzy`, `--s-save-DXT`
|
|
1204
|
-
- Environment Loading from `.env`, `.yaml`, `.json`, and `.toml` files
|
|
1205
|
-
- Enhanced Debugging and configuration export tools
|
|
1206
|
-
|
|
1207
|
-
## API Reference
|
|
545
|
+
### Logo Configuration
|
|
1208
546
|
|
|
1209
|
-
|
|
547
|
+
The logo will appear in Claude Desktop's Extensions settings and when users interact with your MCP tools. Note that neither ArgParser nor Anthropic packer will modify the logo, so make sure to use a reasonable size, such as 256x256 pixels or 512x512 pixels maximum. Any image type that can display in a browser is supported.
|
|
1210
548
|
|
|
1211
|
-
|
|
549
|
+
You can customize the logo/icon that appears in Claude Desktop for your DXT package by configuring the `logo` property in your `serverInfo`:
|
|
1212
550
|
|
|
1213
|
-
#### `ArgParserBase`
|
|
1214
|
-
|
|
1215
|
-
Base class providing core CLI parsing functionality without MCP features. Use this for lightweight CLIs that don't need MCP server capabilities.
|
|
1216
|
-
|
|
1217
|
-
**Constructor:**
|
|
1218
|
-
- `new ArgParserBase(options?, initialFlags?)`: Create basic parser instance
|
|
1219
|
-
|
|
1220
|
-
#### `ArgParser` (v1.1.0+)
|
|
1221
|
-
|
|
1222
|
-
Main class with built-in MCP server capabilities. Extends `ArgParserBase` with MCP integration.
|
|
1223
|
-
|
|
1224
|
-
**Constructors:**
|
|
1225
|
-
- `new ArgParser(options?, initialFlags?)`: Create parser with MCP capabilities
|
|
1226
|
-
- `ArgParser.withMcp(options?, initialFlags?)`: Factory method for MCP-enabled parser (same as constructor)
|
|
1227
|
-
- `ArgParser.fromArgParser(parser)`: Convert existing ArgParserBase to MCP-enabled
|
|
1228
|
-
|
|
1229
|
-
**MCP Methods:**
|
|
1230
|
-
- `toMcpTools(options?)`: Generate MCP tool structures from CLI definition
|
|
1231
|
-
- `createMcpServer(serverInfo, toolOptions?)`: Create MCP server instance
|
|
1232
|
-
- `startMcpServer(serverInfo, toolOptions?)`: Start MCP server with stdio transport
|
|
1233
|
-
- `startMcpServerWithTransport(serverInfo, transportType, transportOptions?, toolOptions?)`: Start with specific transport
|
|
1234
|
-
- `startMcpServerWithMultipleTransports(serverInfo, transports, toolOptions?)`: Start with multiple transports (manual approach)
|
|
1235
|
-
- `addMcpSubCommand(name, serverInfo, options?)`: Add MCP server sub-command with optional preset transports (recommended approach)
|
|
1236
|
-
- `parse(args, options?)`: Async version supporting async handlers
|
|
1237
|
-
|
|
1238
|
-
**MCP Types:**
|
|
1239
|
-
- `McpTransportConfig`: Configuration for a single transport (`{ type, port?, host?, path?, sessionIdGenerator? }`)
|
|
1240
|
-
- `McpSubCommandOptions`: Options for MCP sub-command (`{ defaultTransport?, defaultTransports?, toolOptions? }`)
|
|
1241
|
-
|
|
1242
|
-
**Transport Types:**
|
|
1243
|
-
- `"stdio"`: Standard input/output
|
|
1244
|
-
- `"sse"`: Server-Sent Events over HTTP
|
|
1245
|
-
- `"streamable-http"`: HTTP with streaming support
|
|
1246
|
-
|
|
1247
|
-
**Example:**
|
|
1248
551
|
```typescript
|
|
1249
552
|
const cli = ArgParser.withMcp({
|
|
1250
553
|
appName: "My CLI",
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
appName: "My Tool",
|
|
1262
|
-
handler: async (ctx) => ({ result: ctx.args }),
|
|
1263
|
-
})
|
|
1264
|
-
.addFlags([/* your flags */])
|
|
1265
|
-
.addMcpSubCommand("serve", {
|
|
1266
|
-
name: "my-server",
|
|
1267
|
-
version: "1.0.0",
|
|
1268
|
-
}, {
|
|
1269
|
-
// Default multiple transports - used when no CLI flags provided
|
|
1270
|
-
defaultTransports: [
|
|
1271
|
-
{ type: "stdio" },
|
|
1272
|
-
{ type: "sse", port: 3001 },
|
|
1273
|
-
{ type: "streamable-http", port: 3002 }
|
|
1274
|
-
]
|
|
554
|
+
appCommandName: "mycli",
|
|
555
|
+
mcp: {
|
|
556
|
+
// This will appear in Claude Desktop's Extensions settings
|
|
557
|
+
serverInfo: {
|
|
558
|
+
name: "my-mcp-server",
|
|
559
|
+
version: "1.0.0",
|
|
560
|
+
description: "My CLI as an MCP server",
|
|
561
|
+
logo: "./assets/my-logo.png", // Local file path
|
|
562
|
+
},
|
|
563
|
+
},
|
|
1275
564
|
});
|
|
1276
|
-
|
|
1277
|
-
// Usage: my-tool serve (uses all default transports)
|
|
1278
|
-
// Usage: my-tool serve --transports '[{"type":"sse","port":4000}]' (overrides defaults)
|
|
1279
565
|
```
|
|
1280
566
|
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
#### `new ArgParserBase(options?, initialFlags?)`
|
|
1284
|
-
|
|
1285
|
-
Constructor for creating a basic parser instance without MCP capabilities.
|
|
1286
|
-
|
|
1287
|
-
#### `new ArgParser(options?, initialFlags?)`
|
|
1288
|
-
|
|
1289
|
-
Constructor for creating a parser instance with MCP capabilities.
|
|
1290
|
-
|
|
1291
|
-
- `options`: An object (`IArgParserParams`) configuring the parser.
|
|
1292
|
-
- `appName?: string`: Display name.
|
|
1293
|
-
- `appCommandName?: string`: Command name for help/errors.
|
|
1294
|
-
- `description?: string`: Parser description.
|
|
1295
|
-
- `handler?: (ctx: HandlerContext) => void`: Handler function for this parser.
|
|
1296
|
-
- `subCommands?: ISubCommand[]`: Array of sub-command definitions.
|
|
1297
|
-
- `handleErrors?: boolean`: Enable/disable default error handling (default: `true`).
|
|
1298
|
-
- `throwForDuplicateFlags?: boolean`: Throw error for duplicate flags (default: `false`).
|
|
1299
|
-
- `inheritParentFlags?: boolean`: Enable flag inheritance when this parser is a sub-command (default: `false`).
|
|
1300
|
-
- `initialFlags`: Optional array of `IFlag` objects to add during initialization.
|
|
1301
|
-
|
|
1302
|
-
### `parse(args, options?)`
|
|
1303
|
-
|
|
1304
|
-
Parses an array of command-line arguments.
|
|
1305
|
-
|
|
1306
|
-
- `args`: `string[]` - Array of arguments (usually `process.argv.slice(2)`).
|
|
1307
|
-
- `options`: Optional object (`IParseOptions`).
|
|
1308
|
-
- `skipHelpHandling?: boolean`: Prevents automatic help display/exit on `--help` (default: `false`).
|
|
1309
|
-
- `skipHandlers?: boolean`: Prevents execution of any matched command handlers (default: `false`).
|
|
1310
|
-
- Returns: `TParsedArgs & { $commandChain?: string[] }` - An object containing the parsed arguments and optionally the `$commandChain`. Throws `ArgParserError` if `handleErrors` is `false`.
|
|
1311
|
-
|
|
1312
|
-
### `.addFlag(flag)`
|
|
567
|
+
If no custom logo is provided or loading fails, a default ArgParser logo is included
|
|
1313
568
|
|
|
1314
|
-
|
|
569
|
+
#### Supported Logo Sources
|
|
1315
570
|
|
|
1316
|
-
|
|
1317
|
-
- Returns: `this` for chaining.
|
|
571
|
+
**Local File Path:**
|
|
1318
572
|
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
- `flags`: `IFlag[]` - Array of flag objects.
|
|
1324
|
-
- Returns: `this` for chaining.
|
|
1325
|
-
|
|
1326
|
-
### `.addSubCommand(subCommand)`
|
|
1327
|
-
|
|
1328
|
-
Adds a sub-command definition.
|
|
1329
|
-
|
|
1330
|
-
- `subCommand`: `ISubCommand` - The sub-command object.
|
|
1331
|
-
- Returns: `this` for chaining.
|
|
1332
|
-
|
|
1333
|
-
### `.setHandler(handler)`
|
|
1334
|
-
|
|
1335
|
-
Sets or overrides the handler function for this parser instance.
|
|
1336
|
-
|
|
1337
|
-
- `handler`: `(ctx: HandlerContext) => void` - The handler function.
|
|
1338
|
-
- Returns: `this` for chaining.
|
|
1339
|
-
|
|
1340
|
-
### `.getSubCommand(name)`
|
|
1341
|
-
|
|
1342
|
-
Retrieves a defined sub-command by name.
|
|
1343
|
-
|
|
1344
|
-
- `name`: `string` - The name of the sub-command.
|
|
1345
|
-
- Returns: `ISubCommand | undefined` - The sub-command definition or `undefined` if not found.
|
|
1346
|
-
|
|
1347
|
-
### `.hasFlag(name)`
|
|
1348
|
-
|
|
1349
|
-
Checks if a flag with the given name exists on this parser instance.
|
|
1350
|
-
|
|
1351
|
-
- `name`: `string` - The name of the flag.
|
|
1352
|
-
- Returns: `boolean`.
|
|
1353
|
-
|
|
1354
|
-
### `helpText()`
|
|
1355
|
-
|
|
1356
|
-
Generates the formatted help text for this parser instance.
|
|
1357
|
-
|
|
1358
|
-
- Returns: `string` - The generated help text.
|
|
1359
|
-
|
|
1360
|
-
### `printAll(filePath?)`
|
|
1361
|
-
|
|
1362
|
-
Recursively prints the parser configuration.
|
|
1363
|
-
|
|
1364
|
-
- `filePath`: `string?` - Optional path to write output to file. `.json` extension saves as JSON.
|
|
1365
|
-
|
|
1366
|
-
### Interfaces
|
|
1367
|
-
|
|
1368
|
-
- `IFlag`: Defines the structure of a command-line flag.
|
|
1369
|
-
- `ISubCommand`: Defines the structure of a sub-command.
|
|
1370
|
-
- `HandlerContext`: The object passed to handler functions.
|
|
1371
|
-
- `IParseOptions`: Options for the `parse()` method.
|
|
1372
|
-
- `IArgParserParams`: Options for the `ArgParser` constructor.
|
|
1373
|
-
- `ArgParserError`: Custom error class thrown on parsing failures when `handleErrors` is `false`.
|
|
573
|
+
```typescript
|
|
574
|
+
logo: "./assets/my-logo.png"; // Relative to your project
|
|
575
|
+
logo: "/absolute/path/to/logo.jpg"; // Absolute path
|
|
576
|
+
```
|
|
1374
577
|
|
|
1375
|
-
|
|
578
|
+
**HTTP/HTTPS URL:**
|
|
1376
579
|
|
|
1377
|
-
### **Basic CLI Setup**
|
|
1378
580
|
```typescript
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
const cli = new ArgParser({
|
|
1382
|
-
appName: "My Tool",
|
|
1383
|
-
appCommandName: "my-tool",
|
|
1384
|
-
handler: async (ctx) => ({ result: ctx.args }),
|
|
1385
|
-
})
|
|
1386
|
-
.addFlags([
|
|
1387
|
-
{ name: "input", options: ["--input", "-i"], type: "string", mandatory: true },
|
|
1388
|
-
{ name: "verbose", options: ["--verbose", "-v"], type: "boolean", flagOnly: true },
|
|
1389
|
-
])
|
|
1390
|
-
.addSubCommand({
|
|
1391
|
-
name: "process",
|
|
1392
|
-
description: "Process data",
|
|
1393
|
-
handler: async (ctx) => ({ processed: true }),
|
|
1394
|
-
parser: new ArgParser({}, [
|
|
1395
|
-
{ name: "format", options: ["--format"], type: "string", enum: ["json", "xml"] },
|
|
1396
|
-
]),
|
|
1397
|
-
});
|
|
581
|
+
logo: "https://example.com/logo.png"; // Downloaded automatically
|
|
582
|
+
logo: "https://cdn.example.com/icon.svg";
|
|
1398
583
|
```
|
|
1399
584
|
|
|
1400
|
-
###
|
|
1401
|
-
```typescript
|
|
1402
|
-
import { ArgParser } from "@alcyone-labs/arg-parser";
|
|
585
|
+
### How DXT Generation Works
|
|
1403
586
|
|
|
1404
|
-
|
|
1405
|
-
.addFlags([/* same flags */])
|
|
1406
|
-
.addMcpSubCommand("serve", {
|
|
1407
|
-
name: "my-mcp-server",
|
|
1408
|
-
version: "1.0.0",
|
|
1409
|
-
});
|
|
587
|
+
When you run `--s-build-dxt`, ArgParser performs several steps to create a self-contained, autonomous package:
|
|
1410
588
|
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
589
|
+
1. **Introspection**: It analyzes all tools defined with `.addTool()`.
|
|
590
|
+
2. **Manifest Generation**: It creates a `manifest.json` file.
|
|
591
|
+
- Tool flags are converted into a JSON Schema for the `input_schema`.
|
|
592
|
+
- Flags with an `env` property (e.g., `{ name: 'apiKey', env: 'API_KEY' }`) are automatically added to the `user_config` section, prompting the user for the value upon installation and making it available as an environment variable to your tool.
|
|
593
|
+
3. **Autonomous Build**: It bundles your CLI's source code and its dependencies into a single entry point (e.g., `server.js`) that can run without `node_modules`. This ensures the DXT is portable and reliable.
|
|
594
|
+
4. **Packaging**: It assembles all necessary files (manifest, server bundle, logo, etc.) into the specified output directory, ready to be used by Claude Desktop or packed with `npx @anthropic-ai/dxt`.
|
|
1414
595
|
|
|
1415
|
-
|
|
1416
|
-
Configure default transports that will be used when no CLI transport flags are provided:
|
|
596
|
+
---
|
|
1417
597
|
|
|
1418
|
-
|
|
1419
|
-
|
|
598
|
+
## System Flags & Configuration
|
|
599
|
+
|
|
600
|
+
ArgParser includes built-in `--s-*` flags for development, debugging, and configuration. They are processed before normal arguments and will cause the program to exit after their task is complete.
|
|
601
|
+
|
|
602
|
+
| Flag | Description |
|
|
603
|
+
| --------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
604
|
+
| **MCP & DXT** | |
|
|
605
|
+
| `--s-mcp-serve` | Starts the application in MCP server mode, exposing all tools. |
|
|
606
|
+
| `--s-build-dxt [dir]` | Generates a complete, autonomous DXT package for Claude Desktop. |
|
|
607
|
+
| `--s-mcp-transport <type>` | Overrides the MCP transport (`stdio`, `sse`, `streamable-http`). |
|
|
608
|
+
| `--s-mcp-transports <json>` | Overrides transports with a JSON array for multi-transport setups. |
|
|
609
|
+
| `--s-mcp-port <number>` | Sets the port for HTTP-based transports (`sse`, `streamable-http`). |
|
|
610
|
+
| `--s-mcp-host <string>` | Sets the host address for HTTP-based transports. |
|
|
611
|
+
| **Configuration** | |
|
|
612
|
+
| `--s-with-env <file>` | Loads configuration from a file (`.env`, `.json`, `.yaml`, `.toml`). CLI args take precedence. |
|
|
613
|
+
| `--s-save-to-env <file>` | Saves the current arguments to a configuration file, perfect for templates. |
|
|
614
|
+
| **Debugging** | |
|
|
615
|
+
| `--s-debug` | Prints a detailed, step-by-step log of the argument parsing process. |
|
|
616
|
+
| `--s-debug-print` | Exports the entire parser configuration to a JSON file for inspection. |
|
|
617
|
+
| `--s-enable-fuzzy` | Enables fuzzy testing mode—a dry run that parses args but skips handler execution. |
|
|
1420
618
|
|
|
1421
|
-
|
|
1422
|
-
const cliWithPreset = ArgParser.withMcp({
|
|
1423
|
-
appName: "My Tool",
|
|
1424
|
-
handler: async (ctx) => ({ result: ctx.args }),
|
|
1425
|
-
})
|
|
1426
|
-
.addMcpSubCommand("serve", {
|
|
1427
|
-
name: "my-server",
|
|
1428
|
-
version: "1.0.0",
|
|
1429
|
-
}, {
|
|
1430
|
-
defaultTransport: {
|
|
1431
|
-
type: "sse",
|
|
1432
|
-
port: 3001,
|
|
1433
|
-
host: "0.0.0.0"
|
|
1434
|
-
}
|
|
1435
|
-
});
|
|
619
|
+
---
|
|
1436
620
|
|
|
1437
|
-
|
|
1438
|
-
const cliWithMultiplePresets = ArgParser.withMcp({
|
|
1439
|
-
appName: "Multi-Transport Tool",
|
|
1440
|
-
handler: async (ctx) => ({ result: ctx.args }),
|
|
1441
|
-
})
|
|
1442
|
-
.addMcpSubCommand("serve", {
|
|
1443
|
-
name: "multi-server",
|
|
1444
|
-
version: "1.0.0",
|
|
1445
|
-
}, {
|
|
1446
|
-
defaultTransports: [
|
|
1447
|
-
{ type: "stdio" },
|
|
1448
|
-
{ type: "sse", port: 3001 },
|
|
1449
|
-
{ type: "streamable-http", port: 3002, path: "/api/mcp" }
|
|
1450
|
-
],
|
|
1451
|
-
toolOptions: {
|
|
1452
|
-
includeSubCommands: true
|
|
1453
|
-
}
|
|
1454
|
-
});
|
|
621
|
+
## Changelog
|
|
1455
622
|
|
|
1456
|
-
|
|
1457
|
-
// my-tool serve -> Uses preset transports
|
|
1458
|
-
// my-tool serve --transport sse -> Overrides preset with CLI flags
|
|
1459
|
-
```
|
|
623
|
+
### v2.0.0
|
|
1460
624
|
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
625
|
+
- **Unified Tool Architecture**: Introduced `.addTool()` to define CLI subcommands and MCP tools in a single declaration.
|
|
626
|
+
- **Environment Variables Support**: The `env` property on any IFlag now automatically pull value from the `process.env[${ENV}]` key and generates `user_config` entries in the DXT manifest and fills the flag value to the ENV value if found (process.env).
|
|
627
|
+
- **Enhanced DXT Generation**: The `env` property on flags now automatically generates `user_config` entries in the DXT manifest.
|
|
628
|
+
- **Automatic Console Safety**: Console output is automatically and safely redirected in MCP mode to prevent protocol contamination.
|
|
629
|
+
- **Breaking Changes**: The `addMcpSubCommand()` and separate `addSubCommand()` for MCP tools are deprecated in favor of `addTool()` and `--s-mcp-serve`.
|
|
1465
630
|
|
|
1466
|
-
|
|
1467
|
-
my-tool --s-with-env config.yaml --input override.txt
|
|
631
|
+
### v1.3.0
|
|
1468
632
|
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
633
|
+
- **Plugin System & Architecture**: Refactored to a dependency-injection model, making the core library dependency-free. Optional plugins for TOML/YAML.
|
|
634
|
+
- **Global Console Replacement**: Implemented the first version of automatic console suppression for MCP compliance.
|
|
635
|
+
- **Autonomous Build Improvements**: Significantly reduced DXT bundle size and removed dynamic `require` issues.
|
|
1472
636
|
|
|
1473
|
-
###
|
|
1474
|
-
```bash
|
|
1475
|
-
# Single transport
|
|
1476
|
-
my-tool serve --transport sse --port 3001
|
|
1477
|
-
|
|
1478
|
-
# Multiple transports
|
|
1479
|
-
my-tool serve --transports '[
|
|
1480
|
-
{"type":"stdio"},
|
|
1481
|
-
{"type":"sse","port":3001},
|
|
1482
|
-
{"type":"streamable-http","port":3002}
|
|
1483
|
-
]'
|
|
1484
|
-
```
|
|
637
|
+
### v1.2.0
|
|
1485
638
|
|
|
1486
|
-
|
|
639
|
+
- **Critical MCP Fixes**: Resolved issues where MCP tools with output schemas would fail. Ensured correct JSON-RPC 2.0 response formatting.
|
|
640
|
+
- **Enhanced Handler Context**: Added `isMcp` flag to the handler context for more reliable mode detection.
|
|
641
|
+
|
|
642
|
+
### v1.1.0
|
|
1487
643
|
|
|
1488
|
-
|
|
644
|
+
- **Major Features**: First release with MCP Integration, System Flags (`--s-debug`, `--s-with-env`, etc.), and environment loading from files.
|
|
1489
645
|
|
|
1490
|
-
---
|
|
646
|
+
---
|
|
1491
647
|
|
|
1492
648
|
## Backlog
|
|
1493
649
|
|
|
1494
650
|
- [x] Publish as an open-source library
|
|
1495
651
|
- [x] Make ArgParser compatible with MCP out-of-the-box
|
|
1496
|
-
- [x] Rename --LIB
|
|
652
|
+
- [x] Rename --LIB-\* flags to --s-\*
|
|
1497
653
|
- [x] Make it possible to pass a `--s-save-to-env /path/to/file` parameter that saves all the parameters to a file (works with Bash-style .env, JSON, YAML, TOML)
|
|
1498
654
|
- [x] Make it possible to pass a `--s-with-env /path/to/file` parameter that loads all the parameters from a file (works with Bash-style .env, JSON, YAML, TOML)
|
|
1499
655
|
- [ ] Add System flags to args.systemArgs
|
|
@@ -1506,4 +662,3 @@ my-tool serve --transports '[
|
|
|
1506
662
|
### (known) Bugs / DX improvement points
|
|
1507
663
|
|
|
1508
664
|
- [ ] When a flag with `flagOnly: false` is going to consume a value that appears like a valid flag from the set, raise the appropriate warning
|
|
1509
|
-
- [ ] When a flag with `allowMultiple: false` and `flagOnly: true` is passed multiple times (regardless of the options, for example "-1" and later "--one", both being valid), raise the correct error
|