Skip to content

Route projections: let one operation drive MCP + idiomatic CLI without duplicate route modules #596

Closed

Description

@ScriptedAlchemy

Problem

ScriptedAlchemy/cargo-hauler implements the same logical operations twice: once under src/mcp/hauler/tools/* and again under src/cli/*.

Examples:

  • hauler_request.tsx and cli/request.tsx both call submitTicketRequest(...) and render RequestDocument;
  • hauler_status.tsx and cli/status.tsx both call loadStatusResult(...) and render StatusDocument;
  • similar pairs exist for await/result/kill/last/log.

This is not simply application duplication. The current automatic MCP-to-CLI projection is too rigid for a mature CLI:

  • CLI wants short command names (hauler request, not a generic server/tool path);
  • CLI wants positional argv (hauler request -- cargo check ...);
  • flag names may differ from protocol field names (lane -> laneKey, repeated ticket/status flags -> arrays);
  • CLI help/description/exit behavior can differ;
  • the underlying execution/result contract is still the same operation.

The result is one domain operation with two route modules that must remain semantically synchronized.

This conflicts with #592's "one application graph, many projections" model.

Direction

Introduce a first-class operation/route projection model where one canonical executable route can declare surface-specific projection metadata/adapters without duplicating execution logic.

Illustrative only:

export const config = defineTool({
  description: 'Submit a background cargo request',
  cli: {
    command: 'request',
    positionals: ['argv'],
    mapInput(cli) {
      return {
        ...cli,
        cwd: cli.cwd ?? process.cwd(),
        after: parseTicketList(cli.after ?? []),
      };
    },
  },
});

or a colocated projection module:

src/mcp/hauler/tools/request.tsx
src/mcp/hauler/tools/request.cli.ts

The exact authoring API is open. Architectural requirements:

  1. One canonical operation owns execution, result schema, domain errors, and rendered document.
  2. MCP projection owns protocol-facing name/metadata/annotations.
  3. CLI projection may customize command path, positional mapping, flag aliases, help text, defaults, and exit-code policy.
  4. Surface input adapters are typed from the canonical route input contract and compile into Application/Projection IR.
  5. Tests can invoke the canonical operation once and separately test each projection's argument mapping.

Important boundary

Do not force every MCP tool to become a CLI command. Projection remains opt-in.

Do not make CLI-specific transport concerns leak into MCP input schemas merely so automatic projection can work.

This should build on #593: the canonical route contract must be normalized once from shared schemas, then projections derive their own user-facing grammar.

Acceptance

  • A canonical tool/operation can expose an idiomatic routed CLI command without a second execution route module.
  • CLI can rename fields/flags and define positionals while mapping back to the canonical input type.
  • CLI can choose a short command path independent of MCP server/tool wire names.
  • Result schema/rendered document are shared.
  • Mutation/read-only annotations and host semantics remain MCP projection concerns.
  • Projection mapping is represented in Application/Projection IR and visible in Workbench/inspect.
  • cargo-hauler can collapse request/status/await/result/kill/last/log CLI+MCP pairs to one operation implementation each without degrading its CLI UX.

Consumer evidence

Activity

  1. added
    enhancement
    meta-framework
    on Sep 5, 2026
  2. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Design: one operation, one MCP surface projection, one opt-in CLI surface projection

    Posting before implementation, on top of #593 (#603): the canonical input is already a graph node — RouteContract (contract:<module>#<binding>, input, origin, routes) — that both an MCP tool and a CLI command reference. #596 removes the second route: the CLI grammar becomes a projection of the tool, not a module beside it.

    Vocabulary (aligned with #578 / #592)

    • Host projection — what targets select (claude / codex / cursor / portable), composed into one artifact root by feat(build): emit one composite plugin root; targets select host projections; remove the plugin target (#555 W1) #578. Unchanged here.
    • Surface projection — how one operation is exposed: MCP tool, CLI command. The code already names this axis surface (AgentInvocationKind = tool | event | cli | script | workbench, GeneratedExecutableSurface, CompiledCliSurface, CompiledMcpCliCommandSurface). The two axes are orthogonal: host × surface → artifact rows (the routed CLI bin/<name>.mjs is emitted once per composite root; AB4765/AB4766 unchanged).
    • Operation — the canonical executable route, identity tool:<server>/<tool>. A projection never changes it: CompiledCliCommand.routeId is the tool id, operationId at run time is the tool id, the surface is the kind.

    Authoring form: a colocated projection module, never a route

    src/mcp/hauler/tools/hauler_request.tsx      # the operation: config, inputSchema, resultSchema, default render
    src/mcp/hauler/tools/hauler_request.cli.ts   # its CLI surface projection (opt-in)
    
    // hauler_request.cli.ts
    import type { CliProjectionConfig } from 'agent-bundle/routes';   // bundle-safe entry (AB4837 rule applies)
    import type { z } from 'zod';
    import { parseTicketList } from '../../../client/parse.js';
    import type { inputSchema } from './hauler_request.js';           // `typeof` on a type-only import
    
    export const config = {
      command: ['request'],                                            // default when omitted: [tool]
      description: 'Submit a background cargo request and print its ticket: hauler request [--after cc-N] -- cargo check -p foo',
      positionals: ['argv'],                                           // trailing z.array = variadic, `--` passthrough as today
      flags: {
        after:   { description: 'Tickets that must finish first (repeatable, or comma-separated)' },
        cwd:     { description: 'Workspace directory (default: current directory)', required: false },  // legal only with mapInput
        host:    { description: 'Agent host name for attribution' },
        session: { description: 'Agent session id for attribution' },
      },
      confirm: false,                                                  // default: !(annotations.readOnlyHint === true), as the bulk projection
      exitCode: 'zero',                                                // 'zero' | 'result'; overrides ToolConfig.exitCode
    } satisfies CliProjectionConfig<typeof inputSchema>;
    
    type CliInput = Omit<z.input<typeof inputSchema>, 'cwd' | 'after'> & { cwd?: string; after?: readonly string[] };
    export const mapInput = (input: CliInput): z.input<typeof inputSchema> => ({
      ...input,
      cwd: input.cwd ?? process.cwd(),
      ...(parseTicketList(input.after ?? []).length === 0 ? {} : { after: parseTicketList(input.after ?? []) }),
    });
    // hauler_status.cli.ts — renames only; no mapInput needed, the parser produces canonical keys
    export const config = {
      command: ['status'],
      description: 'Show the queue, in-flight cargo work, lanes, and admission state.',
      flags: {
        laneKey:  { name: 'lane',   description: 'Only requests in this lane key' },
        statuses: { name: 'status', description: 'Only these statuses (repeatable)' },
        tickets:  { name: 'ticket', description: 'Only these tickets (repeatable)' },
        limit:    { description: 'Recent rows to show' },
      },
    } satisfies CliProjectionConfig<typeof inputSchema>;

    Why this form and not the alternatives:

    Projection IR (routes/types.ts, additive)

    export interface CompiledCliOption {
      /* existing: key (canonical), option (CLI spelling), kind, choices, defaultValue, description, positional?, repeated, required */
      readonly aliases?: readonly string[];        // extra long-form --spellings (short -x flags: follow-up; the shell rejects single-dash tokens today)
    }
    export interface CompiledCliProjection {
      readonly mapInput: boolean;                  // the module exports a mapInput function the shell applies before inputSchema
      readonly module: string;                     // project-relative POSIX path (digest-safe)
      readonly relaxed?: readonly string[];        // canonical-required keys made optional on the CLI (flags.<key>.required: false or a CLI default)
    }
    export interface CompiledCliCommand {
      /* existing: aliases, description?, exitCode, mcp?: { confirm, server, tool }, options, path, render?, rendered, routeId */
      readonly projection?: CompiledCliProjection; // present for an explicit projection; absent for src/cli routes and the bulk mcpCommands projection
    }
    export interface CompiledCliSurface {
      /* existing */
      readonly projectionSources?: Readonly<Record<string, string>>; // routeId → absolute module path, build-side only, outside the digest identity
    }

    options is the mapping: { key: 'laneKey', option: 'lane' }, { key: 'tickets', option: 'ticket', repeated: true }, { key: 'argv', positional: 0, repeated: true }. It is produced by the same projectOptions/cliOptionFor policy as src/cli routes, from the tool's RouteContract.input, with a per-key override argument (name, aliases, description, default, required: false), so reserved names (help/json/ndjson/version, plus yes when confirm), kebab-case, and spelling collisions are checked on the final spellings. mcp: { server, tool, confirm } stays as provenance. inspect --routes dumps the graph, so cli.commands[].projection and options[].aliases appear with no renderer change; the route manifest (RouteManifestCliCommand.projection, RouteManifestCliOption.aliases) and the Workbench strict decoder mirror them in the same PR; the Workbench CLI row shows the projection module, mapInput: yes/no, the key ↔ option table, positionals, and aliases beside the (canonical) input editor. #592's manifest v2 reserves exactly routes.cli.commands[].projection; the name is kept.

    Rules: path = config.command ?? [tool] (every segment safeIdentitySegment; collisions through the existing AB4813 pass with a variant recovery naming the projection module); a tool with an explicit projection is removed from the bulk mcpCommands eligible set (one command per operation; an include pattern matching only such tools is AB4822 naming the module); exitCode in the projection wins over ToolConfig.exitCode; render is not accepted on the projection (the budget is the operation's, inherited); confirm defaults to the MCP-annotation rule and may be overridden explicitly — never inferred the other way.

    Runtime: one insertion point

    The generated CLI bin (build/entry-shell.ts generatedCliBinEntrySource, emitted as both dist/bin/<name>.js and the artifact bin/<name>.mjs) imports each projection module beside its route module and applies, in parseInput — the only place both the plain and rendered paths pass before validation:

    1. argv parsed with the projected grammar (parseCommandArgv, unchanged) → canonical keys;
    2. --yes checked and stripped when mcp.confirm;
    3. projection literal defaults filled for absent keys;
    4. mapInput(parsed) if present — synchronous in v1 (render returns a session synchronously); a throw is a CliInputError (exit 2);
    5. the canonical inputSchema.parse(mapped) — the zod boundary is unchanged, issues are spelled --<option> through option.key → option.option;
    6. the tool's component runs through the same rendered session as the generated MCP server, with invocation: { kind: 'cli', operationId: 'tool:hauler/hauler_request', surface: 'request' } (providers get { kind: 'cli', props: { args, command } }). Today the bulk projection runs the tool as kind: 'tool'; explicit projections use 'cli' so a route can pick its surface wording (agent().invocation.kind is the surface, operationId the operation — the literal reading of "projection is not identity"). Whether the bulk projection follows is a separate decision (behaviour change → minor); this PR leaves it.

    The projection module is bundled into the bin only (Rslib inlines every project module; autoExternal: false), never into the Flight worker or the MCP entry; it is judged by AB4837 like a layout. The test harness (agent-bundle/test invokeCli/render) loads the projection from projection.module and applies the same steps, pinned against the bin template.

    Diagnostics (new rows in docs/diagnostics.md; codes confirmed free on main)

    Code Severity Trigger
    AB4840 error A <name>.cli.{ts,tsx} module under src/mcp/<server>/tools/ has no sibling tool route <name>.{ts,tsx} (orphan), or a .cli.* module sits under resources/, prompts/, or apps/. Recovery: rename to match the tool, or prefix _ to park it. The suffix is reserved under src/mcp/** only.
    AB4841 error Projection module contract: config missing or outside the static grammar (wraps the AB4805/AB4806 reason with the module's label), a key outside the closed set (command, description, positionals, flags, aliases, confirm, exitCode), mapInput exported but not statically a function, or flags.<key>.required: false / default without mapInput where the canonical schema requires the key.
    AB4842 error Grammar binding: flags/positionals name a key not in the tool's contract; a name/alias is not kebab-case, is reserved, or collides with another option's spelling; a command segment is not a safe identity segment.

    A tool whose inputSchema has no static contract (out of the bounded grammar, or an unresolvable reference) becomes load-bearing once it has a projection: AB4814/AB4838/AB4839 fire on the tool module with the wording relabelled ("tool route … with a CLI projection"), exactly as for a src/cli route — never a silently missing command. Severity: all errors; a projection that cannot compile has no correct partial output.

    Not forced, not leaked

    No projection module → no command (the bulk mcpCommands opt-in keeps working as today for the rest). The MCP input schema, tools/list, annotations, and _meta are untouched by any projection field; ToolConfig gains nothing.

    Tests

    Unit: projection-module extraction (pairing, orphan AB4840, contract AB4841, binding AB4842, exclusion from the tool glob and from the bulk projection, projection/options mapping, digest stability with relative module paths). Canonical-once: the operation is invoked once through invokeMcpTool and once through the projected command (projection/cli-dispatch-mcp.test.ts already pins structured equality for the bulk projection; extend with a harness tool + .cli.ts), asserting the same structured result; each mapping (lane → laneKey, repeated --ticket → tickets[], positional argv, mapInput deriving cwd, --yes stripping, mapInput throw → exit 2) tested separately against the bin and the harness. Integration (cli-routes-build.test.ts): a temp project with src/mcp/demo/tools/submit.tsx + submit.cli.ts builds, --help shows the short path and renamed flags, argv round-trips, inspect --routes shows projection. Docs en + zh (package-entries.mdx "Project one tool as an idiomatic command", mcp.mdx, project-structure.mdx, workbench.mdx, reference/configuration.mdx), docs/entry-conventions.md, docs/diagnostics.md. Changeset: minor — reserving .cli.{ts,tsx} under src/mcp/** changes the meaning of a tool file that is legal today.

    Consumer proof

    Same dry-run harness as #603: scratch copy of cargo-hauler, packed tarballs, add hauler_request.cli.ts + hauler_status.cli.ts as above, delete src/cli/request.tsx and src/cli/status.tsx, and show inspect --routes (two commands with projection, routeId = the tool ids, no cli:request/cli:status routes), hauler request --help / hauler status --help with the pinned spellings (--lane, --ticket, --status, --after, -- cargo …), and status --json equal to the MCP tool's structured result.

    Deferred

    Short -x aliases (the shell's single-dash rule), async mapInput, aligning the bulk mcpCommands projection to invocation.kind: 'cli', deprecating ToolConfig.exitCode, CLI projections for resources/prompts, a view-adapter API for surface-specific rendering (routes branch on agent().invocation.kind).

  3. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Landed in efdec6b.

  4. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Landed in #616, squash-merged to main as efdec6b (docs: website/docs/{en,zh}/guide/authoring/package-entries.mdx; diagnostics AB4843–AB4845; changeset 596-cli-surface-projection, minor for reserving *.cli.{ts,tsx}). Projection details stay in the route manifest (cli.commands[].projection) and inspect --routes; surfacing them in the Workbench selected-operation inspector is #600's. Follow-ups: #604 absorbs the manifest fields into v2; #632 covers the e2e heading-locator flake seen on this PR's CI.

  5. ScriptedAlchemy commented on Sep 5, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Tracker reconciliation (owner audit 2026-09-05 17:11 UTC): implemented; the old yes-stripping and diagnostic-collision findings are obsolete — main strips yes only for confirming projections; codes are AB4843–AB4845. Landed as #616 (efdec6bc0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementmeta-framework

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions