Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
36 changes: 32 additions & 4 deletions hermes_plugin_kit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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")

Expand Down
104 changes: 104 additions & 0 deletions tests/test_kit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.")
Loading