Skip to content
Konstera
Docs · Cookbook
Konstera documentation.

Getting started, SDK quickstart, manifest reference, kernel MCP services, deploy guide and FAQ — everything you need to build and run agents on Konstera.

Cookbook: Agent that runs a Context-portal skill

A skill is a named reusable playbook authored in the Context portal — an ordered list of steps the tenant admin writes once, that the agent runs deterministically. Separates the business playbook (which changes with policy) from the agent code (which changes with features).

Reads: ctx.semantic.skills_get(name) for the skill + its steps. Runs: an agent-side skill runner that dispatches each step's kind to the matching handler. Why: the admin can rewrite the playbook without a redeploy.

Example use case#

The customer-service agent runs a tenant-authored evaluate_refund_eligibility skill (shipped with the Standard Context Pack v1):

JSON
{
  "name": "evaluate_refund_eligibility",
  "steps": [
    {
      "step_order": 1,
      "kind": "lookup",
      "description": "Fetch customer by email",
      "payload": {
        "capability": "customers.lookup_by_email",
        "field_in_from_input": "email",
        "store_as": "customer"
      }
    },
    {
      "step_order": 2,
      "kind": "lookup",
      "description": "Fetch order by ID",
      "payload": {
        "capability": "orders.lookup_by_id",
        "field_in_from_input": "order_id",
        "store_as": "order"
      }
    },
    {
      "step_order": 3,
      "kind": "decide",
      "description": "Within refund window?",
      "payload": {
        "condition": "order.days_since_delivery <= 30",
        "store_as": "in_window"
      }
    },
    {
      "step_order": 4,
      "kind": "decide",
      "description": "Compute refund amount",
      "payload": {
        "expression": "order.total_usd - (order.restocking_fee_pct / 100 * order.total_usd)",
        "store_as": "refund_amount"
      }
    },
    {
      "step_order": 5,
      "kind": "action",
      "description": "Emit decision",
      "payload": {
        "kind": "emit",
        "fields": {
          "decision": "approve_if(in_window, 'approve', 'reject')",
          "amount_usd": "refund_amount",
          "grounds": "if(in_window, 'within policy', 'outside 30-day window')"
        }
      }
    }
  ]
}

The skill is authored once in the portal. Agents consume it by name.

main.py#

The agent calls ctx.semantic.skills_get() then runs the steps:

Python
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run
from konstera_sdk.semantic import Skill, SkillStep


class RefundAgent(Agent):
    """Runs the tenant-authored evaluate_refund_eligibility skill."""

    async def handle(
        self, req: AgentRequest, ctx: AgentContext
    ) -> AgentResponse:
        payload = req.payload or {}

        # 1. Fetch the skill from the Context Service
        skill = await ctx.semantic.skills_get("evaluate_refund_eligibility")
        if not skill:
            # Degraded path: feature disabled or skill not authored yet
            await ctx.log.warn("skill.not_found", name="evaluate_refund_eligibility")
            return AgentResponse(content="", structured={"error": "skill_unavailable"})

        await ctx.log.info("skill.start", name=skill.name, version=skill.version, steps=len(skill.steps))

        # 2. Run the steps deterministically
        runner = SkillRunner(skill, payload, ctx)
        try:
            result = await runner.run()
        except SkillRunnerError as e:
            await ctx.log.warn("skill.failed", step=e.step_order, reason=str(e))
            return AgentResponse(content="", structured={"error": str(e)})

        await ctx.log.info("skill.done", decision=result.get("decision"))
        return AgentResponse(content="", structured=result)


class SkillRunnerError(Exception):
    def __init__(self, step_order: int, message: str):
        self.step_order = step_order
        super().__init__(message)


class SkillRunner:
    """Deterministic agent-side runner for Context-portal skills.

    Each step kind maps to a handler. The runner builds a local
    'variables' dict that steps read + write via `store_as` / expression
    references like 'order.total_usd'.
    """

    def __init__(self, skill: Skill, input_vars: dict, ctx: AgentContext):
        self.skill = skill
        self.ctx = ctx
        self.vars: dict = {"input": input_vars}

    async def run(self) -> dict:
        for step in self.skill.steps:
            await self._run_step(step)
        return self.vars.get("emit", {})

    async def _run_step(self, step: SkillStep) -> None:
        if step.kind == "lookup":
            await self._do_lookup(step)
        elif step.kind == "decide":
            self._do_decide(step)
        elif step.kind == "action":
            self._do_action(step)
        else:
            raise SkillRunnerError(step.step_order, f"unknown step kind: {step.kind}")

    async def _do_lookup(self, step: SkillStep) -> None:
        payload = step.payload
        cap_name = payload["capability"]
        field = payload["field_in_from_input"]
        store_as = payload["store_as"]
        value = self.vars["input"].get(field)
        if not value:
            raise SkillRunnerError(step.step_order, f"missing input field: {field}")
        self.vars[store_as] = await self.ctx.capability.call(cap_name, **{field: value})

    def _do_decide(self, step: SkillStep) -> None:
        # In a real runner, this is a sandboxed expression evaluator
        # (NOT Python's built-in dynamic-code primitives!) that resolves variable
        # references like 'order.total_usd'. Example implementation: compile the
        # condition into a safe AST and walk it, allowing only known operators.
        payload = step.payload
        store_as = payload["store_as"]
        expr = payload.get("condition") or payload.get("expression")
        self.vars[store_as] = self._eval_safe(expr)

    def _do_action(self, step: SkillStep) -> None:
        payload = step.payload
        if payload["kind"] == "emit":
            self.vars["emit"] = {
                k: self._eval_safe(expr) for k, expr in payload["fields"].items()
            }

    def _eval_safe(self, expr: str):
        """Sandboxed expression evaluator — NEVER use Python's built-in
        dynamic-code primitives here. Real implementation uses asteval or
        a hand-rolled AST walker that only supports a known-safe set of
        operators + the self.vars namespace."""
        # (abbreviated for the recipe — see github.com/Konstera/agents for the full
        # customer-service-agent's skill_runner.py)
        raise NotImplementedError("See reference agent for full implementation")


if __name__ == "__main__":
    run(RefundAgent())

manifest.json#

Declare the skill requirement in contextRequirements so install validation catches missing-skill scenarios:

JSON
{
  "contextRequirements": {
    "skills": [
      {
        "name": "evaluate_refund_eligibility",
        "required": true
      }
    ],
    "ontologyEntities": [
      { "entity": "customer", "required": true },
      { "entity": "order", "required": true }
    ]
  }
}

If the tenant hasn't authored the skill at install time, the kernel refuses install with [VAL-002].

Why not just hardcode the logic?#

Because the admin wants to change 30 days to 45 days without a redeploy. Or add a step. Or branch on a new condition. All without touching the agent code or going through engineering.

The agent code is the playbook runner, not the policy.

Pitfalls#

  • Expression evaluator safety: NEVER use Python's built-in dynamic-code primitives in your runner. Build an AST walker that only supports:
    • Variable references (order.total_usd, input.email)
    • Known operators (<=, >, ==, +, -, *, /, and, or, not)
    • Known functions (approve_if, if, max, min) See the reference customer-service-agent/skill_runner.py for a working implementation.
  • Skill version pinning: for reproducibility, record the skill's version in your output and allow replay against the exact version via skills_get_by_id() (lands with v0.7.0 of the SDK).
  • Capability mapping: a skill step's capability field must match a bound capability on this agent instance. Guard with ctx.capability.available() in the lookup step; emit a clear SkillRunnerError on unbound.
  • Step reordering: steps are run in step_order. Don't assume array index — the kernel may return them unordered.

Common extensions#

  • Skills with LLM steps: add a step kind llm whose payload carries prompt_template, purpose, temperature. Lets the admin tune prompts without touching code.
  • Branching skills: add a branch step kind with on_true / on_false arrays of child steps. The admin models flow control.
  • Skill library per department: tenants author one skill per decision (refund eligibility, triage priority, markdown eligibility). Agents compose them via ctx.semantic.skills_get(category).

See also#