# Install bonsai3 in an agent

This guide is for an AI agent or developer configuring an agent harness to use bonsai3. For policy lookups, see [MCP setup](#mcp-security-context-tool). For enforcement, use the hook contract below and select the framework integration point for your agent. A framework-specific adapter must translate hook events and enforce the response.

## Instructions for an installing agent

1. Identify the actual agent runtime, its installed version, and where task invocation and tool dispatch happen. Read the existing configuration before editing it. Preserve existing hooks, permissions and user settings.
2. Obtain the service URL, project ID and **project-scoped** token from the operator. Ask if any are unavailable; do not guess credentials or put them into source files, logs, chat transcripts, hook output or committed configuration. The token is shown only when issued.
3. Verify the agent process can reach the service and authenticate with the smoke test below. A local address refers to the agent's own network namespace; a remote agent or container may need a different reachable URL.
4. Install synchronous hooks in the agent's actual task-start and tool-dispatch paths using the contract below. Cover every tool, including MCP tools, subagents and parallel calls where the framework supports them. If a framework lacks a blocking hook or a way to feed guidance back before execution, report the gap; do not claim it is enforced.
5. Verify permit, block, steer, and service-failure behavior with the harness, not just an API call. Report which events are covered and any missing coverage.

Do not rely on agent instructions, a prompt, or a post-tool hook as an enforcement point: the action must be intercepted **before** it executes.

## Prerequisites and connection

The operator starts bonsai3 using the [main README](../README.md), creates an organization and project, then issues a project credential. An organization token or the bootstrap admin token can issue a project token:

```sh
curl --fail-with-body -sS -X POST \
  "$POLICY_GATE_URL/v1/projects/$POLICY_GATE_PROJECT_ID/credentials" \
  -H "Authorization: Bearer $POLICY_GATE_MANAGEMENT_TOKEN"
```

Only the operator should handle the management token. Give the agent the returned project token through its runtime's secret store or protected environment. Set the following variables in the agent process (the names here are conventions for integrations, not server configuration):

```sh
export POLICY_GATE_URL="http://127.0.0.1:4000"
export POLICY_GATE_PROJECT_ID="<project-id>"
export POLICY_GATE_TOKEN="<project-token>"
```

Use a TLS-protected endpoint across untrusted networks. Avoid placing real tokens in shell history or project files; use your platform's secret injection mechanism. The server accepts a maximum JSON body of 1,000,000 bytes; avoid sending unneeded secrets in intent or tool arguments. Configured model services receive those inputs.

### Smoke test

```sh
curl --fail-with-body -sS "$POLICY_GATE_URL/health"
curl --fail-with-body -sS \
  "$POLICY_GATE_URL/v1/projects/$POLICY_GATE_PROJECT_ID/decisions" \
  -H "Authorization: Bearer $POLICY_GATE_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"hook":"pre_task","intent":"Implement a controller"}'
```

The standard controller policy should normally return `"decision":"steer"` and security guidance. This confirms the endpoint and credentials, **not** that your harness runs hooks. With semantic classification enabled, an uncertain model response can instead return 503. Without a model service the server uses a demonstration-only keyword matcher. Refer to the main README for model configuration.

## Required hook contract

### Agent intent instruction

When your harness supports passing an intent field from the agent to its pre-task and pre-tool hooks, add the following to its trusted agent instructions. The harness must make that field available to the hook; adding this text alone does not wire up or enforce a hook.

```text
Before starting a task and before proposing a tool call, provide a concise,
specific intent for the policy hook. State what you are trying to accomplish,
which component or resource is affected, and the relevant security purpose or
impact. For code changes, identify the kind of component (for example, an HTTP
controller) and what it will do. For tools, distinguish the purpose of the
individual action from the overall task. Do not claim that an action is safe,
authorized, or already compliant unless that has been verified. Do not include
credentials or other secrets in the intent.

Example task intent: "Implement an HTTP account controller that authenticates
requests and returns account details."
Example tool intent: "Write the account controller implementation, including
request authentication and authorization checks."

Submit intent through the harness's policy-hook field, not as a substitute for
the hook itself. Wait for the policy decision before the task or tool executes.
If blocked, stop. If guidance is returned for a pending tool call, reconsider
that call using the guidance and submit the revised action for a new check. If
the policy check fails or intent cannot be supplied, stop and report the issue.
```

The backend rejects missing, empty, and whitespace-only intent; the hook adapter must also prevent execution on rejection. It cannot verify that an agent's declared intent is truthful or detailed enough. Tool name and actual serialized arguments are separate facts supplied by the harness and must not be replaced by intent. If a runtime such as a specific Codex hook does not expose an agent-provided intent field, report that the above requirement is **not implemented** for that runtime; a prompt or user-task fallback does not make the agent supply per-tool intent. Build a supported intent channel or explicitly accept that limitation before enabling the integration.

### Request and response

Send `POST $POLICY_GATE_URL/v1/projects/$POLICY_GATE_PROJECT_ID/decisions` with the project bearer token and `Content-Type: application/json`.

Before a task or agent invocation:

```json
{"hook":"pre_task","intent":"Implement an account controller"}
```

Before a tool call, send the **actual** tool name and arguments, not only the agent's assertion about them:

```json
{"hook":"pre_tool_use","intent":"Implement the account controller","tool_name":"write_file","tool_input":"{\"path\":\"src/account_controller.ex\"}"}
```

`intent` is a required nonempty string. For tool calls, `tool_name` is required and nonempty; `tool_input` is an optional **string**. Serialize object arguments as JSON into that string. If the framework does not expose per-tool intent, use the current task description as a fallback and document the limitation; never pretend inferred intent is verified fact. Avoid inventing information. Apply the check to the final arguments that will actually be executed, including after any argument-mutating hooks.

A successful response contains `decision`, `guidance`, `matched_policies`, and `audit_id`:

| Response | Required harness behavior |
| --- | --- |
| `permit` | Execute the checked action. |
| `block` | Do not execute; report the denial to the agent. |
| `steer` | Give the guidance to the agent **before** the action. For an already-proposed tool call, cancel or suspend it and let the agent reconsider; evaluate any new call again. |
| non-200, timeout, network error, malformed or unknown response | Fail closed: do not execute; surface the failure. |

Use bounded request timeouts and ensure hook crashes or timeouts also fail closed at the framework layer. `steer` is not proof that the agent complied; require independent checks for important constraints. If the framework cannot safely interrupt and resume, do not execute the proposed call on a steer response.

### How the backend supplies policies

The project ID identifies the project, and the backend loads its attached published custom policies and selected built-in policies. Secure-development policies start enabled and can be removed per project; PCI DSS policies require explicit project opt-in. Drafts do not apply. For the given hook it evaluates each policy's applicability conditions against the intent, tool name and tool input. The preview's keyword adapter uses substring matching; when configured, Strands Decider classifies the applicability question, returning an error for uncertain results. All matching policies are aggregated: block takes precedence over steer, which takes precedence over permit. If none matches, the current default is permit.

The response contains metadata for matched policies and a `guidance` array containing the text of matched steer policies. It is the hook adapter's responsibility to supply this guidance to the agent before execution. For example, an intent mentioning a controller can match the built-in secure-controller policy and return guidance on authentication, authorization, input validation, mass assignment and safe errors. The API does not send every policy or prove that an agent followed the guidance. Inspect the decision's `matched_policies` and `audit_id` to see what was applied.

## Python harness integration

`../clients/policy_gate.py` is a standard-library client. Add the repository's `clients/` directory to the application's `PYTHONPATH` or vendor the file into the application. The following is a **framework-independent integration pattern**; names such as `append_guidance_to_task` and `return_tool_error_to_agent` are application-provided:

```python
import os
from policy_gate import PolicyDenied, PolicyGate

gate = PolicyGate(
    os.environ["POLICY_GATE_URL"],
    os.environ["POLICY_GATE_PROJECT_ID"],
    os.environ["POLICY_GATE_TOKEN"],
    timeout=15,
)

def before_task(intent):
    # A nonempty guidance list means steer; PolicyDenied covers block and errors.
    guidance = gate.check("pre_task", intent)
    if guidance:
        append_guidance_to_task(guidance)

def dispatch_tool(name, arguments, task_intent):
    try:
        guidance = gate.check("pre_tool_use", task_intent, name, arguments)
        if guidance:
            # Do not execute the old proposal: send guidance to the agent to replan.
            return return_tool_error_to_agent("Reconsider this tool call: " + "\n".join(guidance))
        return execute_tool(name, arguments)
    except PolicyDenied as error:
        return return_tool_error_to_agent(str(error))
```

Catch `PolicyDenied` around `before_task` too and do not start the task on failure. `gate.run()` exists for callback-oriented harnesses, but it executes the action immediately after the guidance callback; use `check()` and cancel/replan for an already-proposed tool call unless your harness guarantees the callback itself safely changes the action before execution. A persistent steer for the same unchanged call can cause a loop; expose it to the operator or apply an explicit bounded retry policy rather than bypassing the check.

## MCP: security context tool

Connect directly to **`/mcp`** on the bonsai3 server using **Streamable HTTP** (for example, `http://192.168.1.121:4400/mcp` on the preview). Authenticate each request with `Authorization: Bearer <token>`.

In the dashboard, open **Projects → Organization MCP access → Issue MCP token**. That token grants policy lookups for its issuing organization only. An existing project token also works and is audited against its project. Do not use a dashboard admin token. An operator can also issue a lookup-only token through the API:

```sh
curl --fail-with-body -sS -X POST \
  "$POLICY_GATE_URL/v1/organizations/$POLICY_GATE_ORGANIZATION_ID/mcp-credentials" \
  -H "Authorization: Bearer $POLICY_GATE_MANAGEMENT_TOKEN"
```

The bearer token selects the project or organization; `security_context(intent: string)` takes no tenant or project ID. Project tokens evaluate the project's attached custom and selected built-in policies using the `pre_task` rules. Organization-only tokens evaluate organization policies and the secure-development baseline, without project-specific PCI DSS opt-ins. The result includes `decision`, `guidance`, `matched_policies`, `audit_id`, and `banner`. After the first successful lookup in a session, show `🌱 Secured by bonsai3` on its own line at the top of your next user-visible response. The banner confirms the lookup, not approval of the action. A failed lookup is a tool error. Treat a block as a stop. Use the hook contract above when you need enforcement even if the model skips the MCP tool.

### Codex configuration

Set `POLICY_GATE_MCP_TOKEN` through the Codex process environment. In the appropriate trusted Codex `config.toml`, merge the following configuration, replacing the URL with your deployment's endpoint:

```toml
[mcp_servers.bonsai3]
url = "http://192.168.1.121:4400/mcp"
bearer_token_env_var = "POLICY_GATE_MCP_TOKEN"
```

Restart or reconnect Codex and inspect `/mcp`; confirm that `security_context` is listed. Ask it to check “Implement an account controller” and inspect the returned guidance. Other MCP clients can use the same endpoint with Streamable HTTP and bearer authentication. Use HTTPS outside the trusted preview network. The endpoint rejects requests carrying an `Origin` header by default; deployments can admit specific origins via `POLICY_GATE_MCP_ALLOWED_ORIGINS` (comma-separated exact matches). Clients needing local stdio can still use `clients/mcp_server.py` with a project token and the previously described `POLICY_GATE_*` connection variables.

## Framework integration points

These are starting points, not preinstalled integrations. Verify the installed framework version and its failure, cancellation, and subagent semantics before declaring enforcement.

### Strands Agents

Register callbacks for `BeforeInvocationEvent` and `BeforeToolCallEvent` on **each** agent, including agents in a graph or swarm. The former exposes invocation messages; the latter exposes `event.tool_use` and supports cancellation through `event.cancel_tool` in the Python SDK. Feed task guidance into the invocation before the model runs; on a tool steer, cancel the tool and return guidance to the model for replanning. Ensure exceptions and timeout behavior are fail-closed. See the [Strands hooks guide](https://strandsagents.com/docs/user-guide/sdk/agents/hooks/) and the version-specific event reference.

### Claude Code

Configure synchronous `UserPromptSubmit` and `PreToolUse` command hooks in the appropriate Claude Code settings, merging with existing hooks. A command adapter must translate Claude's JSON stdin to the bonsai3 contract and translate the response to Claude's hook output; the bonsai3 endpoint itself does **not** speak Claude's hook protocol. `UserPromptSubmit` is a per-turn approximation of pre-task, not necessarily every internally created task. Use a matcher that covers all tools; check coverage of subagents and managed-hook restrictions. On versions supporting it, configure `onFailure: "block"` and test hook crashes/timeouts. For tool steering, deny the pending call with the guidance as the reason so Claude can replan. See the [Claude Code hooks reference](https://code.claude.com/docs/en/hooks).

### OpenCode

Inspect the installed OpenCode version and use its supported server-side plugin/hook API to intercept the task and tool-dispatch lifecycle. Local plugins are discovered under `.opencode/plugins/`; see the [plugin documentation](https://opencode.ai/docs/plugins/) and its version-specific hook reference. A plugin must explicitly translate the events, block failures and return steering before tool execution. Confirm subagent and MCP tool coverage. Do not treat an instruction in `AGENTS.md` as an enforced hook, and do not claim support if the installed version has no blocking task hook.

### Codex

For local Codex, inspect the installed version's [hooks reference](https://developers.openai.com/codex/hooks/) and configure trusted `UserPromptSubmit` and `PreToolUse` command hooks where supported. Adapt JSON input and output to the documented Codex hook protocol, and validate trust, cancellation, crash and timeout behavior with the actual version. User prompt submission is only an approximation of pre-task. Hook availability and trust differ across CLI, cloud and managed environments; MCP hook errors may not block, so they must not be assumed fail-closed. If no enforceable interception is available, report that limitation.

### LangChain / LangGraph and other frameworks

Use the framework's synchronous or awaited task-start interceptor and tool-call middleware around the **actual** dispatch. LangChain exposes [agent middleware](https://docs.langchain.com/oss/python/langchain/middleware/overview); register middleware on every agent and graph path. For custom harnesses use the Python pattern above or implement the HTTP contract directly. Translate a denial/steer to the framework's own cancellation and feedback mechanism; do not assume a logging callback can block a tool.

## Verify an installation

Use an isolated test project and policies controlled by the operator. Confirm each item by observing actual execution, not just the returned JSON:

1. A nonmatching action returns permit and executes once.
2. A matching block policy prevents the tool's side effect and produces a denial visible to the agent.
3. A steer at task start reaches the model before it begins. A tool steer prevents the original call and returns guidance for replanning.
4. Stop or disconnect the policy server, use an invalid token, and simulate a timeout and malformed response: none may execute the action.
5. Verify relevant tools, MCP tools, subagents, concurrent calls, retries and argument modifications pass through the hook. Verify a project token cannot access another project.
6. Inspect the organization's `GET /v1/organizations/:organization_id/decision-audit` using an organization credential, and correlate successful decision `audit_id` values. Do not put a management credential in the agent to do this.

bonsai3 is currently an MVP. The default keyword classifier is not a semantic security system; model decisions can also be wrong. Agent-supplied intent is untrusted, and tool enforcement depends on the harness and sandbox.
