Import mcp-to-cli from the rhema workspace
ci / checks (push) Failing after 14s

The crate maps MCP tool catalogs to clap commands and back, and has no
rhema dependencies — it was in-tree only because the workspace glob
reached it. Its own repository gives it its own release cadence and
its own crates.io token, scoped to this crate alone.
This commit is contained in:
vhaudiquet committed 2026-11-12 12:20:25 +01:00
commit a7e1de76ac
24 files changed
+3817

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
//! Shared helpers for the mapping matrix: argv driving and payload
//! unwrapping.
use mcp_to_cli::{Payload, ToolInfo, args};
/// A [`ToolInfo`] from parts, for inline schemas.
pub fn tool(name: &str, description: &str, input_schema: serde_json::Value) -> ToolInfo {
ToolInfo {
name: name.to_owned(),
description: description.to_owned(),
input_schema,
}
}
/// Parses `argv` (no program name) against `cmd`; `None` is clap
/// rejecting the argv — the usage-error path.
pub fn parse(cmd: &clap::Command, argv: &[&str]) -> Option<clap::ArgMatches> {
let mut full: Vec<String> = vec!["srv".to_owned()];
full.extend(argv.iter().map(|a| (*a).to_owned()));
cmd.clone().try_get_matches_from(full).ok()
}
/// Parses clap-valid `argv` and maps the matched tool.
pub fn run(
cmd: &clap::Command,
argv: &[&str],
) -> Result<mcp_to_cli::Payload, mcp_to_cli::MappingError> {
let matches = parse(cmd, argv).expect("argv parses");
args(cmd, &matches)
}
/// The mapped object of a payload that must be mapped.
pub fn mapped(payload: Payload) -> serde_json::Value {
match payload {
Payload::Mapped(value) => value,
other => panic!("expected a mapped payload, got {other:?}"),
}
}
/// The raw string of a payload that must be the `--json` override.
pub fn overridden(payload: Payload) -> String {
match payload {
Payload::Overridden(raw) => raw,
other => panic!("expected an overridden payload, got {other:?}"),
}
}
+40
View File
@@ -0,0 +1,40 @@
# Fixtures
Trimmed `inputSchema` objects from real MCP servers, plus two
hand-written stand-ins, so the mapping matrix runs against real shapes.
All upstream work is MIT-licensed.
## Vendored from github/github-mcp-server
Source: <https://github.com/github/github-mcp-server>, MIT license,
`main @ 4bcdcdf8d7be`, fetched 2026-11-03. The files carry the
`inputSchema` object of the named tool, verbatim:
- `create_pull_request.json` — flat scalars, optional booleans, an
array of strings.
- `search_repositories.json` — a boolean with `default: true`
(`minimal_output`), string `enum`s (`sort`, `order`), constraint
keywords (`minimum`, `maximum`) the mapping ignores.
- `update_pull_request.json` — the `state: ["open", "closed"]` enum.
- `create_issue.json` — flat required scalars, with `x-mcp-header`
extension keys the mapping ignores.
- `projects_write_excerpt.json` — hand-trimmed from the 26-property
`projects_write` tool: `iterations` (array of objects with per-item
`required`) and `updated_field` (a `oneOf` of object variants) kept
verbatim, every other property dropped, `required` emptied because
both listed names (`method`, `owner`) were among the dropped.
## Hand-written stand-ins
Documented stand-ins for the other two servers named in the spec; the
shapes are trimmed from their actual tool definitions, not invented.
- `additional_fields.json` — the pydantic shape `sooperset/mcp-atlassian`
emits: required scalars, a `pattern` the mapping ignores, and
`additional_fields` as a three-variant `anyOf` (`object | string |
null`), which is the JSON-flag case, not the nullable case.
- `get_scene_info.json` — the FastMCP shape `ahujasid/blender-mcp`
emits for every optional parameter: `anyOf: [<T>, null]` nullable
forms (`user_prompt` with `default: ""`, `query`, `fields` as a
nullable array of strings, `limit` integer with `default: 20`) and a
required `code` string.
+20
View File
@@ -0,0 +1,20 @@
{
"type": "object",
"properties": {
"project_key": {
"type": "string",
"pattern": "[A-Z]+"
},
"summary": {
"type": "string"
},
"additional_fields": {
"anyOf": [
{ "type": "object" },
{ "type": "string" },
{ "type": "null" }
]
}
},
"required": ["project_key", "summary"]
}
+41
View File
@@ -0,0 +1,41 @@
{
"properties": {
"body": {
"description": "Issue body content (optional)",
"type": "string"
},
"owner": {
"description": "Repository owner (username or organization)",
"type": "string",
"x-mcp-header": "owner"
},
"parent_issue_number": {
"description": "Issue number of the parent issue. The new issue is created and attached to this parent in the same operation.",
"minimum": 1,
"type": "number"
},
"parent_owner": {
"description": "Repository owner of the parent issue. Must be provided with parent_repo. Omit both to use owner and repo. Only used when parent_issue_number is provided.",
"type": "string"
},
"parent_repo": {
"description": "Repository name of the parent issue. Must be provided with parent_owner. Omit both to use owner and repo. Only used when parent_issue_number is provided.",
"type": "string"
},
"repo": {
"description": "Repository name",
"type": "string",
"x-mcp-header": "repo"
},
"title": {
"description": "Issue title",
"type": "string"
}
},
"required": [
"owner",
"repo",
"title"
],
"type": "object"
}
+51
View File
@@ -0,0 +1,51 @@
{
"properties": {
"base": {
"description": "Branch to merge into",
"type": "string"
},
"body": {
"description": "PR description",
"type": "string"
},
"draft": {
"description": "Create as draft PR",
"type": "boolean"
},
"head": {
"description": "Branch containing changes",
"type": "string"
},
"maintainer_can_modify": {
"description": "Allow maintainer edits",
"type": "boolean"
},
"owner": {
"description": "Repository owner",
"type": "string"
},
"repo": {
"description": "Repository name",
"type": "string"
},
"reviewers": {
"description": "GitHub usernames or ORG/team-slug team reviewers to request reviews from",
"items": {
"type": "string"
},
"type": "array"
},
"title": {
"description": "PR title",
"type": "string"
}
},
"required": [
"owner",
"repo",
"title",
"head",
"base"
],
"type": "object"
}
+43
View File
@@ -0,0 +1,43 @@
{
"type": "object",
"properties": {
"code": {
"description": "Execute arbitrary Blender Python code",
"type": "string"
},
"user_prompt": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"default": "",
"description": "Optional natural-language prompt the operator can add"
},
"query": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "Optional substring to filter the reported objects"
},
"fields": {
"anyOf": [
{
"type": "array",
"items": { "type": "string" }
},
{ "type": "null" }
],
"description": "Optional list of fields to report per object"
},
"limit": {
"anyOf": [
{ "type": "integer" },
{ "type": "null" }
],
"default": 20,
"description": "Maximum number of objects to report"
}
},
"required": ["code"]
}
+73
View File
@@ -0,0 +1,73 @@
{
"type": "object",
"required": [],
"properties": {
"iterations": {
"description": "Custom iterations for 'create_iteration_field' method. Only set this when you need iterations with varying durations, breaks between them, or specific titles. Otherwise omit it: GitHub auto-creates three iterations of 'iteration_duration' days starting on 'start_date', which is the right choice for most cases.",
"items": {
"additionalProperties": false,
"properties": {
"duration": {
"description": "Duration in days",
"type": "number"
},
"start_date": {
"description": "Start date in YYYY-MM-DD format",
"type": "string"
},
"title": {
"description": "Iteration title (e.g. 'Sprint 1')",
"type": "string"
}
},
"required": [
"title",
"start_date",
"duration"
],
"type": "object"
},
"type": "array"
},
"updated_field": {
"description": "The field/value to apply, using {\"id\": 123, \"value\": ...} or {\"name\": \"Status\", \"value\": ...}; null clears the field. Required for 'update_project_item' and 'update_project_items', where one top-level field/value applies to every item in a batch. For 'update_project_item' SINGLE_SELECT fields, the name form accepts option names; the ID form expects an option ID.",
"oneOf": [
{
"additionalProperties": false,
"properties": {
"id": {
"description": "The numeric project field ID.",
"type": "integer"
},
"value": {
"description": "The value to apply. Any JSON value is accepted; use null to clear the field."
}
},
"required": [
"id",
"value"
],
"type": "object"
},
{
"additionalProperties": false,
"properties": {
"name": {
"description": "The project field name. Matching is case-insensitive.",
"type": "string"
},
"value": {
"description": "The value to apply. Any JSON value is accepted; use null to clear the field."
}
},
"required": [
"name",
"value"
],
"type": "object"
}
],
"type": "object"
}
}
}
+46
View File
@@ -0,0 +1,46 @@
{
"properties": {
"minimal_output": {
"default": true,
"description": "Return minimal repository information (default: true). When false, modern clients receive additional curated repository details, not the complete GitHub API object. Legacy clients retain full GitHub API repository objects.",
"type": "boolean"
},
"order": {
"description": "Sort order",
"enum": [
"asc",
"desc"
],
"type": "string"
},
"page": {
"description": "Page number for pagination (min 1)",
"minimum": 1,
"type": "number"
},
"perPage": {
"description": "Results per page for pagination (min 1, max 100)",
"maximum": 100,
"minimum": 1,
"type": "number"
},
"query": {
"description": "Repository search query. Examples: 'machine learning in:name stars:>1000 language:python', 'topic:react', 'user:facebook'. Supports advanced search syntax for precise filtering.",
"type": "string"
},
"sort": {
"description": "Sort repositories by field, defaults to best match",
"enum": [
"stars",
"forks",
"help-wanted-issues",
"updated"
],
"type": "string"
}
},
"required": [
"query"
],
"type": "object"
}
+57
View File
@@ -0,0 +1,57 @@
{
"properties": {
"base": {
"description": "New base branch name",
"type": "string"
},
"body": {
"description": "New description",
"type": "string"
},
"draft": {
"description": "Mark pull request as draft (true) or ready for review (false)",
"type": "boolean"
},
"maintainer_can_modify": {
"description": "Allow maintainer edits",
"type": "boolean"
},
"owner": {
"description": "Repository owner",
"type": "string"
},
"pullNumber": {
"description": "Pull request number to update",
"type": "number"
},
"repo": {
"description": "Repository name",
"type": "string"
},
"reviewers": {
"description": "GitHub usernames or ORG/team-slug team reviewers to request reviews from",
"items": {
"type": "string"
},
"type": "array"
},
"state": {
"description": "New state",
"enum": [
"open",
"closed"
],
"type": "string"
},
"title": {
"description": "New title",
"type": "string"
}
},
"required": [
"owner",
"repo",
"pullNumber"
],
"type": "object"
}
+1047
View File
File diff suppressed because it is too large. Load diff
+424
View File
@@ -0,0 +1,424 @@
//! The mapping matrix against vendored real schemas: github's
//! github-mcp-server, an Atlassian-shaped stand-in, and a
//! FastMCP-shaped stand-in. See tests/fixtures/README.md.
mod common;
use clap::Command;
use common::{mapped, overridden, parse, run, tool};
use mcp_to_cli::{args, command};
use serde_json::json;
/// The vendored fixture `name`, its JSON as the wire format carried it.
fn fixture(name: &str) -> serde_json::Value {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures")
.join(name);
let raw = std::fs::read_to_string(&path).expect("fixture is readable");
serde_json::from_str(&raw).unwrap_or_else(|e| panic!("fixture {name} parses: {e}"))
}
fn catalog(names: &[&str]) -> Command {
let tools: Vec<mcp_to_cli::ToolInfo> = names
.iter()
.map(|name| {
tool(
name,
&format!("the {name} tool"),
fixture(&format!("{name}.json")),
)
})
.collect();
command("github", &tools)
}
#[test]
fn create_pull_request_is_the_worked_example() {
let cmd = catalog(&["create_pull_request"]);
// The spec's own example, flags verbatim.
let value = mapped(
run(
&cmd,
&[
"create_pull_request",
"--owner",
"acme",
"--repo",
"api",
"--title",
"Add /health",
"--head",
"feature/health",
"--base",
"main",
"--draft",
"--reviewers",
"alice",
"--reviewers",
"bob",
],
)
.unwrap(),
);
assert_eq!(
value,
json!({
"owner": "acme",
"repo": "api",
"title": "Add /health",
"head": "feature/health",
"base": "main",
"draft": true,
"reviewers": ["alice", "bob"],
})
);
}
#[test]
fn create_pull_request_omitted_optionals_stay_absent() {
let cmd = catalog(&["create_pull_request"]);
let value = mapped(
run(
&cmd,
&[
"create_pull_request",
"--owner",
"o",
"--repo",
"r",
"--title",
"t",
"--head",
"h",
"--base",
"b",
],
)
.unwrap(),
);
// draft, maintainer_can_modify, body, reviewers: all absent.
assert_eq!(
value,
json!({"owner": "o", "repo": "r", "title": "t", "head": "h", "base": "b"})
);
// And the required scalars are enforced.
assert!(parse(&cmd, &["create_pull_request", "--owner", "o"]).is_none());
}
#[test]
fn search_repositories_bool_default_true_takes_explicit_false() {
let cmd = catalog(&["search_repositories"]);
// The spec's example, verbatim.
let value = mapped(
run(
&cmd,
&[
"search_repositories",
"--query",
"org:acme",
"--minimal_output",
"false",
],
)
.unwrap(),
);
assert_eq!(value, json!({"query": "org:acme", "minimal_output": false}));
// Omitted, the key stays absent and the server applies its true.
let omitted = mapped(run(&cmd, &["search_repositories", "--query", "q"]).unwrap());
assert_eq!(omitted, json!({"query": "q"}));
}
#[test]
fn search_repositories_enums_validate() {
let cmd = catalog(&["search_repositories"]);
let value = mapped(
run(
&cmd,
&[
"search_repositories",
"--query",
"q",
"--sort",
"stars",
"--order",
"desc",
],
)
.unwrap(),
);
assert_eq!(value["sort"], "stars");
assert_eq!(value["order"], "desc");
assert!(
parse(
&cmd,
&[
"search_repositories",
"--query",
"q",
"--sort",
"stargazers"
]
)
.is_none()
);
assert!(
parse(
&cmd,
&["search_repositories", "--query", "q", "--order", "up"]
)
.is_none()
);
}
#[test]
fn search_repositories_numbers_and_ignored_constraints() {
let cmd = catalog(&["search_repositories"]);
// `perPage` rides camelCase verbatim; minimum/maximum are ignored.
let value = mapped(
run(
&cmd,
&[
"search_repositories",
"--query",
"q",
"--perPage",
"1000",
"--page",
"2",
],
)
.unwrap(),
);
assert_eq!(value["perPage"].as_f64(), Some(1000.0));
assert_eq!(value["page"].as_f64(), Some(2.0));
}
#[test]
fn update_pull_request_state_enum_and_number() {
let cmd = catalog(&["update_pull_request"]);
let value = mapped(
run(
&cmd,
&[
"update_pull_request",
"--owner",
"o",
"--repo",
"r",
"--pullNumber",
"7",
"--state",
"closed",
],
)
.unwrap(),
);
assert_eq!(value["state"], "closed");
// The usage line spells the mandatory flags out.
let mut rendered = cmd.clone();
let text = rendered
.find_subcommand_mut("update_pull_request")
.expect("subcommand")
.render_help()
.to_string();
assert!(
text.contains(
"Usage: github update_pull_request --owner <OWNER> --pullNumber <NUMBER> \
--repo <REPO> [OPTIONS]",
),
"{text}"
);
// `pullNumber` is a schema number: whole values keep the integer
// wire form strict parsers accept.
assert_eq!(value["pullNumber"].as_i64(), Some(7));
assert!(!value["pullNumber"].is_f64());
// draft is an optional boolean: presence flag.
assert!(parse(&cmd, &["update_pull_request", "--draft", "false"]).is_none());
}
#[test]
fn create_issue_maps_scalars_and_ignores_extensions() {
let cmd = catalog(&["create_issue"]);
let value = mapped(
run(
&cmd,
&[
"create_issue",
"--owner",
"o",
"--repo",
"r",
"--title",
"t",
"--body",
"b",
],
)
.unwrap(),
);
assert_eq!(
value,
json!({"owner": "o", "repo": "r", "title": "t", "body": "b"})
);
// parent_issue_number (number, minimum ignored) is optional.
let partial = mapped(
run(
&cmd,
&[
"create_issue",
"--owner",
"o",
"--repo",
"r",
"--title",
"t",
],
)
.unwrap(),
);
assert_eq!(partial, json!({"owner": "o", "repo": "r", "title": "t"}));
assert!(parse(&cmd, &["create_issue", "--owner", "o", "--repo", "r"]).is_none());
}
#[test]
fn projects_write_excerpt_maps_both_json_flags() {
let cmd = catalog(&["projects_write_excerpt"]);
let value = mapped(
run(
&cmd,
&[
"projects_write_excerpt",
"--iterations_json",
r#"[{"title": "Sprint 1", "start_date": "2026-01-01", "duration": 7}]"#,
"--updated_field_json",
r#"{"name": "Status", "value": "In Progress"}"#,
],
)
.unwrap(),
);
// Verbatim: the per-item required shape passes through untouched.
assert_eq!(
value,
json!({
"iterations": [
{"title": "Sprint 1", "start_date": "2026-01-01", "duration": 7},
],
"updated_field": {"name": "Status", "value": "In Progress"},
})
);
}
#[test]
fn atlassian_additional_fields_shape() {
let cmd = command(
"atlassian",
&[tool(
"create_issue",
"create an issue",
fixture("additional_fields.json"),
)],
);
// The pattern on project_key is ignored — the server validates.
let value = mapped(
run(
&cmd,
&[
"create_issue",
"--project_key",
"proj",
"--summary",
"Fix login",
"--additional_fields_json",
r#"{"priority": {"name": "High"}}"#,
],
)
.unwrap(),
);
assert_eq!(
value,
json!({
"project_key": "proj",
"summary": "Fix login",
"additional_fields": {"priority": {"name": "High"}},
})
);
// Required scalars are enforced.
assert!(parse(&cmd, &["create_issue", "--project_key", "PROJ"]).is_none());
// The three-variant anyOf is a JSON flag, not a nullable string.
assert!(parse(&cmd, &["create_issue", "--additional_fields", "x"]).is_none());
}
#[test]
fn fastmcp_get_scene_info_shape() {
let cmd = command(
"blender",
&[tool(
"get_scene_info",
"get scene info",
fixture("get_scene_info.json"),
)],
);
// The spec's example: nullable optionals map as plain flags.
let value = mapped(
run(
&cmd,
&[
"get_scene_info",
"--code",
"import bpy; print(bpy.context.scene.name)",
"--query",
"chair",
"--fields",
"location",
"--fields",
"topology",
"--limit",
"5",
],
)
.unwrap(),
);
assert_eq!(
value,
json!({
"code": "import bpy; print(bpy.context.scene.name)",
"query": "chair",
"fields": ["location", "topology"],
"limit": 5,
})
);
// Omitted optionals — user_prompt (default ""), limit (default 20)
// — stay absent; required code is enforced.
let minimal = mapped(run(&cmd, &["get_scene_info", "--code", "bpy"]).unwrap());
assert_eq!(minimal, json!({"code": "bpy"}));
assert!(parse(&cmd, &["get_scene_info"]).is_none());
}
#[test]
fn whole_catalog_round_trips_through_the_override() {
let cmd = catalog(&["create_issue", "create_pull_request"]);
assert_eq!(
overridden(run(&cmd, &["create_issue", "--json", r#"{"owner": "o"}"#]).unwrap()),
r#"{"owner": "o"}"#
);
// Every tool of the catalog also serves the bare list path: bare
// invocation parses, args reports NoSubcommand, list_json renders.
let matches = parse(&cmd, &[]).unwrap();
assert!(matches!(
args(&cmd, &matches),
Err(mcp_to_cli::MappingError::NoSubcommand)
));
let listed = mcp_to_cli::list_json(&[
tool(
"create_issue",
"the create_issue tool",
fixture("create_issue.json"),
),
tool(
"create_pull_request",
"the create_pull_request tool",
fixture("create_pull_request.json"),
),
]);
assert_eq!(listed.as_array().map(Vec::len), Some(2));
}
+289
View File
@@ -0,0 +1,289 @@
//! Tool selection: which tools become subcommands, the bare
//! invocation list, and the errors `args` reports.
mod common;
use common::{mapped, overridden, parse, run, tool};
use mcp_to_cli::{MappingError, args, cli_safe, command, list_json};
use serde_json::json;
#[test]
fn cli_safe_accepts_argv_clean_names() {
for name in [
"create_issue",
"a",
"A9",
"with-dash",
"with_underscore",
"9",
"help",
] {
assert!(cli_safe(name), "{name} should be safe");
}
}
#[test]
fn cli_safe_rejects_everything_else() {
for name in [
"",
"has space",
"dot.name",
"sla/sh",
"uni\u{e7}ode",
"star*",
"tab\tname",
"query?",
] {
assert!(!cli_safe(name), "{name} should not be safe");
}
}
#[test]
fn unsafe_named_tools_are_omitted() {
let cmd = command(
"srv",
&[
tool(
"safe",
"safe tool",
json!({"type": "object", "properties": {}}),
),
tool(
"bad name",
"unreachable",
json!({"type": "object", "properties": {}}),
),
],
);
assert!(cmd.find_subcommand("safe").is_some());
assert!(cmd.find_subcommand("bad name").is_none());
}
#[test]
fn help_named_tools_are_skipped() {
let cmd = command(
"srv",
&[
tool(
"help",
"clap owns this name",
json!({"type": "object", "properties": {}}),
),
tool("other", "fine", json!({"type": "object", "properties": {}})),
],
);
// cli_safe("help") is true — the skip is the command's, not the
// charset's.
assert!(cli_safe("help"));
assert!(cmd.find_subcommand("help").is_none());
assert!(cmd.find_subcommand("other").is_some());
}
#[test]
fn non_object_roots_are_omitted() {
let cmd = command(
"srv",
&[
tool(
"arr",
"array root",
json!({"type": "array", "items": {"type": "string"}}),
),
tool("str", "string root", json!({"type": "string"})),
tool("null_root", "null root", serde_json::Value::Null),
tool(
"object",
"object root",
json!({"type": "object", "properties": {}}),
),
],
);
assert!(cmd.find_subcommand("arr").is_none());
assert!(cmd.find_subcommand("str").is_none());
assert!(cmd.find_subcommand("null_root").is_none());
assert!(cmd.find_subcommand("object").is_some());
}
#[test]
fn duplicate_tool_names_keep_the_first() {
let cmd = command(
"srv",
&[
tool(
"dup",
"first wins",
json!({"type": "object", "properties": {}}),
),
tool(
"dup",
"second ignored",
json!({"type": "object", "properties": {}}),
),
],
);
let sc = cmd.find_subcommand("dup").expect("one subcommand");
assert_eq!(
sc.get_about().map(|a| a.to_string()),
Some("first wins".to_owned())
);
}
#[test]
fn subcommands_follow_catalog_order() {
let empty = json!({"type": "object", "properties": {}});
let cmd = command(
"srv",
&[
tool("bravo", "b", empty.clone()),
tool("alpha", "a", empty.clone()),
tool("charlie", "c", empty),
],
);
let names: Vec<&str> = cmd.get_subcommands().map(|sc| sc.get_name()).collect();
assert_eq!(names, ["bravo", "alpha", "charlie"]);
}
#[test]
fn descriptions_flow_into_about_and_flag_help_verbatim() {
let about = "List things, possibly at length, always helpfully";
let flag_help = "Repository owner (username or organization)";
let cmd = command(
"srv",
&[tool(
"t",
about,
json!({"type": "object", "properties": {"owner": {"type": "string", "description": flag_help}}}),
)],
);
let sc = cmd.find_subcommand("t").expect("tool subcommand");
assert_eq!(
sc.get_about().map(|a| a.to_string()),
Some(about.to_owned())
);
let arg = sc
.get_arguments()
.find(|a| a.get_long() == Some("owner"))
.expect("owner flag");
assert_eq!(
arg.get_help().map(|h| h.to_string()),
Some(flag_help.to_owned())
);
}
#[test]
fn bare_invocation_matches_and_args_reports_it() {
let cmd = command(
"srv",
&[tool("t", "d", json!({"type": "object", "properties": {}}))],
);
let matches = parse(&cmd, &[]).expect("bare invocation parses");
assert!(matches.subcommand().is_none());
assert_eq!(
args(&cmd, &matches).unwrap_err(),
MappingError::NoSubcommand
);
}
#[test]
fn unknown_tool_subcommand_is_claps_error() {
let cmd = command(
"srv",
&[tool("t", "d", json!({"type": "object", "properties": {}}))],
);
assert!(parse(&cmd, &["nope"]).is_none());
}
#[test]
fn matches_outside_the_command_report_unknown_subcommand() {
let with_a = command(
"srv",
&[tool("a", "d", json!({"type": "object", "properties": {}}))],
);
let empty = command("srv", &[]);
let matches = parse(&with_a, &["a"]).expect("parses");
assert_eq!(
args(&empty, &matches).unwrap_err(),
MappingError::UnknownSubcommand {
name: "a".to_owned(),
}
);
}
#[test]
fn list_json_is_name_and_description_pairs() {
let value = list_json(&[
tool("create_issue", "Create an issue", json!({"type": "object"})),
tool(
"get_me",
"Get the authenticated user",
json!({"type": "object"}),
),
]);
assert_eq!(
value,
json!([
{"name": "create_issue", "description": "Create an issue"},
{"name": "get_me", "description": "Get the authenticated user"},
])
);
}
#[test]
fn list_json_of_an_empty_catalog_is_an_empty_array() {
assert_eq!(list_json(&[]), json!([]));
}
#[test]
fn list_json_mirrors_the_rendered_tree() {
let catalog = [
tool("safe", "kept", json!({"type": "object", "properties": {}})),
tool(
"bad name",
"dropped",
json!({"type": "object", "properties": {}}),
),
tool(
"help",
"dropped",
json!({"type": "object", "properties": {}}),
),
tool("str_root", "dropped", json!({"type": "string"})),
tool(
"safe",
"duplicate dropped",
json!({"type": "object", "properties": {}}),
),
];
let cmd = command("srv", &catalog);
let tree: Vec<serde_json::Value> = cmd
.get_subcommands()
.map(|sc| {
json!({
"name": sc.get_name(),
"description": sc.get_about().map(|a| a.to_string()).unwrap_or_default(),
})
})
.collect();
assert_eq!(list_json(&catalog), serde_json::Value::Array(tree));
assert_eq!(
list_json(&catalog),
json!([{"name": "safe", "description": "kept"}])
);
}
#[test]
fn mapped_and_overridden_cover_the_whole_surface() {
let cmd = command(
"srv",
&[tool(
"t",
"d",
json!({"type": "object", "properties": {"owner": {"type": "string"}}}),
)],
);
assert_eq!(overridden(run(&cmd, &["t", "--json", "{}"]).unwrap()), "{}");
assert_eq!(
mapped(run(&cmd, &["t", "--owner", "o"]).unwrap()),
json!({"owner": "o"})
);
}