# Overview

As AI agents become more capable, they also become more powerful and with that power comes responsibility.

An AI agent that can create invoices, deploy infrastructure, delete repositories, or send emails should not be allowed to perform every action without constraints.

Swytchcode provides a policy engine that allows you to define **what an agent is allowed to do, when it is allowed to do it, and how API requests should be executed safely**.

Policies are evaluated before every execution, giving you complete control over your application's behavior without changing your application code. They can block a call, hold it for a person, change its arguments, and - after the call - hide or cut parts of the response before the agent sees it.

---

### Manage policies from the CLI

```bash
swy policy add               # interactive - prompts for target, condition, and action
swy policy list [--json]
swy policy remove <policy-id>
swy policy validate          # checks the file and runs the tests written in it
swy policy state [--reset]   # counts kept by rate, sum, and repeat limits
```

These commands manage the *rules* in `policies.json`. They're a different surface from `swy audit policy`, which is a read-only log of past violations - use `swy policy list` to see what rules are configured, and `swy audit policy` to see what those rules have actually blocked.

See the [policies.json reference](/configuration/policy-json/) for the full schema, condition operators, and command details.

### Write policies with a coding agent

`swy policy add` covers one condition per policy. For anything bigger, such as several targets, `all`/`any`/`not` conditions, or ten policies at once, let your coding agent (Claude Code, Cursor, and others) write them through MCP.

The policy tools are only in the `full` MCP profile, and `swy init` registers the `agent` profile. Switch your editor to `full` while you build. For Claude Code:

```bash
claude mcp remove swytchcode
swy mcp serve --claude --profile full
```

For other editors, change the server's `args` in the editor's MCP config from `["mcp", "serve"]` to `["mcp", "serve", "--profile", "full"]`.

Then describe what you want, e.g. *"require approval before any HubSpot message is sent to an address outside example.com"*. The agent uses three tools:

| Tool | What it does | Writes? |
|------|--------------|---------|
| `swytchcode_policy_check` | Checks a draft policy, lists errors and warnings, and can test it against sample args ("would block", "would pause for approval", "would allow", "would change"). Runs the draft's `tests` with the rest of `policies.json`. | No |
| `swytchcode_policy_add` | Saves a new policy. Refuses a policy with errors or failing tests, and refuses an id that already exists unless the agent passes `replace: true`. | Yes |
| `swytchcode_policy_remove` | Removes a policy by id. | Yes |

You stay in control: your editor asks you to approve each call to `swytchcode_policy_add` and `swytchcode_policy_remove` (both are marked as destructive), and `policies.json` is committed and reviewed like any other code. Don't add these two tools to your editor's auto-approve list, or they will run without asking. Warnings point out a `REQUIRES_APPROVAL` policy that can't reach a human yet (not signed in, no workspace linked), a target that isn't installed, and field names the target tool doesn't have.

These tools exist only in the `full` profile. A deployed agent connects with `agent` and can read policies but not change them. See [Run agents safely](/policies/production-guardrails/#run-agents-safely).

---

## Why Policies Matter

Consider an AI agent connected to your production systems.

Without guardrails, a simple prompt like:

> "Delete all GitHub repositories."

could execute immediately if the necessary credentials are available.

With Swytchcode policies, you can define rules such as:

- Only allow repository operations for approved organizations.
- Block destructive operations in production.
- Prevent payments above a certain amount.
- Restrict requests outside business hours.
- Require specific request fields before execution.

Instead of trusting every generated request, your application evaluates every request against your policies before it reaches the provider.

---

## The Swytchcode Trust Model

Swytchcode separates API execution into three distinct layers.

```text
                    Developer / AI Agent
                            │
                            ▼
                   tooling.json
              "What can execute?"
                            │
                            ▼
                  policies.json
          "Should this request execute?"
                            │
                            ▼
                  manifest.json
           "How should it execute?"
                            │
                            ▼
                    Provider API
```

Each configuration file has a different responsibility.

| File | Responsibility |
|------|----------------|
| `tooling.json` | Defines the trusted methods available to the project. |
| `policies.json` | Evaluates every request and blocks, holds, or changes operations that violate your rules; can also hide parts of responses. |
| `manifest.json` | Configures authentication, endpoints, retries, timeouts, idempotency, and execution behavior. |

Keeping these responsibilities separate makes policies easier to understand, maintain, and audit.

---

## Request Lifecycle

Every request follows the same execution pipeline.

```text
AI Agent
    │
    ▼
Generate Tool Call
    │
    ▼
Is the tool trusted?
(tooling.json)
    │
    ▼
Does the request satisfy policy rules?
(policies.json)
    │
    ▼
Resolve authentication
    │
    ▼
Apply execution policy
(manifest.json)
    │
    ▼
Execute API
    │
    ▼
Apply response policies
(policies.json, "stage": "response")
    │
    ▼
Return Response
```

If a request matches a deny rule, execution stops immediately before any network request is made. If it matches an [approval policy](/policies/human-approval/), the command is held until a person approves or denies it in Slack.

---

## policies.json example

Policies are defined in `.swytchcode/integrations/policies.json`.

A policy consists of four core parts:

- **id** - A unique identifier for the policy.
- **target** - The methods the policy protects.
- **when** - The condition that determines when the policy should apply.
- **action** - What happens when the condition evaluates to `true`.

A simple policy looks like this:

```json
{
  "defaults": {
    "on_violation": "fail",
    "evaluation": "pre_execution"
  },
  "policies": [
    {
      "id": "star-repo-approval",
      "target": [
        "github.repo.star"
      ],
      "when": {
        "field": "name",
        "operator": "exists"
      },
      "action": {
        "type": "POLICY_BLOCKED",
        "message": "Starring repositories is blocked."
      }
    }
  ]
}
```

In this example:

- The policy is identified by `star-repo-approval`.
- It only applies to the `github.repo.star` method.
- Before execution, Swytchcode checks whether the `name` field exists in the request.
- If the condition matches, execution is blocked and the provided message is returned.

The complete `policies.json` schema, supported operators, and advanced examples are covered in the [policies.json reference](/configuration/policy-json/).

A version-2 file (`"version": 2` at the top) adds much more: patterns such as `"stripe.*"` or `"*"` in `target`, built-in fields like `$http_method` and `$email_domains`, shared lists, limits over time (`rate`, `sum`), changing calls (`MODIFY`), response policies (`REDACT`, `TRUNCATE`), monitor mode, alerts, and tests. Existing version-1 files keep working unchanged. See [File Versions](/configuration/policy-json/#file-versions) and [Policy recipes](/policies/recipes/).

## What Can Policies Protect?

Policies can validate any request before execution.

Some common use cases include:

#### Financial Protection

Prevent expensive or risky operations.

Examples:

- Block payments above a threshold.
- Cap daily spend.
- Restrict refunds above a specific amount, or to charges the agent created.
- Hold high-value transactions for [human approval](/policies/human-approval/), or block them with an allow or deny rule.

---

#### Production Safety

Protect production environments from accidental changes.

Examples:

- Block delete operations.
- Prevent infrastructure changes.
- Restrict deployment actions.

---

#### Authentication & Access

Ensure requests meet your organization's security requirements.

Examples:

- Require authentication fields.
- Restrict operations to approved users.
- Allow requests only from trusted environments.

---

#### Business Rules

Enforce organization-specific policies.

Examples:

- Only allow company email domains.
- Restrict API usage to business hours.
- Limit operations by department or region.

---

#### API Protection

Prevent misuse of third-party APIs.

Examples:

- Limit request frequency.
- Prevent duplicate operations.
- Restrict access to specific providers.

---

#### Data Protection

Keep sensitive data out of the agent's hands.

Examples:

- Hide card numbers, ID numbers, and tokens in responses.
- Block messages that contain personal data or secrets.
- Cap how many records an agent can read per day.

See [Policy recipes](/policies/recipes/) for a ready-to-use policy for each of these.

---

## Defense in Depth

Policies are only one layer of protection.

A production-ready AI application should combine multiple safety mechanisms.

```text
Application Logic
        │
        ▼
Trusted Tools
        │
        ▼
Policy Validation
        │
        ▼
Authentication
        │
        ▼
Execution Policies
        │
        ▼
Provider API
```

Each layer reduces the likelihood of unintended or unsafe behavior.

---

## Designing Effective Policies

Good policies are:

- **Simple** - Each policy should enforce a single rule.
- **Predictable** - Similar requests should always produce the same outcome.
- **Explicit** - Avoid relying on implicit assumptions.
- **Reusable** - Write policies that can protect multiple methods when appropriate.
- **Version Controlled** - Store policies alongside your application code.

Rather than creating one large policy with dozens of nested conditions, prefer multiple focused policies that are easier to understand and maintain.

---

## Development vs Production

The same policy engine works in every environment.

During development, policies help catch mistakes before they reach external APIs.

In production, they become an additional security layer protecting critical systems and customer data.

A common workflow looks like this:

```text
Local Development
        │
        ▼
Sandbox Testing
        │
        ▼
Policy Validation
        │
        ▼
Production Deployment
```

Testing policies in sandbox mode before deploying to production helps ensure your application behaves as expected.

---

## Best Practices

- Keep policies under version control.
- Validate policies before deployment.
- Test new rules in sandbox environments, and try them in monitor mode first.
- Write tests for each policy and run `swy policy validate` in CI.
- Prefer allowlists over blocklists whenever possible.
- Review policies whenever new integrations are added.
- Keep production and sandbox configurations separate.
- Enable idempotency for mutating APIs.
- Audit policy changes as part of your code review process.

---

## Next Steps

- [Policy Rules](https://docs.swytchcode.com/policies/policy-rules/) - Learn how to write custom policies using conditions, operators, and actions to control tool execution.
- [Policy recipes](https://docs.swytchcode.com/policies/recipes/) - Ready-to-use policies for email, payments, data safety, and more.
- [Human approval](https://docs.swytchcode.com/policies/human-approval/) - Hold high-impact commands until someone approves in Slack.
- [Production Guardrails](https://docs.swytchcode.com/policies/production-guardrails/) - Discover recommended safeguards for deploying AI agents safely in production environments.
- [Best Practices](https://docs.swytchcode.com/policies/best-practices/) - Explore practical recommendations for designing maintainable, predictable, and secure policy configurations.
- [manifest.json](https://docs.swytchcode.com/configuration/manifest-json/) - Understand how tooling.json, policies.json, and manifest.json work together to control trusted execution.
