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: Connector-backed agent

Most agents should use ctx.capability.call(canonical_name, ...) — it decouples the agent from any specific vendor. But sometimes you need raw access: a Postgres query, a Shopify-specific endpoint not in the catalogue, a custom REST recipe. That's ctx.connector.*.

When to use ctx.connector instead of ctx.capability:

  • The operation doesn't map to a canonical capability (bespoke queries)
  • You explicitly want to require a specific connector type
  • You're building an admin-tier agent that inspects tenant data

When to use ctx.capability instead:

  • The operation is one of the 46 canonical capabilities (orders, tickets, customers, etc.) — see the capability catalogue
  • You want the same agent to work across tenants with different connector bindings

Example use case#

An analytics agent that queries the tenant's warehouse directly:

  1. Lists bound Postgres connections via ctx.connector.list()
  2. Picks the warehouse alias (e.g. pg_analytics)
  3. Runs a parameterised query via ctx.connector.call()
  4. Summarises results via LLM

manifest.json#

JSON
{
  "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
  "id": "io.konstera.sales-analytics",
  "version": "0.1.0",
  "name": "Sales Analytics",
  "description": "Queries the tenant's warehouse directly for sales rollups.",
  "icon": "📊",
  "autonomy": "autonomous",
  "runtime": {
    "kind": "container",
    "image": "ghcr.io/your-org/sales-analytics:0.1.0",
    "port": 8080,
    "timeoutSeconds": 60,
    "memoryMi": 384
  },
  "input": {
    "type": "object",
    "required": ["period_days"],
    "properties": {
      "period_days": { "type": "integer", "default": 30 },
      "connection_alias": {
        "type": "string",
        "default": "pg_analytics",
        "description": "Tenant-configured warehouse connection alias"
      }
    }
  },
  "llmRequirements": [
    { "purpose": "narrator", "suggestedModel": "claude-sonnet-4-6", "maxTokens": 1024 }
  ],
  "capabilities": { "needs": [] }
}

No capabilities needed — connector access is granted via the portal's Connection Grants, not via capability bindings.

main.py#

Python
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run


class SalesAnalyticsAgent(Agent):
    """Queries the warehouse for sales rollups + LLM-summarises."""

    async def handle(
        self, req: AgentRequest, ctx: AgentContext
    ) -> AgentResponse:
        payload = req.payload or {}
        period_days = payload.get("period_days", 30)
        alias = payload.get("connection_alias", "pg_analytics")

        # 1. Verify the connection is granted
        grants = await ctx.connector.list()
        granted_aliases = [g.alias for g in grants]
        if alias not in granted_aliases:
            return AgentResponse(
                content="",
                structured={
                    "error": "connection_not_granted",
                    "requested": alias,
                    "available": granted_aliases,
                },
            )

        # 2. Run the query
        await ctx.log.info("analytics.query", alias=alias, period_days=period_days)
        rows = await ctx.connector.call(
            alias,
            "query",
            {
                "sql": """
                    SELECT
                      DATE_TRUNC('day', created_at) AS day,
                      COUNT(*) AS order_count,
                      SUM(total_usd) AS revenue_usd
                    FROM orders
                    WHERE created_at >= NOW() - INTERVAL '%s days'
                      AND status = 'paid'
                    GROUP BY 1
                    ORDER BY 1 DESC
                    LIMIT %s
                """,
                "params": [period_days, period_days],
            },
        )
        # rows is whatever the connector returns — Postgres gives a list of dicts
        if not rows or not isinstance(rows, list):
            return AgentResponse(
                content="No data in the queried window.",
                structured={"rows": 0, "period_days": period_days},
            )

        # 3. Build a summary prompt
        preview = "\n".join(
            f"{r['day'][:10]}: {r['order_count']} orders, ${r['revenue_usd']:,.0f}"
            for r in rows[:7]  # top 7 for the prompt
        )
        total_revenue = sum(float(r["revenue_usd"]) for r in rows)
        total_orders = sum(int(r["order_count"]) for r in rows)

        # 4. LLM-summarise
        result = await ctx.llm.complete(
            prompt=(
                f"Summarise the following sales data for the last {period_days} days. "
                f"Highlight 1-2 notable trends. Max 3 sentences.\n\n"
                f"Daily snapshot (most recent 7 days):\n{preview}\n\n"
                f"Totals: {total_orders} orders, ${total_revenue:,.0f} revenue"
            ),
            purpose="narrator",
            temperature=0.3,
            max_tokens=300,
        )

        await ctx.log.info(
            "analytics.done",
            days=len(rows),
            total_revenue=total_revenue,
            llm_cost_usd=result.cost_usd,
        )

        return AgentResponse(
            content=result.content,
            structured={
                "period_days": period_days,
                "days_with_data": len(rows),
                "total_orders": total_orders,
                "total_revenue_usd": total_revenue,
                "connection": alias,
            },
        )


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

How the operator grants access#

Terminal
# Portal → Settings → Connections → New Connection
# Name: pg_analytics
# Type: Postgres
# Host / Port / Database / Role (RO) / Password
# Save.

# Portal → Agent instance → Settings → Grants
# Grant: pg_analytics → agent instance
# Save.

Now ctx.connector.list() returns a ConnectorGrant for pg_analytics; ctx.connector.call("pg_analytics", "query", {...}) works.

Pitfalls#

  • SQL injection via LLM-written SQL: if your agent lets an LLM generate SQL and runs it, you're one prompt-injection away from DROP TABLE. Use parameterised queries (params) only — never string-interpolate values into the SQL. The example above does this correctly.
  • Over-fetching: LIMIT your queries. A connector call doesn't have a built-in cap; a SELECT * on a huge table can OOM the agent container.
  • No capability indirection: switching from Postgres to Snowflake means rewriting the agent. If you want portability, model the query as a capability (sales.rollup_by_day) and have the connector hidden behind it.
  • Connection pooling: each ctx.connector.call() is a separate kernel activity, not a long-lived connection. Don't try BEGIN TRANSACTION / COMMIT across multiple calls — they land on different pool connections.

Common extensions#

  • Multiple connections: an agent can use several bound connections. Pass the alias in req.payload so the operator can route the same agent to different warehouses.
  • Streaming large results: Postgres connectors support cursor_name for server-side cursors. Fetch in batches to keep memory bounded.
  • Shopify / BigCommerce / NetSuite: use ctx.connector.call(alias, "orders.list", {...}) for vendor-specific operations not in the canonical catalogue. Common verbs: products.*, customers.*, fulfillments.*.

See also#