From 91f2c2739ccf51b891331f3a789a15dd4f40a087 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Mon, 21 Sep 2026 16:49:08 -0500 Subject: [PATCH] fix(tools): give supplied schemas the same description guidance as params Choosing @tool(schema=...) silently cost a plugin its model-facing guidance. _augment_description ran only on the params path, so a supplied Hermes schema reached the model with its bare description -- no "Required: `x` (e.g. ...)", no "Optional:" -- and the runtime missing-argument error dropped its example too, because the examples dict was hardcoded to {} whenever schema was supplied. That made the two paths mutually exclusive with nothing saying so: use params and lose expressive keywords like oneOf, or use schema and lose the guidance. A peer found it by probing the running kit rather than by reading, which is the tell that it was undocumented rather than intended. Both clauses are now built from the consumer's own schema -- its required list and the JSON Schema examples keyword on each property -- so this surfaces their data rather than inventing any. examples is the spelling Hermes understands: its schema sanitizer names it a preserved metadata keyword and a non-schema sibling, and does not recognize a scalar example, so a scalar is deliberately not read. Two limits keep this from rewriting descriptions people wrote by hand. A clause is skipped when the description already carries that label, so prose spelling out its own requirements is not contradicted by a second, differently-worded Required: clause. And a schema with no required properties and no examples is left byte-identical. This also serves the standing rule that validation errors stay instructive "including the missing argument name and example when available" -- on the schema path the example was available and thrown away. Note the tension with PR #15, which offered this path so plugins could "adopt decorators without changing their public schemas": the emitted description does change. The schema itself does not, the added text is derived wholly from the schema, and the path already replaced the description with the resolved doc rather than passing it through, so description fidelity was never absolute here. Verified: schema= and params= now emit byte-identical descriptions for equivalent inputs, with oneOf and required preserved. Mutation-tested all three guards -- dropping the augmentation fails 4 tests, dropping the double-augmentation guard fails 1, reading a scalar example fails 1. Full suite 265 tests OK. --- README.md | 16 ++++++ hermes_plugin_kit/__init__.py | 36 ++++++++++-- tests/test_kit.py | 104 ++++++++++++++++++++++++++++++++++ 3 files changed, 152 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a5865cf..86f02c4 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,22 @@ references. Required fields stay visible to the model. The default set it to `False` only when an existing handler must retain its established validation and error payload. +A supplied schema gets the same description guidance a `params` schema gets. +The kit appends `Required:` and `Optional:` clauses built from the schema's own +`required` list and the JSON Schema `examples` keyword on each property, and +uses the first `examples` entry in missing-argument errors: + +```python +"properties": {"content": {"type": "string", "examples": ["a short note"]}} +# description becomes: "... Required: `content` (e.g. 'a short note')." +``` + +Use `examples` (the JSON Schema list), not a scalar `example` — the list is the +spelling Hermes' schema sanitizer carries through. Nothing is appended when the +schema declares no required properties and no examples, and a clause is skipped +when your description already spells that label out itself, so prose you wrote +by hand is never contradicted. + ## Commands, middleware, hooks, and plugin skills Use the lifecycle entrypoint when a plugin provides more than tools: diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index 0484f5c..c9b09fd 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -819,9 +819,14 @@ def _augment_description(description: str, required: list, examples: dict) -> st perfectly good one that no agent ever saw. An example is guidance about shape; whether the key is mandatory is a separate fact, and conflating them silently discarded the guidance. + + A clause is skipped when the supplied description already carries its + label. Hand-written Hermes schemas often spell their own requirements out + in prose, and appending a second "Required:" would contradict rather than + clarify. """ parts = [description] - if required: + if required and "Required:" not in description: bits = [ f"`{key}`" + (f" (e.g. {examples[key]!r})" if key in examples else "") for key in required @@ -833,7 +838,7 @@ def _augment_description(description: str, required: list, examples: dict) -> st for key in examples if key not in required ] - if optional_examples: + if optional_examples and "Optional:" not in description: parts.append(f"Optional: {', '.join(optional_examples)}.") return " ".join(parts) @@ -857,6 +862,27 @@ def build_schema(name: str, description: str, params: dict | None) -> dict: } +def _schema_examples(properties: dict) -> dict: + """Pull per-key examples out of a supplied Hermes function schema. + + The kit's own ``params`` format carries a scalar ``_example``; a + hand-written Hermes schema carries the JSON Schema ``examples`` keyword, + a list. That is the spelling the host understands -- its schema sanitizer + names ``examples`` as a preserved metadata keyword and a non-schema + sibling ("list of example values"), and does not recognize a scalar + ``example``. So read ``examples`` and take the first entry, which is the + one a description can show without becoming a catalogue. + """ + found: dict[str, Any] = {} + for key, spec in properties.items(): + if not isinstance(spec, dict): + continue + values = spec.get("examples") + if isinstance(values, list) and values: + found[key] = values[0] + return found + + def _copy_and_validate_schema( name: str, description: str, @@ -895,7 +921,9 @@ def _copy_and_validate_schema( "schema.parameters.required references unknown properties: " + ", ".join(unknown_required) ) - copied["description"] = description + copied["description"] = _augment_description( + description, list(required), _schema_examples(properties) + ) return copied @@ -2127,7 +2155,7 @@ def decorate(fn: Callable) -> Callable: for key in required } if schema is None - else {} + else _schema_examples(emitted_schema["parameters"].get("properties", {})) ) log = logging.getLogger(fn.__module__ or "hermes_plugin_kit") diff --git a/tests/test_kit.py b/tests/test_kit.py index 6502ae1..47f8aaa 100644 --- a/tests/test_kit.py +++ b/tests/test_kit.py @@ -2343,3 +2343,107 @@ def _module(self, **attrs): if __name__ == "__main__": unittest.main() + + +class SchemaPathDescriptionParityTests(unittest.TestCase): + """The ``schema=`` path must guide the model as well as ``params=`` does. + + A supplied Hermes schema used to reach the model with its bare + description: ``_augment_description`` ran only on the ``params=`` path, + so a plugin choosing ``schema=`` for an expressive construct such as + ``oneOf`` silently gave up the ``Required:``/``Optional:`` guidance and + the missing-argument examples. The two were mutually exclusive and + nothing said so. + """ + + BASE = "Write a memory entry." + + def _emit(self, **overrides): + schema = { + "parameters": { + "type": "object", + "properties": { + "message": {"type": "string", "examples": ["hello"]}, + "tag": {"type": "string", "examples": ["urgent"]}, + }, + "required": ["message"], + "oneOf": [{"required": ["message"]}], + }, + } + schema["parameters"].update(overrides.pop("parameters", {})) + decorated = hpk.tool( + toolset="x", + name="parity_write_entry", + description=overrides.pop("description", self.BASE), + schema=schema, + **overrides, + )(lambda args, **kwargs: {"ok": True}) + return getattr(decorated, "_hpk_tool_spec")["schema"], decorated + + def test_schema_path_matches_params_path_byte_for_byte(self) -> None: + emitted, _ = self._emit() + equivalent = hpk.build_schema( + "parity_write_entry", + self.BASE, + { + "message": hpk.str_arg("m", required=True, example="hello"), + "tag": hpk.str_arg("t", example="urgent"), + }, + ) + self.assertEqual(emitted["description"], equivalent["description"]) + self.assertIn("Required: `message` (e.g. 'hello')", emitted["description"]) + self.assertIn("Optional: `tag` (e.g. 'urgent')", emitted["description"]) + + def test_augmenting_preserves_expressive_keywords_and_required(self) -> None: + emitted, _ = self._emit() + # The whole reason a consumer picks schema= over params=. + self.assertEqual(emitted["parameters"]["oneOf"], [{"required": ["message"]}]) + self.assertEqual(emitted["parameters"]["required"], ["message"]) + + def test_required_survives_disabled_validation(self) -> None: + emitted, _ = self._emit(validate_required=False) + self.assertEqual(emitted["parameters"]["required"], ["message"]) + self.assertIn("Required: `message`", emitted["description"]) + + def test_missing_argument_error_carries_the_schema_example(self) -> None: + _, decorated = self._emit() + self.assertEqual( + json.loads(decorated({}))["error"], + "message is required (e.g. 'hello')", + ) + + def test_a_description_that_already_says_required_is_not_doubled(self) -> None: + emitted, _ = self._emit( + description="Write an entry. Required: the message body." + ) + self.assertEqual( + emitted["description"].count("Required:"), + 1, + "hand-written requirement prose must not gain a contradicting clause", + ) + # The optional clause is independent and still lands. + self.assertIn("Optional: `tag` (e.g. 'urgent')", emitted["description"]) + + def test_a_schema_with_nothing_to_surface_is_left_alone(self) -> None: + emitted, _ = self._emit( + parameters={ + "properties": {"note": {"type": "string"}}, + "required": [], + "oneOf": [{"required": ["note"]}], + } + ) + self.assertEqual(emitted["description"], self.BASE) + + def test_scalar_openapi_example_is_not_read(self) -> None: + """The host recognizes JSON Schema ``examples``, not scalar ``example``. + + Reading a keyword the host's schema sanitizer does not treat as + metadata would surface guidance the model never sees enforced. + """ + emitted, _ = self._emit( + parameters={ + "properties": {"message": {"type": "string", "example": "hello"}}, + "required": ["message"], + } + ) + self.assertEqual(emitted["description"], f"{self.BASE} Required: `message`.")