@happyvertical/smrt-app-cli

中文文档
0.62.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 1.5万

Reusable CLI factory for SMRT apps — branded <name> <resource> <command> CLI + stdio MCP bridge with decorator-driven resource discovery

原始使用文档
文档目录11 节
  1. Installation
  2. Quick start
  3. Discovery conformance artifact
  4. Remote MCP client commands
  5. Add an app-specific command
  6. MCP bridge
  7. Configuration and authentication
  8. Public API
  9. Development
  10. Generate local desktop plugin metadata
  11. Generated local-client setup

@happyvertical/smrt-app-cli

Reusable, application-branded CLI support for s-m-r-t apps. It combines resource discovery, generated command invocation, device-code authentication, local configuration, and an MCP stdio bridge without coupling the CLI to one app.

Use this package when a deployed s-m-r-t application should expose a branded <app> <resource> <command> CLI. Use @happyvertical/smrt-cli for framework development, schema, and code-generation commands.

Installation

pnpm add @happyvertical/smrt-app-cli

Node.js 26 or newer is required.

The published package also exposes a configuration-driven smrt-app binary. It lets policy runners and app operators use the canonical CLI outside a consumer repository without maintaining a branded wrapper:

SMRT_APP_NAME=work \
SMRT_APP_ENV_PREFIX=WORK \
SMRT_APP_CONFIG_DIR=happyvertical-work \
SMRT_APP_DEFAULT_SERVER_URL=https://work.example \
pnpm dlx --package @happyvertical/[email protected] \
  smrt-app -- auth status

Pin the exact published package version in automation. The four application settings are required and are non-secret; command arguments after -- are forwarded unchanged to createAppCli. The same values may be passed as --name, --env-prefix, --config-dir, and --default-server-url before the delimiter. Invalid or incomplete configuration fails before the CLI performs network or credential access. The executable also applies the HTTPS/loopback policy to the effective server URL selected from app-specific environment or persisted configuration, and to command-level server overrides.

To run the same CLI's stdio MCP bridge, configure its explicit identity and select bridge mode:

SMRT_APP_NAME=work \
SMRT_APP_ENV_PREFIX=WORK \
SMRT_APP_CONFIG_DIR=happyvertical-work \
SMRT_APP_DEFAULT_SERVER_URL=https://work.example \
SMRT_APP_MCP_SERVER_NAME=work-mcp \
SMRT_APP_MCP_SERVER_VERSION=1.0.0 \
smrt-app --stdio-mcp

SMRT_APP_* is reserved for non-secret executable configuration. Runtime credentials continue to use the app-specific environment/config resolution implemented by createAppCli; never pass bearer tokens as executable options.

Quick start

#!/usr/bin/env node
import { createAppCli } from '@happyvertical/smrt-app-cli';

const cli = createAppCli({
  name: 'acme',
  defaultServerUrl: 'https://app.acme.test',
});

await cli.run(process.argv.slice(2));

The resulting CLI includes:

acme auth login [--server <url>] [--no-open]
acme auth status
acme auth logout
acme resources [--json] [--debug]
acme mcp
acme <resource> <command> [flags]

Resources and their commands are discovered from the app's /_resources surface. JSON Schema becomes CLI flags, while unsupported schema shapes are reported instead of silently guessed.

Discovery conformance artifact

createResourceListHandler() includes an artifact beside the compatible user, warnings, and resources response fields. The artifact has a stable schema selector, version, canonical ordering, and a sha256:<hex> digest. The CLI validates it before using its embedded discovery payload.

For a released downstream app, install the exact published @happyvertical/smrt-users version and pin a captured artifact like this:

import {
  validateDiscoveryConformanceArtifact,
} from '@happyvertical/smrt-users/app-contract';

const response = await fetch('https://app.example/api/_resources');
const body = await response.json();
const artifact = validateDiscoveryConformanceArtifact(body.artifact);

console.log(artifact.schema, artifact.version, artifact.integrity.digest);
// Store all three selectors and the canonical JSON in your packaged-runtime test.

The result contract embedded in the artifact names the common code, message, details, retryable, correlationId, idempotencyKey, and expectedVersion metadata. mcp tools and mcp call print this as a JSON success/error envelope. HTTP failures may use either a conventional top-level metadata object or { error: metadata }; both normalize to that same shape. Generated action failures use the latter form with { error: { ok: false, code, message, status, ... } }; the CLI reports the HTTP status beside that normalized metadata. The stdio bridge carries it in MCP _meta under io.happyvertical/smrt. It deliberately does not synthesize MCP structuredContent.

Remote MCP client commands

<app> mcp tools lists and <app> mcp call <tool> '<json>' invokes tools on a deployed app's modern MCP endpoint (Streamable HTTP at exactly /api/mcp, or mcpPath), printing the JSON result. Flags:

  • --url <server> targets a server other than the configured one.
  • --token-env <NAME> reads the bearer token from that environment variable. The token is never printed: it is scrubbed from stdout and stderr, and errors name only the variable. An explicit token requires an HTTPS (or loopback) --url. Without it the stored login token is used.
  • --mcp-path <path> overrides the same-server MCP route.
  • --legacy-rest opts in to the deprecated <mcpPath>/tools and <mcpPath>/call REST routes and their result envelope.
  • --confirm (mcp call only) sets confirm: true in the call arguments for outbound or destructive tools. It is never added unless passed, and the arguments must be a JSON object. A "confirm": true already present in the JSON passes through unchanged.
WORK_OWNER_TOKEN=... acme mcp call send_invoice '{"id":"inv_1"}' \
  --url https://work.example.com --token-env WORK_OWNER_TOKEN --confirm

Add an app-specific command

const cli = createAppCli({
  name: 'acme',
  extraCommands: [
    {
      name: 'doctor',
      description: 'Check the deployed app',
      async run(_args, context) {
        const health = await context.requestJson('/api/health');
        context.stdout.write(`${JSON.stringify(health, null, 2)}\n`);
      },
    },
  ],
});

App-specific commands win over built-ins. Avoid names that may collide with a discovered resource slug.

MCP bridge

The same app CLI can expose the deployed application's MCP surface to local stdio clients:

await cli.startMcpBridge({ name: 'acme-mcp', version: '1.0.0' });

The bridge forwards to /api/mcp by default. When the app mounts its MCP route elsewhere, set mcpPath on createAppCli() or pass it per call (startMcpBridge({ mcpPath: '/mcp' })). The binaries take --mcp-path=/mcp (smrt-mcp-bridge, or SMRT_MCP_PATH) and --mcp-path / SMRT_APP_MCP_PATH (smrt-app). The path must be same-server and absolute.

For a local-profile s-m-r-t app, mint a credential with smrt app token --scopes <scope> in the app checkout. The token is printed once. Then give the bridge the loopback server and that token through the app's environment prefix. This Claude Desktop entry is an example:

{
  "mcpServers": {
    "notes": {
      "command": "npx",
      "args": ["smrt-mcp-bridge", "--env-prefix=NOTES", "--mcp-path=/mcp"],
      "env": {
        "NOTES_SERVER_URL": "http://127.0.0.1:5173",
        "NOTES_TOKEN": "smrt_mcp_…"
      }
    }
  }
}

The token is sent only when <PREFIX>_SERVER_URL matches the target server. Revoke a token with smrt app token revoke <id>.

The package also ships the generic smrt-mcp-bridge binary. The remote app surface is typically mounted with @happyvertical/smrt-app-mcp. The binary rejects non-loopback plaintext HTTP origins before resolving or sending stored credentials; use HTTPS for remote application servers.

The default native MCP bridge preserves upstream tool catalog order and forwards tools/list, tools/call, resources/list, and resources/read through SDK v2. Tool catalogs and resource responses use a zero TTL with private cache scope so subsequent requests recheck upstream authorization. The bridge uses the configured local app credentials and never opts into shared caching.

Only the explicit transport: 'legacy-rest' compatibility mode sorts its tools/list catalog by tool name and emits a one-day private cache lifetime. That mode uses the REST-shaped tools endpoints and does not forward resources.

Configuration and authentication

  • name supplies the display name and default environment-variable prefix.
  • envPrefix overrides that prefix; configDir overrides the local config namespace.
  • defaultServerUrl is used only when neither environment nor stored config supplies a server.
  • Device-code login distinguishes pending approval, expiry, transient network failure, and hard rejection.
  • Tokens and server configuration stay in the app-specific local config path.
  • Device-flow responses identify their issuer. Tokens are keyed by that exact issuer and are not reused when the configured server changes.

For standards-based remote MCP OAuth registration, use registerMcpClient() (Client ID Metadata Document first, executable RFC 7591 DCR fallback with application_type) and follow the remote MCP authorization guide.

Public API

ExportPurpose
createAppCli()Build the branded CLI and MCP bridge
createMcpStdioBridge() / runMcpStdioBridge()Lower-level bridge control
fetchResourceList()Fetch the deployed resource catalog
invokeCommand()Invoke one generated resource command
buildFlagParser()Convert supported JSON Schema to flags
loadCliConfig() / saveCliConfig()Read and write namespaced CLI config
resolveMcpClientRegistration()Inspect the selected Client ID Metadata or DCR path
registerMcpClient()Use Client ID Metadata or execute the DCR fallback

Development

pnpm --filter @happyvertical/smrt-app-cli test
pnpm --filter @happyvertical/smrt-app-cli typecheck
pnpm --filter @happyvertical/smrt-app-cli build

Maintainer patterns and authentication invariants are documented in AGENTS.md.

For remote deployments with a known OAuth issuer, set CliConfigContext.expectedCredentialIssuer to its exact identifier. Stored credentials must match both server and issuer; environment credentials also require ${PREFIX}_TOKEN_ISSUER. This does not replace the terminal device flow with browser OAuth. See the remote authorization contract.

Generate local desktop plugin metadata

Use generateDesktopPluginArtifacts in the product's packaging step. Pass public product metadata from the portable plugin manifest, such as the checked-in Kitchen manifest. The required fields are name (lowercase letters, digits and single hyphens), version (SemVer), description, and author.name. The optional extensions["com.openai"].interface.displayName defaults to name.

import { generateDesktopPluginArtifacts } from '@happyvertical/smrt-app-cli';

const files = generateDesktopPluginArtifacts(productManifest, {
  platform: 'darwin',
  executable: 'server/smrt-mcp-launcher',
});

The result maps distribution-root-relative paths to deterministic UTF-8 JSON. Materialize the files in a fresh staging directory. Place the executable under the same server/ path in each plugin directory. Run the generator for the target platform (darwin, win32, or linux), using an .exe launcher filename for Windows. The launcher must resolve the installed app's bundled runtime and obtain local authorization at launch. The generator reads public metadata only and takes no environment, MCP arguments, endpoint, or authentication configuration.

  • claude-desktop/<name>/manifest.json is the binary extension manifest in the staging directory for mcpb pack. Include the executable when packing. The manifest declares the target platform and resolves the launcher from the installed extension directory. Claude Desktop Extensions · MCPB manifest format
  • plugins/<name>/plugin.json and mcp.json are the portable ChatGPT desktop plugin, listed in .agents/plugins/marketplace.json. OpenAI plugin packaging · Desktop-only plugins · Agent Plugins stdio path rules
  • plugins/<name>/.claude-plugin/plugin.json and .claude-plugin/marketplace.json provide Claude Code marketplace compatibility. Claude Desktop installs the MCPB extension from the separate staging directory. Claude Code marketplaces

Each generated catalog contains one entry. For a shared catalog, merge the entry into the catalog maintained by the packager. Live installation and execution in Claude Desktop and ChatGPT desktop require the production launcher and separate host verification.

Generated local-client setup

generateLocalMcpSetup({name,command,args}) renders Claude Code's shell-quoted claude mcp add, Claude Desktop/.mcp.json JSON and Codex TOML for an existing owner-authorized stdio launcher. Pass public executable/launcher paths only, never a bearer. CliConfigContext.configPath lets the app write its private connection directly through saveCliConfig without mutating process environment. Modern stdio bridges advertise tools.listChanged and poll the stateless upstream catalog every two seconds (including pages). Changed descriptors, revocation and recovery invalidate discovery; close clears the timer. No shared catalog cache.

版本与发布记录

@happyvertical/smrt-app-cli 共发布 366 个版本,首次发布于 2026/06/23;过去 12 个月发布了 366 个版本。

版本发布日期距今
0.62.1latest2026/11/17今天
0.62.02026/11/17今天
0.61.62026/11/161 天前
0.61.52026/11/161 天前
0.61.42026/11/161 天前
0.61.32026/11/152 天前

关于 @happyvertical/smrt-app-cli 的常见问题

@happyvertical/smrt-app-cli 是什么?

Reusable CLI factory for SMRT apps — branded <name> <resource> <command> CLI + stdio MCP bridge with decorator-driven resource discovery

如何安装 @happyvertical/smrt-app-cli?

在项目目录运行 npm install @happyvertical/smrt-app-cli,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 smrt-app、smrt-mcp-bridge,可以用 npx smrt-app 直接运行。

@happyvertical/smrt-app-cli 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyvertical/smrt-app-cli 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/smrt-app-cli 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=26.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@happyvertical/smrt-app-cli 可以商用吗?

@happyvertical/smrt-app-cli 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/smrt-app-cli 的下载量有多少?

根据 npm 官方下载统计,@happyvertical/smrt-app-cli 在 2026/10/17 – 2026/11/15 这 30 天内被下载 14,909 次,日均约 497 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyvertical/smrt-app-cli 还在维护吗?

最新版本 0.62.1 发布于 2026/11/17(今天);至今共发布 366 个版本,其中过去 12 个月发布了 366 个;首次发布于 2026/06/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。