Repository navigation
Description
Problem
ScriptedAlchemy/cargo-hauler implements the same logical operations twice: once under src/mcp/hauler/tools/* and again under src/cli/*.
Examples:
hauler_request.tsxandcli/request.tsxboth callsubmitTicketRequest(...)and renderRequestDocument;hauler_status.tsxandcli/status.tsxboth callloadStatusResult(...)and renderStatusDocument;- 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:
- One canonical operation owns execution, result schema, domain errors, and rendered document.
- MCP projection owns protocol-facing name/metadata/annotations.
- CLI projection may customize command path, positional mapping, flag aliases, help text, defaults, and exit-code policy.
- Surface input adapters are typed from the canonical route input contract and compile into Application/Projection IR.
- 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
ScriptedAlchemy/cargo-hauler/src/cli/request.tsxScriptedAlchemy/cargo-hauler/src/mcp/hauler/tools/hauler_request.tsxScriptedAlchemy/cargo-hauler/src/cli/status.tsxScriptedAlchemy/cargo-hauler/src/mcp/hauler/tools/hauler_status.tsx- Meta-framework architecture: one application graph, capability-driven projections, one execution kernel #592
- Application IR: resolve local schema imports so one route contract can drive MCP, CLI argv, Apps, and generated types #593
Activity
ScriptedAlchemy commentedon Sep 5, 2026
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)
targetsselect (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(AgentInvocationKind = tool | event | cli | script | workbench,GeneratedExecutableSurface,CompiledCliSurface,CompiledMcpCliCommandSurface). The two axes are orthogonal: host × surface → artifact rows (the routed CLIbin/<name>.mjsis emitted once per composite root;AB4765/AB4766unchanged).tool:<server>/<tool>. A projection never changes it:CompiledCliCommand.routeIdis the tool id,operationIdat run time is the tool id, the surface is the kind.Authoring form: a colocated projection module, never a route
Why this form and not the alternatives:
cliblock inside the tool'sconfig—configis the MCP projection's metadata and ships verbatim into the generated server's route table; a function-valuedmapInputisAB4806(dynamic) and would reject the whole config, taking the tool's MCP description with it. CLI transport concerns would live in the MCP module and its Flight worker bundle. Rejected.src/cli/<name>.tsre-exporting the tool — with Application IR: resolve local schema imports so one route contract can drive MCP, CLI argv, Apps, and generated types #593 it binds the same contract, but it is a second route (cli:<name>, secondoperationId, second typegen entry) and cannot rename flags or relaxrequiredwithout a second schema — the duplication Route projections: let one operation drive MCP + idiomatic CLI without duplicate route modules #596 exists to remove. Migration stop-gap only.<tool>.cli.{ts,tsx}—configis read by the unchanged static grammar (config-extract.ts: literals, string consts through the Application IR: resolve local schema imports so one route contract can drive MCP, CLI argv, Apps, and generated types #593 resolver;satisfiesunwraps for free);mapInputis an ordinary named export whose presence is recorded statically (scanRouteModuleExports().namedFunctions) and loaded only by the CLI bin; the MCP worker never sees the module. Discovery:src/mcp/*/tools/*.cli.{ts,tsx}is excluded from route classification before id derivation (today it would become the broken tooltool:hauler/hauler_request.cli, failingAB4810) and paired with<stem>.{ts,tsx};_-prefixed parks it as today.Projection IR (
routes/types.ts, additive)optionsis the mapping:{ key: 'laneKey', option: 'lane' },{ key: 'tickets', option: 'ticket', repeated: true },{ key: 'argv', positional: 0, repeated: true }. It is produced by the sameprojectOptions/cliOptionForpolicy assrc/cliroutes, from the tool'sRouteContract.input, with a per-key override argument (name,aliases,description,default,required: false), so reserved names (help/json/ndjson/version, plusyeswhenconfirm), kebab-case, and spelling collisions are checked on the final spellings.mcp: { server, tool, confirm }stays as provenance.inspect --routesdumps the graph, socli.commands[].projectionandoptions[].aliasesappear 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 exactlyroutes.cli.commands[].projection; the name is kept.Rules:
path = config.command ?? [tool](every segmentsafeIdentitySegment; collisions through the existingAB4813pass with a variant recovery naming the projection module); a tool with an explicit projection is removed from the bulkmcpCommandseligible set (one command per operation; anincludepattern matching only such tools isAB4822naming the module);exitCodein the projection wins overToolConfig.exitCode;renderis not accepted on the projection (the budget is the operation's, inherited);confirmdefaults 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.tsgeneratedCliBinEntrySource, emitted as bothdist/bin/<name>.jsand the artifactbin/<name>.mjs) imports each projection module beside its route module and applies, inparseInput— the only place both the plain and rendered paths pass before validation:parseCommandArgv, unchanged) → canonical keys;--yeschecked and stripped whenmcp.confirm;defaults filled for absent keys;mapInput(parsed)if present — synchronous in v1 (renderreturns a session synchronously); a throw is aCliInputError(exit 2);inputSchema.parse(mapped)— the zod boundary is unchanged, issues are spelled--<option>throughoption.key → option.option;invocation: { kind: 'cli', operationId: 'tool:hauler/hauler_request', surface: 'request' }(providers get{ kind: 'cli', props: { args, command } }). Today the bulk projection runs the tool askind: 'tool'; explicit projections use'cli'so a route can pick its surface wording (agent().invocation.kindis the surface,operationIdthe 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 byAB4837like a layout. The test harness (agent-bundle/testinvokeCli/render) loads the projection fromprojection.moduleand applies the same steps, pinned against the bin template.Diagnostics (new rows in
docs/diagnostics.md; codes confirmed free onmain)AB4840<name>.cli.{ts,tsx}module undersrc/mcp/<server>/tools/has no sibling tool route<name>.{ts,tsx}(orphan), or a.cli.*module sits underresources/,prompts/, orapps/. Recovery: rename to match the tool, or prefix_to park it. The suffix is reserved undersrc/mcp/**only.AB4841configmissing or outside the static grammar (wraps theAB4805/AB4806reason with the module's label), a key outside the closed set (command,description,positionals,flags,aliases,confirm,exitCode),mapInputexported but not statically a function, orflags.<key>.required: false/defaultwithoutmapInputwhere the canonical schema requires the key.AB4842flags/positionalsname a key not in the tool's contract; aname/alias is not kebab-case, is reserved, or collides with another option's spelling; acommandsegment is not a safe identity segment.A tool whose
inputSchemahas no static contract (out of the bounded grammar, or an unresolvable reference) becomes load-bearing once it has a projection:AB4814/AB4838/AB4839fire on the tool module with the wording relabelled ("tool route … with a CLI projection"), exactly as for asrc/cliroute — 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
mcpCommandsopt-in keeps working as today for the rest). The MCP input schema,tools/list, annotations, and_metaare untouched by any projection field;ToolConfiggains nothing.Tests
Unit: projection-module extraction (pairing, orphan
AB4840, contractAB4841, bindingAB4842, exclusion from the tool glob and from the bulk projection,projection/optionsmapping, digest stability with relative module paths). Canonical-once: the operation is invoked once throughinvokeMcpTooland once through the projected command (projection/cli-dispatch-mcp.test.tsalready 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[], positionalargv,mapInputderivingcwd,--yesstripping,mapInputthrow → exit 2) tested separately against the bin and the harness. Integration (cli-routes-build.test.ts): a temp project withsrc/mcp/demo/tools/submit.tsx+submit.cli.tsbuilds,--helpshows the short path and renamed flags, argv round-trips,inspect --routesshowsprojection. 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}undersrc/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.tsas above, deletesrc/cli/request.tsxandsrc/cli/status.tsx, and showinspect --routes(two commands withprojection,routeId= the tool ids, nocli:request/cli:statusroutes),hauler request --help/hauler status --helpwith the pinned spellings (--lane,--ticket,--status,--after,-- cargo …), andstatus --jsonequal to the MCP tool's structured result.Deferred
Short
-xaliases (the shell's single-dash rule), asyncmapInput, aligning the bulkmcpCommandsprojection toinvocation.kind: 'cli', deprecatingToolConfig.exitCode, CLI projections for resources/prompts, a view-adapter API for surface-specific rendering (routes branch onagent().invocation.kind).fix(diagnostics): reallocate event preflight codes to AB4850/AB4851
feat(routes): CLI surface projections of MCP tools — colocated <tool>…
ScriptedAlchemy commentedon Sep 5, 2026
Landed in efdec6b.
ScriptedAlchemy commentedon Sep 5, 2026
Landed in #616, squash-merged to
mainas efdec6b (docs:website/docs/{en,zh}/guide/authoring/package-entries.mdx; diagnostics AB4843–AB4845; changeset596-cli-surface-projection,minorfor reserving*.cli.{ts,tsx}). Projection details stay in the route manifest (cli.commands[].projection) andinspect --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.ScriptedAlchemy commentedon Sep 5, 2026
Tracker reconciliation (owner audit 2026-09-05 17:11 UTC): implemented; the old
yes-stripping and diagnostic-collision findings are obsolete — main stripsyesonly for confirming projections; codes are AB4843–AB4845. Landed as #616 (efdec6bc0).