Repository navigation
feat(mcpx): adapter import generates declarations from completions, man and --help (#1962) - #9161
Conversation
…an and --help (#1962) Implements #1962 steps 2-5 (the #2118 gate closed with PR #4637, so the refusal at adapter.go is stale). Source ladder, best evidence first: completion scripts (fish/zsh/bash parsers; system completion dirs, then the binary completion <shell> probe; --completion FILE parses a script directly), then the man page OPTIONS section, then --help with one level of subcommand recursion. Generated declarations carry provenance (source, source detail, resolved binary path, version token, date) in a new Spec.Provenance field, and adapter check now reports version drift in the form the issue promised. Sources that parse to nothing are clear errors, never partial declarations; --bare is untouched. Tests: 11 new deterministic parser/spec tests naming hand-written shapes as oracle, version extraction and drift against a fake binary, and a loadAdapterFiles round-trip. Verified live: import git (man source, 23 global flags) passes adapter check and a hand-drifted copy fails it with the drift message; importing the mcpx binary itself via its fish completion probe yields 77 tools.
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 2 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 10de70e1a3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for _, shell := range []string{"fish", "zsh", "bash"} { | ||
| out, err := runCapture(binary, "completion", shell) |
There was a problem hiding this comment.
Gate completion probes on confirmed command support
When no installed completion file is found, importing an arbitrary binary executes it with ordinary positional arguments before trying man or help. For example, mcpx adapter import rm runs rm completion fish in the caller's working directory; rm --help documents rm [OPTION]... [FILE]... and “Remove (unlink) the FILE(s).”, so existing files named completion or fish are deleted merely by importing the adapter. Only invoke this probe after establishing that the binary supports a non-mutating completion command, or make execution of unverified probes explicitly opt-in.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in commit 07cacdd — agreed, this was the dangerous one. In auto mode the completion probe now runs only when the binary advertises a completion subcommand in its own --help (the cobra/clap convention); system completion files are still read without executing anything, and an explicit --source completion remains the caller's opt-in to probe anyway. Regression test TestAutoImportNeverProbesAnUnadvertisedBinary imports a fake mutating binary with an invocation log and asserts it was never called with completion-shaped arguments (the import falls through to help); TestAutoImportProbesAnAdvertisedCompletion covers the advertised case.
| Args: []string{sub.Name}, | ||
| Params: flagParams(sub.Flags), |
There was a problem hiding this comment.
Preserve positional input on generated subcommand tools
For an imported program whose subcommand requires positional operands, the generated tool has no way to supply them: this branch emits only flag parameters, while the positional args catch-all exists only in the single-tool branch. ToolSpec.buildArgs rejects every undeclared argument, and helpShape also discards the positionals parsed from subcommand help, so these imports validate successfully but cannot perform operations such as toolbox add ITEM. Preserve parsed subcommand positionals or expose a positional array on each generated subcommand tool.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in commit 07cacdd. Subcommand help positionals are now kept through the recursion (importSub.Positionals), emitted as required params on the subcommand tool, and every subcommand tool also carries the trailing args array catch-all like the single-tool branch — so a generated toolbox add tool can actually be called with its item. Regression test TestHelpImportPreservesSubcommandPositionals drives a fake binary through buildGeneratedImport and checks the force/item/args params.
| if i := strings.IndexAny(name, "=["); i >= 0 { | ||
| f.Long = name[:i] | ||
| f.Value = strings.Trim(name[i:], "=[]<>") | ||
| f.TakesValue = true |
There was a problem hiding this comment.
Preserve equals-only binding for optional flag values
For options written as --flag[=<value>], stripping the binding syntax produces a parameter that cannot be rendered correctly: ToolSpec.buildArgs always emits the flag and value as separate argv entries. The existing man fixture includes --exec-path[=<path>], and git --help confirms that exact syntax; its generated exec_path parameter therefore renders as git --exec-path /tmp, which prints the existing executable path instead of setting it to /tmp. Preserve attached-value semantics through generation and rendering, or explicitly reject unsupported options instead of exposing a parameter that silently performs a different operation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in commit 07cacdd, by preservation rather than rejection. The bracketed form is now recorded at parse time (importFlag.EqualsOnly), carried onto a new Param.Equals field, and buildArgs renders equals-bound values attached (flag=value, including the Repeat case) — so the generated git declaration's exec_path parameter now sets the path instead of printing it. Regression tests TestBracketedValueBindsEqualsOnly (parse and param) and TestBuildArgsEqualsRendering / TestBuildArgsEqualsRepeat (argv oracle) in internal/adapter.
| if len(words) == 0 { | ||
| return "" | ||
| } | ||
| return words[0] |
There was a problem hiding this comment.
Apply fish flag conditions to every listed command
When a fish completion condition lists multiple command spellings, returning only its first word silently drops the flag from every other spelling. This affects the repository's own generated completions: fishCompletion in completion.go:155–175 declares tools for every alias and groups their flag conditions using strings.Join(spellings(c), " "); completion_test.go:168–188 explicitly verifies that those conditions cover every alias. Importing that completion consequently exposes alias tools without their supported flag parameters, and ToolSpec.buildArgs rejects attempts to supply them. Associate each flag with every command listed in the condition rather than treating the list as a nested command path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in commit 07cacdd. fishSubcommandsOf now returns every word listed after __fish_seen_subcommand_from and the flag is added to each listed spelling's tool — which, as you note, is exactly the shape mcpx's own generated fish completions use for aliases. Regression test TestFishConditionAppliesToEverySpelling.
| GeneratedAt: time.Now().UTC().Format(time.RFC3339), | ||
| Generator: "mcpx adapter import", | ||
| } | ||
| spec, notes, err := shapeToSpec(name, binary, shape, prov) |
There was a problem hiding this comment.
Make relative executable paths absolute before emitting them
When importing a binary through a relative path such as ./bin/tool, this call stores that relative path unchanged as Spec.Command. Loading the generated declaration from another working directory then makes Spec.command() resolve it against the adapter process's directory, so the adapter either fails to find the imported binary or executes a different file at the same relative location. Recording BinaryPath in provenance does not help because the execution path never consults it. Apply the same absolute-path normalization already used by buildBareImport before passing the command to shapeToSpec.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in commit 07cacdd. buildGeneratedImport now applies buildBareImport's rule: a path-like binary is stored absolute in Spec.Command (the resolved BinaryPath in provenance was already absolute but, as you say, the execution path never consulted it). Regression test TestRelativeBinaryPathIsStoredAbsolute imports ./bin/tool and requires the absolute command.
…nding in adapter import (#1962) Codex review of PR #9161, all five findings: (P1) auto import no longer probes completion <shell> blindly — running rm completion fish would delete files named completion/fish; the probe now requires the binary to advertise a completion subcommand in its own --help, with explicit --source completion as the opt-in. (P2) Subcommand tools gain their parsed positionals plus the args catch-all, so toolbox add ITEM is callable. (P2) The bracketed optional-value form --flag[=<value>] is preserved as the new Param.Equals and rendered attached by buildArgs; git --exec-path separated would print instead of set. (P2) Fish conditions bind a flag to every listed command spelling, not just the first (mcpx own completions join aliases that way). (P2) Path-like binaries are stored absolute, matching buildBareImport. Regression tests for each, incl. fake-binary probe-gating with an invocation log.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 07cacdd5b9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| params = append(params, adapter.Param{ | ||
| Name: "args", | ||
| Type: "array", | ||
| Description: "Additional positional arguments, passed in order.", |
There was a problem hiding this comment.
Reserve a unique name for the positional catch-all
When imported help declares a positional named args or a flag named --args, the generated parameters already contain an args entry before this catch-all is appended. Spec.Validate() accepts duplicate parameter names, Schema() overwrites the earlier schema, and buildArgs() renders both entries from the same input. Consequently, positional operands are passed twice, or a flag value also becomes an unintended trailing operand. This affects both generation branches; choose a catch-all name that does not collide with parsed parameters, or reuse an existing variadic positional.
Useful? React with 👍 / 👎.
| Name: pos.Long, | ||
| Description: pos.Desc, | ||
| Type: "string", | ||
| Required: true, |
There was a problem hiding this comment.
Preserve optionality of parsed positional operands
For help describing optional positional operands, marking every parsed positional as required prevents valid invocations. For example, argparse's add_argument('item', nargs='?', default='default-item') produces usage containing [item] and an ordinary item row under positional arguments:. The parser retains that row without its optionality, and this declaration makes buildArgs() reject calls omitting item, even though the binary accepts them and uses its default. Preserve usage-derived optionality, or avoid requiring operands whose required status has not been established; the subcommand branch has the same problem.
Useful? React with 👍 / 👎.
| name := o.name | ||
| if name == "" { | ||
| name = adapterName(completionName(base, shell)) |
There was a problem hiding this comment.
Keep the completion command separate from the adapter name
For a completion file whose program name contains a dot, such as toolbox.v2.fish, this normalization changes the name to toolbox-v2 before it is passed to parseCompletion(). parseFishCompletion() then discards every complete -c toolbox.v2 ... line because its command filter compares against the normalized name, so a valid completion file fails import as empty. For bash and zsh, generation instead stores the normalized name as the executable command. Retain the original program name for parsing and execution, and sanitize only the adapter namespace.
Useful? React with 👍 / 👎.
| case (kind == "commands" || kind == "subcommands" || kind == "cmds") && !strings.HasPrefix(w, "-"): | ||
| if w != "help" && !seenSub[w] { | ||
| seenSub[w] = true | ||
| shape.Subs = append(shape.Subs, importSub{Name: w}) |
There was a problem hiding this comment.
Preserve command context when extracting bash subcommands
When a bash completion contains command lists inside nested-command handlers, this branch promotes every list to top-level tools. In the installed /usr/share/bash-completion/completions/git:1448–1453, _git_bisect() declares local subcommands="start bad good skip reset visualize replay log run"; the parser therefore generates a start tool whose fixed arguments are just ["start"], omitting bisect. The inspected git start --help confirms the result: "'start' is not a git command." Because this nonempty completion wins the source ladder, ordinary Git imports can emit unusable tools instead of falling back to another source. Preserve the enclosing command path or reject lists whose context cannot be established.
Useful? React with 👍 / 👎.
| } else if c == '\\' && quote == '"' && i+1 < len(line) { | ||
| i++ | ||
| cur.WriteByte(line[i]) |
There was a problem hiding this comment.
Honor escaped apostrophes inside fish single quotes
When a fish description contains an escaped apostrophe, ignoring escapes inside single quotes can consume the option metadata following the description. The installed /usr/share/fish/completions/fd.fish:15 describes --ignore-file using 'Add a custom ignore-file in \'.gitignore\' format' -r -F; this tokenizer incorrectly closes and reopens quotes, swallowing -r -F into the description. The resulting parameter is boolean and renders only --ignore-file, whereas the inspected fdfind --help explicitly documents --ignore-file <path>. Handle fish's escaped apostrophes and backslashes inside single-quoted strings so required-value markers remain separate tokens.
Useful? React with 👍 / 👎.
| if v := strings.ToLower(f.Value); strings.Contains(v, "int") || strings.Contains(v, "num") || strings.Contains(v, "count") { | ||
| p.Type = "integer" |
There was a problem hiding this comment.
Infer integer types from complete placeholders, not substrings
For string-valued options whose placeholders happen to contain int, this heuristic generates an integer-only schema. For example, inspected argparse help for add_argument('--endpoint') prints --endpoint ENDPOINT, and argparse accepts a URL as its value, but ENDPOINT contains int and therefore produces an integer parameter here. ToolSpec.Schema() publishes that incorrect type, and mcpclient.validateToolArgs() rejects a valid string endpoint before invoking the adapter; generated TypeScript clients also expose it as a number. Match explicit numeric type names rather than arbitrary substrings, retaining string as the fallback when the source does not establish a numeric type.
Useful? React with 👍 / 👎.
|
Salvage note — duplicate PR #9041 diffed against this merged PR (task 15313, lane code-b, 2026-11-13) Per the fleet duplicate-PR protocol: PR #9161 (this PR, merged as 2a2cc1d) is canonical for task 15313 / issue #1962. PR #9041 (branch
Everything else in PR #9041 (source ladder, completion/man/help parsers, provenance + drift reporting, |
Implements the remaining half of #1962 (steps 2-5): mcpx adapter import now generates declarations instead of refusing everything that is not --bare. The #2118 declaration-format gate is closed and PR #4637 merged, so the refusal was stale.
What landed
Source ladder (the issue's Approach C order — best evidence first), all deterministic, no model in the loop:
A source that parses to nothing is a clear error naming what was tried, never a partial declaration. Global flags of a subcommand-ful binary are reported as an import note rather than folded into subcommand tools, where they would render in the wrong position (git status --git-dir is not a thing).
Provenance + drift — generated declarations record provenance (source, source detail, resolved binary path, version token from --version, generation date, generator) via a new Spec.Provenance field that the run path never consults. adapter check now reports drift in the form #83 asked for: "git: this declaration was written against git 9.9.9, found 2.56.0".
Untouched: --bare semantics and its loud warning; loadAdapters validation/dedup (generated declarations load through it unchanged — covered by a round-trip test).
Tests (oracles are hand-written shapes/fixtures)
Verified live
#1962 stays open: this PR satisfies the generation/provenance/drift acceptance criteria; the issue's open questions (re-import merge semantics) and the docs sentence about argv-escape binaries remain.