docstar-cli 1.0.1 → 1.0.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # docstar-cli
2
2
 
3
- A CLI for calling published DocStar API endpoints directly from your terminal, without leaving the shell to read docs. Point it at a DocStar docs site, pick which modules (e.g. "Slack") you want, and it turns each published endpoint into a real command you can run.
3
+ A CLI for calling published DocStar API endpoints directly from your terminal, without leaving the shell to read docs. Point it at a DocStar docs site, pick which modules (e.g. "Slack") you want, and it turns each published endpoint into a real command you can run. You can install from multiple docs sites/collections at once — each is kept separate under its own **CLI name**.
4
4
 
5
5
  ## Install
6
6
 
@@ -26,40 +26,41 @@ For a local/non-custom-domain docs site, pass the collection id explicitly:
26
26
  docstar-cli init localhost:3000 --collectionId paM4R4A26Hvb
27
27
  ```
28
28
 
29
- This fetches the list of published modules for that site, shows an interactive checklist (all modules pre-checked — press `space` to toggle, `enter` to confirm), and for each selected module:
29
+ This fetches the list of published modules for that collection, shows an interactive checklist (all modules pre-checked — press `space` to toggle, `enter` to confirm), and for each selected module:
30
30
 
31
- - saves its full endpoint contract to `~/.docstar/modules/<module>.json`
32
- - registers a real CLI command for every endpoint in that module
33
- - registers a `<module> list` command
31
+ - saves its full endpoint contract to `~/.docstar/modules/<cli-name>/<module>.json`
32
+ - registers a real CLI command for every endpoint: `docstar-cli <cli-name> <module> <command>`
34
33
 
35
- Overall settings (domain, collection, installed modules) are saved to `~/.docstar/config.json`.
34
+ The **CLI name** comes from the collection's settings (set it under the collection's Domain settings in the docs editor — lowercase letters, numbers, `-` and `_` only; auto-generated from the collection name if not set yet). Running `init` against a different domain/collection adds it alongside any others already installed — nothing gets overwritten.
36
35
 
37
- ### 2. See what's available in a module
36
+ Everything is saved to `~/.docstar/config.json`, grouped by collection.
37
+
38
+ ### 2. See what's installed
38
39
 
39
40
  ```sh
40
- docstar-cli slack list
41
+ docstar-cli list # every installed collection
42
+ docstar-cli list msg91 # modules installed for the "msg91" collection
43
+ docstar-cli list msg91 slack # Slack's installed endpoints in "msg91"
41
44
  ```
42
45
 
43
46
  ```
44
47
  send-message-1
45
48
  send message
46
49
  POST
47
- required: MY_SECRET_KEY
50
+ required: message
48
51
  ```
49
52
 
50
53
  ### 3. Call an endpoint
51
54
 
52
- Pass required parameters as flags:
53
-
54
55
  ```sh
55
- docstar-cli slack send-message-1 --MY_SECRET_KEY "hello from the CLI"
56
+ docstar-cli msg91 slack send-message-1 --message "hello from the CLI"
56
57
  ```
57
58
 
58
- Or omit them and answer the prompts instead:
59
+ Or omit required parameters and answer the prompts instead:
59
60
 
60
61
  ```sh
61
- docstar-cli slack send-message-1
62
- ? Enter value for MY_SECRET_KEY
62
+ docstar-cli msg91 slack send-message-1
63
+ ? Enter value for message
63
64
  ```
64
65
 
65
66
  The command prints the response status and body from the actual API call.
@@ -67,7 +68,8 @@ The command prints the response status and body from the actual API call.
67
68
  ## Use from an AI client (MCP)
68
69
 
69
70
  `docstar-cli` can run as an [MCP](https://modelcontextprotocol.io) server, turning every installed
70
- endpoint into a proper tool an AI client can call directly — no shell access required.
71
+ endpoint (across all installed collections) into a proper tool an AI client can call directly — no
72
+ shell access required.
71
73
 
72
74
  ```sh
73
75
  docstar-cli mcp
@@ -86,17 +88,17 @@ Register it with Claude Code (`.mcp.json`) or Claude Desktop (`claude_desktop_co
86
88
  }
87
89
  ```
88
90
 
89
- Each installed endpoint becomes one tool named `<module>__<command>` (e.g. `slack__send-message-1`),
90
- with required/optional parameters exposed in its schema. A prompt like "call the slack api and
91
- send a message saying hi" resolves directly to that tool call — the AI client asks you for any
92
- required value it can't infer, exactly like any other MCP tool. Run `docstar-cli init` first so
93
- there's at least one installed module for `mcp` to expose.
91
+ Each installed endpoint becomes one tool named `<cli-name>__<module>__<command>` (e.g.
92
+ `msg91__slack__send-message-1`), with required/optional parameters exposed in its schema. A prompt
93
+ like "call the slack api and send a message saying hi" resolves directly to that tool call — the
94
+ AI client asks you for any required value it can't infer, exactly like any other MCP tool. Run
95
+ `docstar-cli init` first so there's at least one installed module for `mcp` to expose.
94
96
 
95
97
  ## How it works
96
98
 
97
- - `docstar-cli init` talks to `GET /p/module.json?collectionId=...` (list of modules) and `GET /p/<module>/module.json?collectionId=...` (a module's endpoint contract) on the docs site.
99
+ - `docstar-cli init` talks to `GET /p/module.json?collectionId=...` (the collection's name, CLI name, and list of modules) and `GET /p/<module>/module.json?collectionId=...` (a module's endpoint contract) on the docs site.
98
100
  - Each endpoint's contract (method, url, base url, headers, body, and CLI parameter names) is saved locally and used to build the real HTTP request when you run its command — no network round-trip to the docs site is needed to run a command once a module is installed.
99
- - Commands are generated as real files on disk under this repo's `dist/commands/<module>/`, which is why `npm run build` (it wipes `dist/`) requires re-running `docstar-cli init` afterwards to reinstall your modules.
101
+ - Commands are generated as real files on disk under this repo's `dist/commands/<cli-name>/<module>/`, which is why `npm run build` (it wipes `dist/`) requires re-running `docstar-cli init` for each installed collection afterwards to reinstall your modules.
100
102
 
101
103
  ## Development
102
104
 
@@ -0,0 +1,30 @@
1
+ import {Command, Flags} from '@oclif/core'
2
+ import {executeCliCommand} from '../../../lib/http.js'
3
+ import {promptForMissingParams} from '../../../lib/prompt.js'
4
+
5
+ const REQUIRED_PARAMS = ["message"]
6
+
7
+ export default class Generated extends Command {
8
+ static description = "send message"
9
+ static aliases = []
10
+ static flags = {
11
+ 'message': Flags.string({description: 'Required parameter'}),
12
+ }
13
+
14
+ async run() {
15
+ const {flags} = await this.parse(Generated)
16
+ const params = {}
17
+ for (const [key, value] of Object.entries(flags)) {
18
+ if (value !== undefined) params[key] = value
19
+ }
20
+
21
+ Object.assign(params, await promptForMissingParams(REQUIRED_PARAMS, params))
22
+
23
+ try {
24
+ const result = await executeCliCommand('api-collection', 'slack', 'send-message-1', params)
25
+ this.log(JSON.stringify(result, null, 2))
26
+ } catch (error) {
27
+ this.error(error.message)
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,30 @@
1
+ import {Command, Flags} from '@oclif/core'
2
+ import {executeCliCommand} from '../../../lib/http.js'
3
+ import {promptForMissingParams} from '../../../lib/prompt.js'
4
+
5
+ const REQUIRED_PARAMS = ["message"]
6
+
7
+ export default class Generated extends Command {
8
+ static description = "send alert"
9
+ static aliases = []
10
+ static flags = {
11
+ 'message': Flags.string({description: 'Required parameter'}),
12
+ }
13
+
14
+ async run() {
15
+ const {flags} = await this.parse(Generated)
16
+ const params = {}
17
+ for (const [key, value] of Object.entries(flags)) {
18
+ if (value !== undefined) params[key] = value
19
+ }
20
+
21
+ Object.assign(params, await promptForMissingParams(REQUIRED_PARAMS, params))
22
+
23
+ try {
24
+ const result = await executeCliCommand('api-collection-2', 'viasocket', 'send-alert', params)
25
+ this.log(JSON.stringify(result, null, 2))
26
+ } catch (error) {
27
+ this.error(error.message)
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,33 @@
1
+ import {Command, Flags} from '@oclif/core'
2
+ import {executeCliCommand} from '../../../lib/http.js'
3
+ import {promptForMissingParams} from '../../../lib/prompt.js'
4
+
5
+ const REQUIRED_PARAMS = ["query","collectionIds","getUrl","allowNonDomain"]
6
+
7
+ export default class Generated extends Command {
8
+ static description = "Find matches"
9
+ static aliases = []
10
+ static flags = {
11
+ 'query': Flags.string({description: 'Required parameter'}),
12
+ 'collectionIds': Flags.string({description: 'Required parameter'}),
13
+ 'getUrl': Flags.string({description: 'Required parameter'}),
14
+ 'allowNonDomain': Flags.string({description: 'Required parameter'}),
15
+ }
16
+
17
+ async run() {
18
+ const {flags} = await this.parse(Generated)
19
+ const params = {}
20
+ for (const [key, value] of Object.entries(flags)) {
21
+ if (value !== undefined) params[key] = value
22
+ }
23
+
24
+ Object.assign(params, await promptForMissingParams(REQUIRED_PARAMS, params))
25
+
26
+ try {
27
+ const result = await executeCliCommand('docstar-apis', 'public-routes', 'find-matches-1', params)
28
+ this.log(JSON.stringify(result, null, 2))
29
+ } catch (error) {
30
+ this.error(error.message)
31
+ }
32
+ }
33
+ }
@@ -1,7 +1,7 @@
1
1
  import { checkbox } from '@inquirer/prompts';
2
2
  import { Args, Command, Flags } from '@oclif/core';
3
- import { mkdir, writeFile } from 'node:fs/promises';
4
- import { generateCommandFile, generateListCommandFile } from '../lib/codegen.js';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { generateCommandFile } from '../lib/codegen.js';
5
5
  import { configDir, configPath, modulePath } from '../lib/paths.js';
6
6
  const buildBaseUrl = (domain) => {
7
7
  if (domain.startsWith('http://') || domain.startsWith('https://'))
@@ -15,11 +15,23 @@ const fetchJson = async (url) => {
15
15
  throw new Error(`Request to ${url} failed (${response.status} ${response.statusText})`);
16
16
  return (await response.json());
17
17
  };
18
+ const readSavedConfig = async () => {
19
+ try {
20
+ return JSON.parse(await readFile(configPath(), 'utf8'));
21
+ }
22
+ catch {
23
+ return { collections: [] };
24
+ }
25
+ };
18
26
  export default class Init extends Command {
19
27
  static args = {
20
28
  domain: Args.string({ description: 'DocStar docs domain, e.g. docs.msg91.com or localhost:3000', required: true }),
21
29
  };
22
- static description = 'Discover published modules for a DocStar docs site, pick which ones to install, and register their CLI commands';
30
+ static description = [
31
+ 'Discover published modules for a DocStar docs site, pick which ones to install, and register their CLI commands.',
32
+ 'You can run this against multiple docs sites/collections — each is kept separate under its own CLI name (`docstar-cli <cli-name> <module> <command>`).',
33
+ 'After installing, run `docstar-cli list` to see what got installed.',
34
+ ].join('\n');
23
35
  static examples = [
24
36
  '<%= config.bin %> <%= command.id %> docs.msg91.com',
25
37
  '<%= config.bin %> <%= command.id %> localhost:3000 --collectionId paM4R4A26Hvb',
@@ -35,10 +47,14 @@ export default class Init extends Command {
35
47
  listUrl.searchParams.set('collectionId', flags.collectionId);
36
48
  this.log(`Fetching modules from ${listUrl.toString()} ...`);
37
49
  const listResponse = await fetchJson(listUrl.toString());
50
+ if (!listResponse.collection?.cliName) {
51
+ this.error('The docs site did not return a CLI name for this collection. Please update hitman-api/hitman-ui, or set one in the collection settings.');
52
+ }
38
53
  if (!listResponse.modules || listResponse.modules.length === 0) {
39
54
  this.log('No published modules found.');
40
55
  return;
41
56
  }
57
+ const { cliName } = listResponse.collection;
42
58
  const selectedPaths = await checkbox({
43
59
  choices: listResponse.modules.map((module) => {
44
60
  const count = module.endpointCount ?? module.endpoints?.length ?? 0;
@@ -48,7 +64,7 @@ export default class Init extends Command {
48
64
  value: module.path,
49
65
  };
50
66
  }),
51
- message: 'Select modules to install (space to toggle, enter to confirm)',
67
+ message: `Select modules to install for "${cliName}" (space to toggle, enter to confirm)`,
52
68
  });
53
69
  if (selectedPaths.length === 0) {
54
70
  this.log('No modules selected, nothing installed.');
@@ -61,26 +77,32 @@ export default class Init extends Command {
61
77
  if (flags.collectionId)
62
78
  moduleUrl.searchParams.set('collectionId', flags.collectionId);
63
79
  this.log(`Fetching ${path} ...`);
80
+ // eslint-disable-next-line no-await-in-loop
64
81
  const moduleJson = await fetchJson(moduleUrl.toString());
65
- await mkdir(configDir() + '/modules', { recursive: true });
66
- await writeFile(modulePath(path), JSON.stringify(moduleJson, null, 2));
82
+ // eslint-disable-next-line no-await-in-loop
83
+ await mkdir(configDir() + `/modules/${cliName}`, { recursive: true });
84
+ // eslint-disable-next-line no-await-in-loop
85
+ await writeFile(modulePath(cliName, path), JSON.stringify(moduleJson, null, 2));
67
86
  for (const endpoint of moduleJson.endpoints) {
68
- const filePath = await generateCommandFile(this.config.root, path, endpoint);
69
- this.log(` registered command: ${this.config.bin} ${path} ${endpoint.cli.command.name} -> ${filePath}`);
87
+ // eslint-disable-next-line no-await-in-loop
88
+ await generateCommandFile(this.config.root, cliName, path, endpoint);
89
+ this.log(` registered command: ${this.config.bin} ${cliName} ${path} ${endpoint.cli.command.name}`);
70
90
  }
71
- await generateListCommandFile(this.config.root, path);
72
- this.log(` registered command: ${this.config.bin} ${path} list`);
73
91
  selectedModules.push({ name: moduleJson.module.name, path });
74
92
  }
75
- const savedConfig = {
93
+ const collectionConfig = {
76
94
  baseUrl,
77
- collection: listResponse.collection ?? null,
95
+ cliName,
78
96
  collectionId: flags.collectionId ?? null,
79
97
  domain: args.domain,
80
98
  modules: selectedModules,
99
+ name: listResponse.collection.name,
81
100
  updatedAt: new Date().toISOString(),
82
101
  };
102
+ const savedConfig = await readSavedConfig();
103
+ const otherCollections = savedConfig.collections.filter((collection) => collection.cliName !== cliName);
104
+ savedConfig.collections = [...otherCollections, collectionConfig];
83
105
  await writeFile(configPath(), JSON.stringify(savedConfig, null, 2));
84
- this.log(`\nInstalled ${selectedModules.length} module(s). Config saved to ${configPath()}`);
106
+ this.log(`\nInstalled ${selectedModules.length} module(s) for "${cliName}". Config saved to ${configPath()}`);
85
107
  }
86
108
  }
@@ -0,0 +1,13 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class List extends Command {
3
+ static args: {
4
+ collection: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
5
+ module: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
6
+ };
7
+ static description: string;
8
+ static examples: string[];
9
+ static flags: {
10
+ all: import("@oclif/core/interfaces").BooleanFlag<boolean>;
11
+ };
12
+ run(): Promise<void>;
13
+ }
@@ -0,0 +1,71 @@
1
+ import { Args, Command, Flags } from '@oclif/core';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { loadModule } from '../lib/http.js';
4
+ import { configPath } from '../lib/paths.js';
5
+ export default class List extends Command {
6
+ static args = {
7
+ collection: Args.string({ description: 'Show modules installed for this collection (CLI name), e.g. msg91', required: false }),
8
+ module: Args.string({ description: 'Show all endpoints for this module within the collection, e.g. slack', required: false }),
9
+ };
10
+ static description = 'List installed collections, the modules within one, or every endpoint of one module';
11
+ static examples = [
12
+ '<%= config.bin %> <%= command.id %> # list every installed collection',
13
+ '<%= config.bin %> <%= command.id %> --all # same as above',
14
+ '<%= config.bin %> <%= command.id %> msg91 # list modules installed for the "msg91" collection',
15
+ '<%= config.bin %> <%= command.id %> msg91 slack # list all of Slack\'s installed endpoints in "msg91"',
16
+ ];
17
+ static flags = {
18
+ all: Flags.boolean({ description: 'List every installed collection (default when no arguments are given)' }),
19
+ };
20
+ async run() {
21
+ const { args } = await this.parse(List);
22
+ let savedConfig;
23
+ try {
24
+ savedConfig = JSON.parse(await readFile(configPath(), 'utf8'));
25
+ }
26
+ catch {
27
+ this.error('No installed modules found. Run `docstar-cli init <domain>` first.');
28
+ }
29
+ if (savedConfig.collections.length === 0) {
30
+ this.log('No collections installed. Run `docstar-cli init <domain>` to install one.');
31
+ return;
32
+ }
33
+ if (!args.collection) {
34
+ for (const collection of savedConfig.collections) {
35
+ this.log(`${collection.name} (${collection.cliName}) — ${collection.domain} — ${collection.modules.length} module${collection.modules.length === 1 ? '' : 's'}`);
36
+ }
37
+ return;
38
+ }
39
+ const collection = savedConfig.collections.find((c) => c.cliName === args.collection);
40
+ if (!collection) {
41
+ this.error(`Collection "${args.collection}" isn't installed. Run \`docstar-cli list\` to see installed collections.`);
42
+ }
43
+ if (!args.module) {
44
+ for (const module of collection.modules) {
45
+ // eslint-disable-next-line no-await-in-loop
46
+ const moduleJson = await loadModule(collection.cliName, module.path);
47
+ const count = moduleJson.endpoints.length;
48
+ this.log(`${module.name} (${module.path}) — ${count} endpoint${count === 1 ? '' : 's'}`);
49
+ }
50
+ return;
51
+ }
52
+ const moduleJson = await loadModule(collection.cliName, args.module);
53
+ if (moduleJson.endpoints.length === 0) {
54
+ this.log(`No endpoints found for module "${args.module}".`);
55
+ return;
56
+ }
57
+ for (const endpoint of moduleJson.endpoints) {
58
+ const { cli } = endpoint;
59
+ const aliases = cli.command.aliases.filter((alias) => alias !== cli.command.name);
60
+ this.log(`${cli.command.name}${aliases.length > 0 ? ` (aliases: ${aliases.join(', ')})` : ''}`);
61
+ if (cli.description)
62
+ this.log(` ${cli.description}`);
63
+ this.log(` ${endpoint.method}`);
64
+ if (cli.parameters.required.length > 0)
65
+ this.log(` required: ${cli.parameters.required.join(', ')}`);
66
+ if (cli.parameters.optional.length > 0)
67
+ this.log(` optional: ${cli.parameters.optional.join(', ')}`);
68
+ this.log('');
69
+ }
70
+ }
71
+ }
@@ -15,8 +15,16 @@ const buildInputShape = (required, optional) => {
15
15
  return shape;
16
16
  };
17
17
  export default class Mcp extends Command {
18
- static description = 'Start an MCP server exposing every installed endpoint as a tool for AI clients (Claude Desktop, Claude Code, etc.)';
19
- static examples = ['<%= config.bin %> <%= command.id %>'];
18
+ static description = [
19
+ 'Start an MCP (Model Context Protocol) server exposing every installed endpoint (across all installed collections) as a callable tool for AI clients (Claude Desktop, Claude Code, etc.).',
20
+ 'Each endpoint becomes one tool named `<cli-name>__<module>__<command>`, e.g. `msg91__slack__send-message-1`. Run `docstar-cli init <domain>` first so there is at least one installed module to expose.',
21
+ 'This command does not exit on its own — it stays running and communicates over stdio for as long as the connecting AI client keeps the connection open.',
22
+ ].join('\n');
23
+ static examples = [
24
+ '<%= config.bin %> <%= command.id %>',
25
+ '# Then register it in an MCP client config, e.g. .mcp.json:',
26
+ '# { "mcpServers": { "docstar": { "command": "docstar-cli", "args": ["mcp"] } } }',
27
+ ];
20
28
  async run() {
21
29
  let savedConfig;
22
30
  try {
@@ -27,24 +35,26 @@ export default class Mcp extends Command {
27
35
  }
28
36
  const server = new McpServer({ name: 'docstar-cli', version: '1.0.0' });
29
37
  let toolCount = 0;
30
- for (const module of savedConfig.modules) {
31
- // eslint-disable-next-line no-await-in-loop
32
- const moduleJson = await loadModule(module.path);
33
- for (const endpoint of moduleJson.endpoints) {
34
- const { cli } = endpoint;
35
- const toolName = sanitize(`${module.path}__${cli.command.name}`);
36
- const description = cli.description || `${cli.command.name} (${module.path})`;
37
- const inputShape = buildInputShape(cli.parameters.required, cli.parameters.optional);
38
- server.tool(toolName, description, inputShape, async (args) => {
39
- try {
40
- const result = await executeCliCommand(module.path, cli.command.name, args);
41
- return { content: [{ type: 'text', text: JSON.stringify(result) }] };
42
- }
43
- catch (error) {
44
- return { content: [{ type: 'text', text: error.message }], isError: true };
45
- }
46
- });
47
- toolCount++;
38
+ for (const collection of savedConfig.collections) {
39
+ for (const module of collection.modules) {
40
+ // eslint-disable-next-line no-await-in-loop
41
+ const moduleJson = await loadModule(collection.cliName, module.path);
42
+ for (const endpoint of moduleJson.endpoints) {
43
+ const { cli } = endpoint;
44
+ const toolName = sanitize(`${collection.cliName}__${module.path}__${cli.command.name}`);
45
+ const description = cli.description || `${cli.command.name} (${collection.cliName} ${module.path})`;
46
+ const inputShape = buildInputShape(cli.parameters.required, cli.parameters.optional);
47
+ server.tool(toolName, description, inputShape, async (args) => {
48
+ try {
49
+ const result = await executeCliCommand(collection.cliName, module.path, cli.command.name, args);
50
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
51
+ }
52
+ catch (error) {
53
+ return { content: [{ type: 'text', text: error.message }], isError: true };
54
+ }
55
+ });
56
+ toolCount++;
57
+ }
48
58
  }
49
59
  }
50
60
  if (toolCount === 0) {
@@ -1,3 +1,2 @@
1
1
  import type { EndpointContract } from './types.js';
2
- export declare const generateCommandFile: (cliRoot: string, modulePathSegment: string, endpoint: EndpointContract) => Promise<string>;
3
- export declare const generateListCommandFile: (cliRoot: string, modulePathSegment: string) => Promise<string>;
2
+ export declare const generateCommandFile: (cliRoot: string, cliName: string, modulePathSegment: string, endpoint: EndpointContract) => Promise<string>;
@@ -3,20 +3,20 @@ import { join } from 'node:path';
3
3
  const flagLine = (name, required) =>
4
4
  // Required params are collected interactively when missing, so the flag itself stays optional to oclif.
5
5
  ` '${name}': Flags.string({description: '${required ? 'Required' : 'Optional'} parameter'}),`;
6
- const commandFileContent = (modulePathSegment, endpoint) => {
6
+ const commandFileContent = (cliName, modulePathSegment, endpoint) => {
7
7
  const { cli } = endpoint;
8
8
  const flagLines = [
9
9
  ...cli.parameters.required.map((name) => flagLine(name, true)),
10
10
  ...cli.parameters.optional.map((name) => flagLine(name, false)),
11
11
  ].join('\n');
12
12
  return `import {Command, Flags} from '@oclif/core'
13
- import {executeCliCommand} from '../../lib/http.js'
14
- import {promptForMissingParams} from '../../lib/prompt.js'
13
+ import {executeCliCommand} from '../../../lib/http.js'
14
+ import {promptForMissingParams} from '../../../lib/prompt.js'
15
15
 
16
16
  const REQUIRED_PARAMS = ${JSON.stringify(cli.parameters.required)}
17
17
 
18
18
  export default class Generated extends Command {
19
- static description = ${JSON.stringify(cli.description || `${cli.name} (${modulePathSegment})`)}
19
+ static description = ${JSON.stringify(cli.description || `${cli.name} (${cliName} ${modulePathSegment})`)}
20
20
  static aliases = ${JSON.stringify(cli.command.aliases.filter((alias) => alias !== cli.name))}
21
21
  static flags = {
22
22
  ${flagLines}
@@ -32,7 +32,7 @@ ${flagLines}
32
32
  Object.assign(params, await promptForMissingParams(REQUIRED_PARAMS, params))
33
33
 
34
34
  try {
35
- const result = await executeCliCommand('${modulePathSegment}', '${cli.command.name}', params)
35
+ const result = await executeCliCommand('${cliName}', '${modulePathSegment}', '${cli.command.name}', params)
36
36
  this.log(JSON.stringify(result, null, 2))
37
37
  } catch (error) {
38
38
  this.error(error.message)
@@ -41,38 +41,10 @@ ${flagLines}
41
41
  }
42
42
  `;
43
43
  };
44
- const listCommandFileContent = (modulePathSegment) => `import {Command} from '@oclif/core'
45
- import {loadModule} from '../../lib/http.js'
46
-
47
- export default class GeneratedList extends Command {
48
- static description = 'List installed APIs for the ${modulePathSegment} module'
49
-
50
- async run() {
51
- const moduleJson = await loadModule('${modulePathSegment}')
52
-
53
- for (const endpoint of moduleJson.endpoints) {
54
- const {cli} = endpoint
55
- this.log(\`\${cli.command.name}\${cli.command.aliases.filter((alias) => alias !== cli.command.name).length > 0 ? \` (aliases: \${cli.command.aliases.filter((alias) => alias !== cli.command.name).join(', ')})\` : ''}\`)
56
- if (cli.description) this.log(\` \${cli.description}\`)
57
- this.log(\` \${endpoint.method}\`)
58
- if (cli.parameters.required.length > 0) this.log(\` required: \${cli.parameters.required.join(', ')}\`)
59
- if (cli.parameters.optional.length > 0) this.log(\` optional: \${cli.parameters.optional.join(', ')}\`)
60
- this.log('')
61
- }
62
- }
63
- }
64
- `;
65
- export const generateCommandFile = async (cliRoot, modulePathSegment, endpoint) => {
66
- const dir = join(cliRoot, 'dist', 'commands', modulePathSegment);
44
+ export const generateCommandFile = async (cliRoot, cliName, modulePathSegment, endpoint) => {
45
+ const dir = join(cliRoot, 'dist', 'commands', cliName, modulePathSegment);
67
46
  await mkdir(dir, { recursive: true });
68
47
  const filePath = join(dir, `${endpoint.cli.command.name}.js`);
69
- await writeFile(filePath, commandFileContent(modulePathSegment, endpoint));
70
- return filePath;
71
- };
72
- export const generateListCommandFile = async (cliRoot, modulePathSegment) => {
73
- const dir = join(cliRoot, 'dist', 'commands', modulePathSegment);
74
- await mkdir(dir, { recursive: true });
75
- const filePath = join(dir, 'list.js');
76
- await writeFile(filePath, listCommandFileContent(modulePathSegment));
48
+ await writeFile(filePath, commandFileContent(cliName, modulePathSegment, endpoint));
77
49
  return filePath;
78
50
  };
@@ -1,8 +1,8 @@
1
1
  import type { EndpointContract, ModuleJson } from './types.js';
2
2
  export declare const stripHtml: (value: string | null | undefined) => string;
3
- export declare const loadModule: (modulePathSegment: string) => Promise<ModuleJson>;
3
+ export declare const loadModule: (cliName: string, modulePathSegment: string) => Promise<ModuleJson>;
4
4
  export declare const findEndpoint: (moduleJson: ModuleJson, commandName: string) => EndpointContract | undefined;
5
- export declare const executeCliCommand: (modulePathSegment: string, commandName: string, params: Record<string, string>) => Promise<{
5
+ export declare const executeCliCommand: (cliName: string, modulePathSegment: string, commandName: string, params: Record<string, string>) => Promise<{
6
6
  status: number;
7
7
  body: unknown;
8
8
  }>;
package/dist/lib/http.js CHANGED
@@ -4,8 +4,8 @@ import { modulePath } from './paths.js';
4
4
  // `<span text-block="true">...</span>`-style markup; unwrap to the raw value.
5
5
  export const stripHtml = (value) => (value ?? '').replaceAll(/<[^>]*>/g, '');
6
6
  const substitutePlaceholders = (template, params) => Object.entries(params).reduce((result, [key, value]) => result.replaceAll(`:${key}`, value).replaceAll(`{${key}}`, value).replaceAll(`{{${key}}}`, value), template);
7
- export const loadModule = async (modulePathSegment) => {
8
- const raw = await readFile(modulePath(modulePathSegment), 'utf8');
7
+ export const loadModule = async (cliName, modulePathSegment) => {
8
+ const raw = await readFile(modulePath(cliName, modulePathSegment), 'utf8');
9
9
  return JSON.parse(raw);
10
10
  };
11
11
  export const findEndpoint = (moduleJson, commandName) => moduleJson.endpoints.find((endpoint) => endpoint.cli.command.name === commandName || endpoint.cli.command.aliases.includes(commandName));
@@ -17,14 +17,47 @@ const buildUrl = (endpoint, params) => {
17
17
  return `${baseUrl}${path}`;
18
18
  };
19
19
  const buildHeaders = (endpoint, params) => {
20
+ // Header names are case-insensitive; the docs editor can end up storing two entries that only
21
+ // differ by case (e.g. "Content-Type" and "content-type"). Sending both as separate header
22
+ // lines has been observed to break body parsing on the receiving server, so dedupe by
23
+ // lowercased name — first entry wins, using its original casing for readability.
24
+ const seenLowerNames = new Set();
20
25
  const headers = {};
21
26
  for (const [rawKey, rawValue] of Object.entries(endpoint.headers || {})) {
22
27
  const key = stripHtml(rawKey);
28
+ const lowerKey = key.toLowerCase();
29
+ if (seenLowerNames.has(lowerKey))
30
+ continue;
31
+ seenLowerNames.add(lowerKey);
23
32
  const value = stripHtml(rawValue?.value ?? rawValue);
24
33
  headers[key] = params[key] ?? value;
25
34
  }
26
35
  return headers;
27
36
  };
37
+ // CLI flag values always arrive as strings, but the JSON body template's existing value for a
38
+ // key tells us its real type (boolean/number/array) — coerce back to that shape instead of
39
+ // clobbering e.g. `getUrl: true` with the literal string "true", or `collectionIds: []` with a
40
+ // plain string.
41
+ const coerceToTemplateType = (existingValue, rawValue) => {
42
+ if (typeof existingValue === 'boolean')
43
+ return rawValue === 'true';
44
+ if (typeof existingValue === 'number') {
45
+ const parsedNumber = Number(rawValue);
46
+ return Number.isNaN(parsedNumber) ? rawValue : parsedNumber;
47
+ }
48
+ if (Array.isArray(existingValue)) {
49
+ try {
50
+ const parsed = JSON.parse(rawValue);
51
+ if (Array.isArray(parsed))
52
+ return parsed;
53
+ }
54
+ catch {
55
+ // not a JSON array literal — fall through to comma-splitting
56
+ }
57
+ return rawValue.split(',').map((item) => item.trim());
58
+ }
59
+ return rawValue;
60
+ };
28
61
  const buildBody = (endpoint, params) => {
29
62
  const rawValue = endpoint.body?.raw?.value;
30
63
  if (endpoint.body?.type !== 'JSON' || !rawValue)
@@ -38,15 +71,15 @@ const buildBody = (endpoint, params) => {
38
71
  }
39
72
  for (const [key, value] of Object.entries(params)) {
40
73
  if (key in parsed)
41
- parsed[key] = value;
74
+ parsed[key] = coerceToTemplateType(parsed[key], value);
42
75
  }
43
76
  return JSON.stringify(parsed);
44
77
  };
45
- export const executeCliCommand = async (modulePathSegment, commandName, params) => {
46
- const moduleJson = await loadModule(modulePathSegment);
78
+ export const executeCliCommand = async (cliName, modulePathSegment, commandName, params) => {
79
+ const moduleJson = await loadModule(cliName, modulePathSegment);
47
80
  const endpoint = findEndpoint(moduleJson, commandName);
48
81
  if (!endpoint) {
49
- throw new Error(`No endpoint found for command "${commandName}" in module "${modulePathSegment}"`);
82
+ throw new Error(`No endpoint found for command "${commandName}" in module "${cliName} ${modulePathSegment}"`);
50
83
  }
51
84
  const url = buildUrl(endpoint, params);
52
85
  const headers = buildHeaders(endpoint, params);
@@ -1,4 +1,5 @@
1
1
  export declare const configDir: () => string;
2
2
  export declare const configPath: () => string;
3
3
  export declare const modulesDir: () => string;
4
- export declare const modulePath: (modulePathSegment: string) => string;
4
+ export declare const collectionModulesDir: (cliName: string) => string;
5
+ export declare const modulePath: (cliName: string, modulePathSegment: string) => string;
package/dist/lib/paths.js CHANGED
@@ -3,4 +3,5 @@ import { join } from 'node:path';
3
3
  export const configDir = () => join(homedir(), '.docstar');
4
4
  export const configPath = () => join(configDir(), 'config.json');
5
5
  export const modulesDir = () => join(configDir(), 'modules');
6
- export const modulePath = (modulePathSegment) => join(modulesDir(), `${modulePathSegment}.json`);
6
+ export const collectionModulesDir = (cliName) => join(modulesDir(), cliName);
7
+ export const modulePath = (cliName, modulePathSegment) => join(collectionModulesDir(cliName), `${modulePathSegment}.json`);
@@ -41,14 +41,20 @@ export type ModuleSummary = {
41
41
  path: string;
42
42
  }[];
43
43
  };
44
- export type SavedConfig = {
45
- baseUrl: string;
44
+ export type CollectionSummary = {
45
+ id: string;
46
+ name: string;
47
+ cliName: string;
48
+ };
49
+ export type CollectionConfig = {
50
+ cliName: string;
51
+ name: string;
46
52
  domain: string;
53
+ baseUrl: string;
47
54
  collectionId: string | null;
48
- collection: {
49
- id: string;
50
- name: string;
51
- } | null;
52
55
  modules: ModuleSummary[];
53
56
  updatedAt: string;
54
57
  };
58
+ export type SavedConfig = {
59
+ collections: CollectionConfig[];
60
+ };
@@ -9,7 +9,7 @@
9
9
  "required": true
10
10
  }
11
11
  },
12
- "description": "Discover published modules for a DocStar docs site, pick which ones to install, and register their CLI commands",
12
+ "description": "Discover published modules for a DocStar docs site, pick which ones to install, and register their CLI commands.\nYou can run this against multiple docs sites/collections — each is kept separate under its own CLI name (`docstar-cli <cli-name> <module> <command>`).\nAfter installing, run `docstar-cli list` to see what got installed.",
13
13
  "examples": [
14
14
  "<%= config.bin %> <%= command.id %> docs.msg91.com",
15
15
  "<%= config.bin %> <%= command.id %> localhost:3000 --collectionId paM4R4A26Hvb"
@@ -38,12 +38,58 @@
38
38
  "init.js"
39
39
  ]
40
40
  },
41
+ "list": {
42
+ "aliases": [],
43
+ "args": {
44
+ "collection": {
45
+ "description": "Show modules installed for this collection (CLI name), e.g. msg91",
46
+ "name": "collection",
47
+ "required": false
48
+ },
49
+ "module": {
50
+ "description": "Show all endpoints for this module within the collection, e.g. slack",
51
+ "name": "module",
52
+ "required": false
53
+ }
54
+ },
55
+ "description": "List installed collections, the modules within one, or every endpoint of one module",
56
+ "examples": [
57
+ "<%= config.bin %> <%= command.id %> # list every installed collection",
58
+ "<%= config.bin %> <%= command.id %> --all # same as above",
59
+ "<%= config.bin %> <%= command.id %> msg91 # list modules installed for the \"msg91\" collection",
60
+ "<%= config.bin %> <%= command.id %> msg91 slack # list all of Slack's installed endpoints in \"msg91\""
61
+ ],
62
+ "flags": {
63
+ "all": {
64
+ "description": "List every installed collection (default when no arguments are given)",
65
+ "name": "all",
66
+ "allowNo": false,
67
+ "type": "boolean"
68
+ }
69
+ },
70
+ "hasDynamicHelp": false,
71
+ "hiddenAliases": [],
72
+ "id": "list",
73
+ "pluginAlias": "docstar-cli",
74
+ "pluginName": "docstar-cli",
75
+ "pluginType": "core",
76
+ "strict": true,
77
+ "enableJsonFlag": false,
78
+ "isESM": true,
79
+ "relativePath": [
80
+ "dist",
81
+ "commands",
82
+ "list.js"
83
+ ]
84
+ },
41
85
  "mcp": {
42
86
  "aliases": [],
43
87
  "args": {},
44
- "description": "Start an MCP server exposing every installed endpoint as a tool for AI clients (Claude Desktop, Claude Code, etc.)",
88
+ "description": "Start an MCP (Model Context Protocol) server exposing every installed endpoint (across all installed collections) as a callable tool for AI clients (Claude Desktop, Claude Code, etc.).\nEach endpoint becomes one tool named `<cli-name>__<module>__<command>`, e.g. `msg91__slack__send-message-1`. Run `docstar-cli init <domain>` first so there is at least one installed module to expose.\nThis command does not exit on its own — it stays running and communicates over stdio for as long as the connecting AI client keeps the connection open.",
45
89
  "examples": [
46
- "<%= config.bin %> <%= command.id %>"
90
+ "<%= config.bin %> <%= command.id %>",
91
+ "# Then register it in an MCP client config, e.g. .mcp.json:",
92
+ "# { \"mcpServers\": { \"docstar\": { \"command\": \"docstar-cli\", \"args\": [\"mcp\"] } } }"
47
93
  ],
48
94
  "flags": {},
49
95
  "hasDynamicHelp": false,
@@ -61,25 +107,44 @@
61
107
  "mcp.js"
62
108
  ]
63
109
  },
64
- "hello": {
110
+ "api-collection-2:viasocket:send-alert": {
65
111
  "aliases": [],
66
- "args": {
67
- "person": {
68
- "description": "Person to say hello to",
69
- "name": "person",
70
- "required": true
112
+ "args": {},
113
+ "description": "send alert",
114
+ "flags": {
115
+ "message": {
116
+ "description": "Required parameter",
117
+ "name": "message",
118
+ "hasDynamicHelp": false,
119
+ "multiple": false,
120
+ "type": "option"
71
121
  }
72
122
  },
73
- "description": "Say hello",
74
- "examples": [
75
- "<%= config.bin %> <%= command.id %> friend --from oclif\nhello friend from oclif! (./src/commands/hello/index.ts)\n"
76
- ],
123
+ "hasDynamicHelp": false,
124
+ "hiddenAliases": [],
125
+ "id": "api-collection-2:viasocket:send-alert",
126
+ "pluginAlias": "docstar-cli",
127
+ "pluginName": "docstar-cli",
128
+ "pluginType": "core",
129
+ "strict": true,
130
+ "enableJsonFlag": false,
131
+ "isESM": true,
132
+ "relativePath": [
133
+ "dist",
134
+ "commands",
135
+ "api-collection-2",
136
+ "viasocket",
137
+ "send-alert.js"
138
+ ]
139
+ },
140
+ "api-collection:slack:send-message-1": {
141
+ "aliases": [],
142
+ "args": {},
143
+ "description": "send message",
77
144
  "flags": {
78
- "from": {
79
- "char": "f",
80
- "description": "Who is saying hello",
81
- "name": "from",
82
- "required": true,
145
+ "message": {
146
+ "description": "Required parameter",
147
+ "name": "message",
83
148
  "hasDynamicHelp": false,
84
149
  "multiple": false,
85
150
  "type": "option"
@@ -87,7 +152,7 @@
87
152
  },
88
153
  "hasDynamicHelp": false,
89
154
  "hiddenAliases": [],
90
- "id": "hello",
155
+ "id": "api-collection:slack:send-message-1",
91
156
  "pluginAlias": "docstar-cli",
92
157
  "pluginName": "docstar-cli",
93
158
  "pluginType": "core",
@@ -97,21 +162,48 @@
97
162
  "relativePath": [
98
163
  "dist",
99
164
  "commands",
100
- "hello",
101
- "index.js"
165
+ "api-collection",
166
+ "slack",
167
+ "send-message-1.js"
102
168
  ]
103
169
  },
104
- "hello:world": {
170
+ "docstar-apis:public-routes:find-matches-1": {
105
171
  "aliases": [],
106
172
  "args": {},
107
- "description": "Say hello world",
108
- "examples": [
109
- "<%= config.bin %> <%= command.id %>\nhello world! (./src/commands/hello/world.ts)\n"
110
- ],
111
- "flags": {},
173
+ "description": "Find matches",
174
+ "flags": {
175
+ "query": {
176
+ "description": "Required parameter",
177
+ "name": "query",
178
+ "hasDynamicHelp": false,
179
+ "multiple": false,
180
+ "type": "option"
181
+ },
182
+ "collectionIds": {
183
+ "description": "Required parameter",
184
+ "name": "collectionIds",
185
+ "hasDynamicHelp": false,
186
+ "multiple": false,
187
+ "type": "option"
188
+ },
189
+ "getUrl": {
190
+ "description": "Required parameter",
191
+ "name": "getUrl",
192
+ "hasDynamicHelp": false,
193
+ "multiple": false,
194
+ "type": "option"
195
+ },
196
+ "allowNonDomain": {
197
+ "description": "Required parameter",
198
+ "name": "allowNonDomain",
199
+ "hasDynamicHelp": false,
200
+ "multiple": false,
201
+ "type": "option"
202
+ }
203
+ },
112
204
  "hasDynamicHelp": false,
113
205
  "hiddenAliases": [],
114
- "id": "hello:world",
206
+ "id": "docstar-apis:public-routes:find-matches-1",
115
207
  "pluginAlias": "docstar-cli",
116
208
  "pluginName": "docstar-cli",
117
209
  "pluginType": "core",
@@ -121,10 +213,11 @@
121
213
  "relativePath": [
122
214
  "dist",
123
215
  "commands",
124
- "hello",
125
- "world.js"
216
+ "docstar-apis",
217
+ "public-routes",
218
+ "find-matches-1.js"
126
219
  ]
127
220
  }
128
221
  },
129
- "version": "1.0.1"
222
+ "version": "1.0.3"
130
223
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "docstar-cli",
3
- "description": "A new CLI generated with oclif",
4
- "version": "1.0.1",
3
+ "description": "Call published DocStar API endpoints directly from your terminal, or expose them as MCP tools for AI clients.",
4
+ "version": "1.0.3",
5
5
  "author": "Swayam Maheshwari",
6
6
  "bin": {
7
7
  "docstar-cli": "./bin/run.js"
@@ -56,11 +56,9 @@
56
56
  "@oclif/plugin-plugins"
57
57
  ],
58
58
  "topicSeparator": " ",
59
- "topics": {
60
- "hello": {
61
- "description": "Say hello to the world and others"
62
- }
63
- }
59
+ "additionalVersionFlags": [
60
+ "-v"
61
+ ]
64
62
  },
65
63
  "repository": "swayammaheshwari/docstar-cli",
66
64
  "scripts": {
@@ -1,12 +0,0 @@
1
- import { Command } from '@oclif/core';
2
- export default class Hello extends Command {
3
- static args: {
4
- person: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
5
- };
6
- static description: string;
7
- static examples: string[];
8
- static flags: {
9
- from: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
10
- };
11
- run(): Promise<void>;
12
- }
@@ -1,19 +0,0 @@
1
- import { Args, Command, Flags } from '@oclif/core';
2
- export default class Hello extends Command {
3
- static args = {
4
- person: Args.string({ description: 'Person to say hello to', required: true }),
5
- };
6
- static description = 'Say hello';
7
- static examples = [
8
- `<%= config.bin %> <%= command.id %> friend --from oclif
9
- hello friend from oclif! (./src/commands/hello/index.ts)
10
- `,
11
- ];
12
- static flags = {
13
- from: Flags.string({ char: 'f', description: 'Who is saying hello', required: true }),
14
- };
15
- async run() {
16
- const { args, flags } = await this.parse(Hello);
17
- this.log(`hello ${args.person} from ${flags.from}! (./src/commands/hello/index.ts)`);
18
- }
19
- }
@@ -1,8 +0,0 @@
1
- import { Command } from '@oclif/core';
2
- export default class World extends Command {
3
- static args: {};
4
- static description: string;
5
- static examples: string[];
6
- static flags: {};
7
- run(): Promise<void>;
8
- }
@@ -1,14 +0,0 @@
1
- import { Command } from '@oclif/core';
2
- export default class World extends Command {
3
- static args = {};
4
- static description = 'Say hello world';
5
- static examples = [
6
- `<%= config.bin %> <%= command.id %>
7
- hello world! (./src/commands/hello/world.ts)
8
- `,
9
- ];
10
- static flags = {};
11
- async run() {
12
- this.log('hello world! (./src/commands/hello/world.ts)');
13
- }
14
- }