Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,22 @@ apijack supports pluggable authentication:
| `routine validate <name>` | Validate routine YAML |
| `routine test <name>` | Run a routine's spec/test file |

### Turning off built-in commands

A CLI can leave out the optional `mcp` and `plugin` commands:

```json
// .apijack/settings.json
{ "disableCommands": ["mcp"] }
```

A project with its own `bin/<cli>.ts` passes `createCli({ disableCommands: ['mcp'], /* ... */ })` instead.

- Turning off `mcp` also turns off `plugin`, which registers the MCP server with Claude Code.
- With `plugin` off (directly or through `mcp`), updates (`upgrade` and the startup update prompt) no longer re-run `plugin install`.
- A turned-off command isn't registered: it's missing from help, and running it is an unknown-command error.
- Only `mcp` and `plugin` can be turned off. Any other value is dropped with a warning.

### Running one command against another environment

A leading `--config <name>` runs a single invocation against any environment in `config.json`, without changing the active one:
Expand All @@ -157,6 +173,8 @@ A leading `--config <name>` runs a single invocation against any environment in

Run `<cli> mcp` to start a Model Context Protocol server, exposing all CLI commands as MCP tools for use with AI agents and editors.

A CLI can turn it off with `disableCommands` — see "Turning off built-in commands" above.

## AI Agent Integration

apijack CLIs can be driven by any AI agent or automation tool:
Expand Down
20 changes: 19 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ The `.apijack/` directory at a project root is auto-loaded when the CLI runs ins
| `.apijack/auth.ts` | Project-level `AuthStrategy` and optional `onChallenge` |
| `.apijack/plugins.ts` | Project-level plugin registrations (`default: ApijackPlugin[]` — each entry passed to `cli.use(...)`) |
| `.apijack/routines/*.yaml` | Routines available via `routine run <name>` |
| `.apijack/settings.json` | Framework defaults (see below; also `auth.refreshOn` — see "Stale-session refresh and retry" above) |
| `.apijack/settings.json` | Framework defaults (see below; also `auth.refreshOn` — see "Stale-session refresh and retry" above, and `disableCommands` — see "Turning off built-in commands") |
| `.apijack/aliases.json` | Project-local command aliases (see below) |

### Command aliases
Expand Down Expand Up @@ -341,6 +341,22 @@ Module-level `requiresAuth` overrides the settings default. On `CliContext`:
| `routine validate <name>` | Validate routine YAML |
| `routine test <name>` | Run a routine's spec/test file |

### Turning off built-in commands

A CLI can leave out the optional `mcp` and `plugin` commands:

```json
// .apijack/settings.json
{ "disableCommands": ["mcp"] }
```

A project with its own `bin/<cli>.ts` passes `createCli({ disableCommands: ['mcp'], /* ... */ })` instead.

- Turning off `mcp` also turns off `plugin`, which registers the MCP server with Claude Code.
- With `plugin` off (directly or through `mcp`), updates (`upgrade` and the startup update prompt) no longer re-run `plugin install`.
- A turned-off command isn't registered: it's missing from help, and running it is an unknown-command error.
- Only `mcp` and `plugin` can be turned off. Any other value is dropped with a warning.

### Running one command against another environment

A leading `--config <name>` runs a single invocation against any environment in `config.json`, without changing the active one:
Expand All @@ -360,6 +376,8 @@ A leading `--config <name>` runs a single invocation against any environment in

Run `<cli> mcp` to start a Model Context Protocol server, exposing all CLI commands as MCP tools for use with AI agents and editors.

A CLI can turn it off with `disableCommands` — see "Turning off built-in commands" above.

## Claude Code Integration

This project follows the CLAUDE.md convention for Claude Code. Key patterns:
Expand Down
18 changes: 18 additions & 0 deletions GEMINI.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,22 @@ apijack supports pluggable authentication:
| `routine validate <name>` | Validate routine YAML |
| `routine test <name>` | Run a routine's spec/test file |

### Turning off built-in commands

A CLI can leave out the optional `mcp` and `plugin` commands:

```json
// .apijack/settings.json
{ "disableCommands": ["mcp"] }
```

A project with its own `bin/<cli>.ts` passes `createCli({ disableCommands: ['mcp'], /* ... */ })` instead.

- Turning off `mcp` also turns off `plugin`, which registers the MCP server with Claude Code.
- With `plugin` off (directly or through `mcp`), updates (`upgrade` and the startup update prompt) no longer re-run `plugin install`.
- A turned-off command isn't registered: it's missing from help, and running it is an unknown-command error.
- Only `mcp` and `plugin` can be turned off. Any other value is dropped with a warning.

### Running one command against another environment

A leading `--config <name>` runs a single invocation against any environment in `config.json`, without changing the active one:
Expand All @@ -157,6 +173,8 @@ A leading `--config <name>` runs a single invocation against any environment in

Run `<cli> mcp` to start a Model Context Protocol server, exposing all CLI commands as MCP tools for use with AI agents and editors.

A CLI can turn it off with `disableCommands` — see "Turning off built-in commands" above.

## Gemini Integration

This project follows the GEMINI.md convention. Key patterns:
Expand Down
17 changes: 14 additions & 3 deletions bin/apijack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { findProjectConfig, loadProjectConfig, resolveConfigDir } from '../src/p
import { loadProjectAuth, loadProjectCommands, loadProjectDispatchers, loadProjectPlugins, loadProjectResolvers } from '../src/project-loader';
import { loadProjectSettings } from '../src/settings';
import { checkForUpdate } from '../src/updater';
import { shouldReinstallPlugin } from '../src/post-update';
import { commandGates } from '../src/command-gates';
import { getPluginPaths } from '../src/plugin/paths';
import { getActiveEnvConfig } from '../src/config';
import { takeLeadingOption } from '../src/leading-options';
import pkg from '../package.json';
Expand All @@ -23,9 +26,6 @@ const CLI_NAME = 'apijack';
const globalDir = join(homedir(), '.apijack');
mkdirSync(globalDir, { recursive: true });

// 2. Check for updates (24h throttle)
await checkForUpdate(VERSION, globalDir);

// 3. Detect project mode
const projectConfigPath = findProjectConfig(process.cwd());
const projectConfig = projectConfigPath ? loadProjectConfig(projectConfigPath) : null;
Expand Down Expand Up @@ -148,6 +148,16 @@ const projectSettings = projectRoot
? loadProjectSettings(join(projectRoot, '.apijack'))
: {};

// 8b. Check for updates (throttled). Runs after the settings load so a
// project that turned off `mcp` / `plugin` doesn't get `plugin install`
// re-run after updating.
await checkForUpdate(VERSION, globalDir, {
reinstallPlugin: shouldReinstallPlugin({
...commandGates(projectSettings.disableCommands),
marketplaceDir: getPluginPaths(VERSION).marketplaceDir,
}),
});

// 9. Create CLI
// `name` stays apijack so storage paths (~/.apijack/) and env-var prefix
// (APIJACK_*) are unaffected. `programName`, `description`, and `version`
Expand All @@ -168,6 +178,7 @@ const cli = createCli({
defaultUrl: projectConfig?.defaultUrl,
configPath: join(configDir, 'config.json'),
customCommandDefaults: projectSettings.customCommands?.defaults,
disableCommands: projectSettings.disableCommands,
});

// 10. Register project-level extensions
Expand Down
110 changes: 66 additions & 44 deletions src/cli-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ import { registerSetupCommand, setupAction, setupUrlDefault } from './commands/s
import { registerConfigCommand } from './commands/config/register';
import { registerGenerateCommand } from './commands/generate/generate';
import { registerUpgradeCommand } from './commands/upgrade/upgrade';
import { shouldReinstallPlugin } from './post-update';
import { commandGates } from './command-gates';
import { getPluginPaths } from './plugin/paths';
import { registerMcpCommand } from './commands/mcp/mcp';
import { registerRoutineCommand, loadBuiltinRoutines } from './commands/routine/register';
import { prompt, hiddenPrompt } from './prompt';
Expand Down Expand Up @@ -65,23 +68,14 @@ export interface RunRoutineOptions {
dryRun?: boolean;
}

const CORE_COMMANDS = new Set([
'setup',
'login',
'config',
'generate',
'routine',
'upgrade',
'mcp',
'plugin',
'plugins',
]);

function showCustomHelp(
program: Command,
displayName: string,
showAll: boolean,
customCommandNames: Set<string>,
/** The built-in Command instances, so an API group that happens to share a
* built-in's name (e.g. `mcp` once the built-in is off) isn't listed as one. */
builtinCommands: ReadonlySet<Command>,
): void {
console.log(`Usage: ${program.name()} [options] [command]\n`);
console.log(`${program.description()}\n`);
Expand All @@ -99,10 +93,10 @@ function showCustomHelp(
console.log(` ${'-h, --help'.padEnd(30)} display help for command`);

// Core commands
const core = program.commands.filter(c => CORE_COMMANDS.has(c.name()));
const custom = program.commands.filter(c => customCommandNames.has(c.name()));
const core = program.commands.filter(c => builtinCommands.has(c));
const custom = program.commands.filter(c => !builtinCommands.has(c) && customCommandNames.has(c.name()));
const api = program.commands.filter(
c => !CORE_COMMANDS.has(c.name()) && !customCommandNames.has(c.name()) && c.name() !== 'help',
c => !builtinCommands.has(c) && !customCommandNames.has(c.name()) && c.name() !== 'help',
);

if (core.length > 0) {
Expand Down Expand Up @@ -149,6 +143,7 @@ export function createCli(options: CliOptions): Cli {
: join(homedir(), `.${cliName}`);
const routinesDir = join(configDir, 'routines');
const generatedDir = options.generatedDir ?? join(process.cwd(), 'src', 'generated');
const { mcpEnabled, pluginEnabled } = commandGates(options.disableCommands);
const defaultRequiresAuth = options.customCommandDefaults?.requiresAuth ?? false;
const effectiveRequiresAuth = (explicit: boolean | undefined): boolean =>
explicit ?? defaultRequiresAuth;
Expand Down Expand Up @@ -535,30 +530,55 @@ export function createCli(options: CliOptions): Cli {
);
program.option('--dry-run', 'Preview the API request without executing');

// 3. Register built-in commands
registerSetupCommand(program, cliName, {
allowedCidrs: options.allowedCidrs,
configPath: options.configPath,
displayName,
defaultUrl: options.defaultUrl,
});
registerConfigCommand(program, cliName, {
configPath: options.configPath,
knownSites: options.knownSites,
allowedCidrs: options.allowedCidrs,
displayName,
sessions: { configDir, currentEnvironment },
// 3. Register built-in commands. Track the Command instances so help
// can tell them apart from API groups and project commands.
const builtinCommands = new Set<Command>();
const markBuiltins = (register: () => void): void => {
const before = new Set(program.commands);
register();

for (const c of program.commands) {
if (!before.has(c)) builtinCommands.add(c);
}
};
markBuiltins(() => {
registerSetupCommand(program, cliName, {
allowedCidrs: options.allowedCidrs,
configPath: options.configPath,
displayName,
defaultUrl: options.defaultUrl,
});
registerConfigCommand(program, cliName, {
configPath: options.configPath,
knownSites: options.knownSites,
allowedCidrs: options.allowedCidrs,
displayName,
sessions: { configDir, currentEnvironment },
});
registerUpgradeCommand(program, options.version, {
reinstallPlugin: () => shouldReinstallPlugin({
mcpEnabled,
pluginEnabled,
marketplaceDir: getPluginPaths(options.version).marketplaceDir,
}),
});

if (mcpEnabled) {
registerMcpCommand(
program,
cliName,
resolve(options.generatedDir || 'src/generated'),
join(homedir(), '.' + options.name, 'routines'),
{ environment: () => selectedEnvironment, configPath: options.configPath },
);
}

if (pluginEnabled) {
registerPluginCommand(program, cliName, options.version);
}

registerPluginsCommand(program, pluginRegistry, options.version);
});
registerUpgradeCommand(program, options.version);
registerMcpCommand(
program,
cliName,
resolve(options.generatedDir || 'src/generated'),
join(homedir(), '.' + options.name, 'routines'),
{ environment: () => selectedEnvironment, configPath: options.configPath },
);
registerPluginCommand(program, cliName, options.version);
registerPluginsCommand(program, pluginRegistry, options.version);

// 4. Resolve auth
let environment = currentEnvironment();
Expand All @@ -573,9 +593,11 @@ export function createCli(options: CliOptions): Cli {
'routine',
'generate',
'upgrade',
'mcp',
'plugin',
'plugins',
// Only while the built-in exists: with it off, an API group of
// that name is an ordinary API command and needs auth.
...(mcpEnabled ? ['mcp'] : []),
...(pluginEnabled ? ['plugin'] : []),
]);
const isVersion = leadingOptions.some(o => o.flag === '--version' || o.flag === '-V');
const isHelpOrVersion = isVersion
Expand Down Expand Up @@ -637,15 +659,15 @@ export function createCli(options: CliOptions): Cli {
}

// 5b. Register generate (depends on strategy + sessionMgr from step 5)
registerGenerateCommand(
markBuiltins(() => registerGenerateCommand(
program,
cliName,
options.specPath,
generatedDir,
envOpts(),
strategy,
sessionMgr,
);
));

// 6. Import generated commands (ALWAYS — no auth needed)
let commandsModule: Record<string, unknown> | null = null;
Expand Down Expand Up @@ -944,7 +966,7 @@ export function createCli(options: CliOptions): Cli {
}

// 12. Register routine commands
registerRoutineCommand(program, cliName, routinesDir, dispatch, options.builtinRoutinesDir, customResolvers, pluginRegistry, displayName);
markBuiltins(() => registerRoutineCommand(program, cliName, routinesDir, dispatch, options.builtinRoutinesDir, customResolvers, pluginRegistry, displayName));

// 13. Handle -o routine-step
if (isRoutineStep) {
Expand Down Expand Up @@ -1040,7 +1062,7 @@ export function createCli(options: CliOptions): Cli {
if (commandArgs.length === 0 && !isVersion && leadingAccepted) {
const showAll = leadingOptions.some(o => isHelpFlag(o.flag));
const customCommandNames = new Set(consumerCommands.map(c => c.name));
showCustomHelp(program, displayName, showAll, customCommandNames);
showCustomHelp(program, displayName, showAll, customCommandNames, builtinCommands);
process.exit(0);
}

Expand Down
8 changes: 8 additions & 0 deletions src/command-gates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { DisableableCommand } from './types';

/** Which optional built-ins are on. `plugin` registers the MCP server, so turning off `mcp` turns it off too. */
export function commandGates(disable: readonly DisableableCommand[] = []): { mcpEnabled: boolean; pluginEnabled: boolean } {
const mcpEnabled = !disable.includes('mcp');

return { mcpEnabled, pluginEnabled: mcpEnabled && !disable.includes('plugin') };
}
16 changes: 9 additions & 7 deletions src/commands/upgrade/upgrade.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Command } from 'commander';
import { defaultSpawnCli, refreshAfterUpdate } from '../../post-update';

export interface UpgradeInput {
currentVersion: string;
Expand Down Expand Up @@ -42,7 +43,11 @@ async function bunInstallGlobal(version: string): Promise<number> {
return proc.exited;
}

export function registerUpgradeCommand(program: Command, version: string): void {
export function registerUpgradeCommand(
program: Command,
version: string,
opts?: { reinstallPlugin?: () => boolean },
): void {
program
.command('upgrade')
.description('Check for and install the latest version')
Expand All @@ -62,13 +67,10 @@ export function registerUpgradeCommand(program: Command, version: string): void

console.log(`v${result.previousVersion} → v${result.newVersion}`);

// Update plugin registration
const pluginProc = Bun.spawn([...process.argv.slice(0, 2), 'plugin', 'install'], {
stdout: 'inherit',
stderr: 'inherit',
env: { ...process.env, APIJACK_SKIP_UPDATE: '1' },
await refreshAfterUpdate({
reinstallPlugin: opts?.reinstallPlugin?.() ?? false,
spawnCli: defaultSpawnCli(),
});
await pluginProc.exited;

console.log(`Upgraded to v${result.newVersion}.`);
} catch (err) {
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export type {
CustomResolver,
CustomResolverHelpers,
ApijackPlugin,
DisableableCommand,
} from './types';
export {
PluginNamespaceError,
Expand Down
Loading
Loading