writ-mcp
Official# pywrit
**Find the dangerous writes in your Python agent's code, then gate it.** `pywrit` is the Python
client and `writ` CLI for [Writ](https://withwrit.com): an allow/deny gate that sits
in front of your agent's consequential writes (database, HTTP, files, email, queues,
AWS) and records a hash-chained receipt for every decision.
[](https://mcpservers.org/servers/avenuedadmin/pywrit)

`writ scan` is **local, deterministic, and free**: it parses your code with Python's
`ast` module, makes no network calls, and needs no API key.
After your first successful scan, the CLI prints a one-time line pointing at
this repo so you can star it (interactive terminals only, never in JSON or
piped output). `writ star` opens this repo in your browser at any time.
## Install
```bash
pip install pywrit
```
Requires Python 3.9+. Installs the `writ` command and the `pywrit` Python client.
**JavaScript/TypeScript devs:** run the scanner with no Python setup via npm:
```bash
npx writ-scan .
```
The `writ-scan` package wraps the same scanner (including TS/JS support). On
first run it installs `pywrit[polyglot]` from PyPI using your Python 3.9+
(one-time); afterwards it starts instantly. See [`npm/`](npm/) for details,
environment overrides (`WRIT_PYTHON`, `WRIT_SCAN_NO_INSTALL`), and the
install test.
## Language coverage
| Language | `writ scan` | `writ scan --apply` | Notes |
| --- | --- | --- | --- |
| Python | Yes | Yes, inserts `_writ_check` gates | Parsed with the stdlib `ast`, no extra needed |
| TypeScript / JavaScript | Yes, with `pywrit[polyglot]` | No, scan only | Needs the extra: `pip install 'pywrit[polyglot]'`. Without it, the report says so loudly: a warning block names the unscanned files instead of reporting zero findings |
| Go | Yes, with `pywrit[polyglot]` | No, scan only | First detection family plus request-pipeline Call/RawRequest, package-level generated clients, and GORM Raw raw-SQL writes: database/sql Exec/ExecContext, GORM Create/Save/Update/Updates/Delete/FirstOrCreate/CreateInBatches, HTTP client writes (Post/Put/Patch/Delete/PostForm, package-level and client method) and http.NewRequest with a write method, generated-client <client>.<Resource>.<New\|Update\|Delete\|Create>, request-pipeline X.Call/X.RawRequest with a write method, package-level generated clients <pkg>.<New\|Update\|Delete\|Create> on an imported resource-shaped package, GORM Raw `db.Raw` / `tx.Raw` with a write-first SQL string literal, including WITH-CTE writes. Go findings are product-code-only by default: writes under `docs/`, `scripts/`, `examples/`, `sandbox/`, `benchmark/`, `demo/`, `testdata/`, and in files carrying the standard Go codegen marker are suppressed by default and counted per class, restored with `--include-non-product`. Without the extra, the report names the unscanned Go files in the same warning block as TS/JS |
## 60-second quickstart: scan → wrap → gate
**1. Scan.** See which functions write, and how many of them are gated.
```bash
writ scan .
```
```text
writ scan: /path/to/support-agent
files scanned: 4 skipped: 0
write sites: 4 in 3 function(s)
gated: 0/4 (0%)
verbs discovered: 3
crm.update
payments.refund
tickets.close
```
It also prints a **risk report** (0-100, weighted by risk tier), writes the discovered
verbs to `writ-policy.json`, and shows the instrumentation it would add as a unified
diff. Nothing in your code changes yet. `writ scan . --score` prints just the risk report.
**2. Wrap.** One command takes the repo from unwrapped to wrapped: scan, show the diff,
ask for explicit approval, apply the gates, and report before/after coverage.
```bash
writ wrap . # interactive approval
writ wrap . --yes # no prompt (e.g. in CI)
```
`--dry-run` previews the plan and exits before prompting; `--diff-only` prints the
unified diff for review tools. Each gated function now asks Writ before it writes, and
fails closed:
```python
def issue_refund(charge_id, amount_cents):
if _writ_check("payments.refund") != "ALLOW":
raise PermissionError("writ denied payments.refund")
...
```
`writ scan . --apply` is still available as the manual alternative. Re-run `writ scan .`
and you'll see `gated: 4/4 (100%)`.
**3. Gate.** Get a free API key, load the discovered policy, and run your agent.
```bash
writ key --email you@example.com # free API key + tenant
export WRIT_API_KEY=writ_... # read by the inserted gate
export WRIT_SPONSOR=acme WRIT_AGENT=support-agent # optional: who is acting
writ scan . --push-policy --key "$WRIT_API_KEY" # upload the discovered verb policy
```
Every gated write now gets `ALLOW`, `DENY`, or `STEP_UP` (a human sponsor must
approve), and every decision is written to your tenant's tamper-evident audit log:
```bash
writ receipts --key "$WRIT_API_KEY" # latest receipts
writ verify-chain --key "$WRIT_API_KEY" # verify the receipt hash chain
writ stream --key "$WRIT_API_KEY" # tail decisions live
writ report --key "$WRIT_API_KEY" # Agent Action Report
```
## What `writ scan` detects
Python (`.py`) files, parsed with the stdlib `ast` (no extra dependencies):
| Category | Examples |
|---|---|
| Database | `cursor.execute(...)` / `executemany` / `executescript` (write SQL only; `SELECT`/`WITH`/... skipped), `session.add` / `commit` / `delete` / `merge` / `flush` |
| HTTP | `requests.post` / `put` / `patch`, `client.delete(...)`, `session.request(...)` |
| Files | `open(..., "w"/"a"/"x"/"+")`, `Path.write_text` / `write_bytes` / `unlink` / `rename`, `os.remove` / `rename` / `makedirs`, `shutil.rmtree` / `move` / `copy` |
| Email | `sendmail`, `send_message`, `send_email` |
| Queues | `publish`, `produce`, `enqueue`, `queue.send(...)` |
| AWS SDK | `put_object`, `put_item`, `delete_item`, `upload_file`, `send_message`, `start_execution`, ... |
- Each write is mapped to a verb such as `payments.refund` or `crm.update`, inferred
from the file path and function name. JS private methods keep their `#` out of the
verb, and a write inside a class `constructor` reports the kind fallback action.
- A function that already calls `writ_check(...)` / `_writ_check(...)` counts as gated.
- Skipped: tests, hidden directories, virtualenvs, `node_modules`, `dist`, `build`.
Use `--exclude SUBSTR` (repeatable) to skip more.
- Not covered (review by hand): writes behind dynamically built SQL, or shared clients
several layers down. The risk report lists these gaps every time.
### TypeScript / JavaScript (scan-only)
`writ scan` also finds write sites in TypeScript and JavaScript. It needs the
optional extra (tree-sitter based):
pip install 'pywrit[polyglot]'
writ scan .
Without the extra, the scanner prints a prominent warning block naming the
unscanned TS/JS files and keeps going — Python scanning never needs it.
Findings from non-product paths (docs/, scripts/, sandbox/, examples/,
benchmark/, demo/, test-harness directories (ecosystem-tests/, e2e/,
e2e-tests/, integration-tests/, test-harness/, test-harnesses/), and
build-tooling files such as gulpfile.js or webpack.config.*) are suppressed
by default: the report counts them per class and names every suppressed
path instead of listing them as findings.
Pass `--include-non-product` to report them like any other finding.
Every scan report ends with a one-line pointer to the Writ GitHub App
(install: https://github.com/apps/writ-scanner, guide:
https://docs.withwrit.com/git-hub-app), which runs the scan on every push
and pull request; the JSON report (`--format json`) carries the same
pointer under `github_app`.
TS/JS is **scan-only**: findings are listed with verbs for your policy file,
but `writ scan --apply` never rewrites TS/JS files — gate those by hand.
Covered patterns: `fetch`/`axios` writes, `fs` writes, SQL through knex-style
clients, Prisma writes, JS SDK calls such as `stripe.refunds.create(...)`, and
generated REST resource clients: `create` / `update` / `patch` / `remove`
methods (plus their `...WithHttpInfo` variants) that build request options
with an explicit write HTTP method and route them through the client request
pipeline (twilio-style generated clients, e.g. `twilio-node`), and
query-builder methods `insert` / `upsert` / `update` / `delete` that set a
write HTTP method and return a chainable builder (the postgrest-js shape).
Wrapped-client calls `this._client.post` / `put` / `patch` / `delete` (the
Stainless generated-SDK shape; `.get` reads stay silent).

### Go (scan-only)
`writ scan` also finds write sites in Go. It needs the optional extra (tree-sitter based):
pip install 'pywrit[polyglot]'
Covered in this first family plus request-pipeline and package-level generated-client detection: `database/sql` `Exec` / `ExecContext`, GORM `Create` / `Save` / `Update` / `Updates` / `Delete` / `FirstOrCreate` / `CreateInBatches` (a `FirstOrCreate` reads first and creates the row when the lookup misses; that conditional create is a write, and the GORM modifiers `Attrs` / `Assign` are not writes alone and stay off), HTTP client `Post` / `Put` / `Patch` / `Delete` / `PostForm` (package-level `http.PostForm(url, data)` and the client method `client.PostForm(url, data)`) and `http.NewRequest` / `NewRequestWithContext` with a write method, generated-client calls shaped `<client>.<Resource>.<New|Update|Delete|Create>` with an uppercase resource segment (the stripe-go shape), request-pipeline calls `X.Call(method, ...)` / `X.RawRequest(method, ...)` where argument 0 is a write method (the `stripe.Backend` shape, e.g. `c.B.Call(http.MethodPost, "/v1/accounts", ...)`), and package-level generated-client calls `<pkg>.<New|Update|Delete|Create>(...)` where `<pkg>` is imported in the file and the import path's last segment is resource-shaped, not structy (`params`, `config`, ...) and not service-, client-, library-, or test-double-shaped (`svc`, `service`, `client`, `api`, `sdk`, `internal`, `mock`, `fake`). This is the pre-v87 stripe-go shape (`charge.New(params)`), aliased imports included: the guard reads the import path, so `acmeinvoice "example.com/acme/acme-payments/invoice"` fires while `paymentsvc.New(cfg)` does not. GORM raw-SQL calls `db.Raw("INSERT INTO ...")` / `tx.Raw("DELETE FROM ...")` fire when argument 0 is a string literal (interpreted or backtick) whose first keyword is a write verb (INSERT, UPDATE, DELETE, REPLACE, TRUNCATE, MERGE), case-insensitive; a variable, a read-first literal (SELECT), or a Raw call on a non-db/tx receiver never fires. A leading WITH is graded past: the CTE list is parsed and the main statement's first keyword is graded the same way, so WITH ... DELETE / INSERT / UPDATE fires while WITH ... SELECT stays silent; a write verb inside a CTE query never decides the grade, and a malformed WITH grades as a read. GET/HEAD requests, `db.Query` / `QueryRow`, bare constructors (`.New` on a local variable or on an imported service- or structy-shaped package), and pipeline calls with a variable method or a non-method first argument are not flagged. `_test.go` files and `vendor/` trees are skipped. Go is **scan-only**: `writ scan --apply` never rewrites `.go` files, gate those by hand. Go coverage is also product-code-only by default, the same rule as TS/JS: write sites under `docs/`, `scripts/`, `examples/`, `sandbox/`, `benchmark/`, and `demo/` directories (matching by whole path segment at any depth, never filename substring, so `lib/demo-utils.go` stays product code), under any `testdata/` directory (the Go test-fixture convention), and in files carrying the standard Go codegen marker (a `// Code generated ... DO NOT EDIT.` line among the first 10 lines, the shape protoc, mockgen, sqlc, and stringer emit) parse as real writes but are not product behavior, so the scanner suppresses them from the findings list, reports a suppressed count per class, names every suppressed path, and records the same breakdown in the signed manifest as `findings.go.suppressedNonProduct`. The marker is the signal for generated code, not the filename: a file named `gen.go` with no marker stays product code. `--include-non-product` restores the full list. `_test.go` files, `vendor/` trees, and `tests/` / `testing/` directories are skipped entirely, not suppressed. Not yet covered: further verb coverage beyond this family and other Go write patterns. `FirstOrCreate` and `CreateInBatches` fire under the same handle rule as `Create` (a receiver chain segment that is or ends in `db` / `tx`), so either verb on a non-handle receiver stays silent. `PostForm` is an HTTP verb only: a `PostForm` on a receiver chain with no client-shaped segment never fires, and `POSTFORM` is not an HTTP method string, so a pipeline or `NewRequest` call with `"POSTFORM"` as the method argument stays silent.
## GitHub Action
Scan every pull request for ungated write sites. Findings land as check
annotations on the exact file and line, plus a Markdown risk report in the
job summary. The check fails when an ungated finding meets your
`fail-on-risk` threshold (default: `high`).
```yaml
- uses: actions/checkout@v4
- uses: withwrit/pywrit@v0
with:
fail-on-risk: high # high | medium | low | never
```
No API key needed. Full reference: [docs/github-action.md](docs/github-action.md) ·
example workflow: [examples/github-action/writ-scan.yml](examples/github-action/writ-scan.yml)
## GitHub App
Install the [Writ GitHub App](https://github.com/apps/writ-scanner) on selected
repositories: every push and pull request is scanned for ungated write-sites,
with results as a check run on the PR and in the
[portal](https://app.withwrit.com), where you manage policy, keys, and the audit log.
Setup and data handling: [GitHub App docs](https://docs.withwrit.com/git-hub-app).
## MCP server (`writ-mcp`)
Give any MCP-compatible agent point-of-action policy checks. `writ-mcp` is a
[Model Context Protocol](https://modelcontextprotocol.io) server (stdio transport,
built on the MCP Python SDK) that exposes the Writ gate as **29 MCP tools**:
the agent calls `writ_check` before a consequential write and gets back `ALLOW`,
`DENY`, or `STEP_UP` — with a tamper-evident, hash-chained audit receipt for
every decision.
```bash
uvx writ-mcp # no install — runs on demand
# or
pip install writ-mcp # then run `writ-mcp`
```
| Tool | What it does |
|---|---|
| `writ_check` | The gate: `ALLOW` / `DENY` / `STEP_UP` for a proposed write |
| `writ_verify_token` | Validate an `ALLOW` auth token (catches purpose drift) |
| `writ_lease` | Convert an `ALLOW` token into a single-use gated-execution lease |
| `writ_execute` | Run one gated upstream request with a lease or `ALLOW` token |
| `writ_grant` | Human-sponsor approval for the `STEP_UP` path |
| `writ_revoke` / `writ_reinstate` | The kill switch |
| `writ_receipts` | Read the tenant's audit log |
| `writ_verify_receipts` | Verify the audit-log hash chain |
| `writ_policy` | Read the verb policy |
| `writ_policies` | List the tenant default plus every environment and principal override |
| `writ_policy_env` | Read or set one environment's sparse policy override |
| `writ_policy_principal` | Read or set one principal's sparse policy override |
| `writ_sandbox` | Keyless 90-second demo grant — no API key needed |
| `writ_github_installations` | List connected GitHub App installations |
| `writ_github_set_threshold` | Set the check-run fail threshold per install |
| `writ_github_toggle_pr_comments` | Enable/disable the PR-comment bot |
| `writ_manifests` | List repos with risk profiles or fetch one manifest |
| `writ_scan` | Scan a local directory for consequential writes (Python, TS/JS, Go); no gate call, no API key |
| `writ_explain_receipt` | Explain a receipt in plain language |
| `writ_tenant_notify` | Get or update step-up notification settings |
| `writ_principals` | List the tenant's principals |
| `writ_verbs` | List the tenant's verb vocabulary |
| `writ_keys` | List API key metadata |
| `writ_me` | Who the API key belongs to: tenant, key email and plan, policy summary, monthly receipt usage |
| `writ_badge_token` | Mint a public README badge token |
| `writ_badge_revoke` | Revoke a badge token; its badge image URL 404s |
| `writ_tenant_invite` | Mint/rotate the tenant's one live team invite code (writ_inv_...) |
| `writ_join_tenant` | Join a tenant with an invite code; issues an API key, no key needed first |
The gate tools need a free Writ API key (`WRIT_API_KEY`): 10,000 receipts/month
free, no credit card. `writ_sandbox` works with no key at all.
The server implementation lives in [`mcp/`](mcp/) (MIT). Also published on the
official MCP Registry as `io.github.withwrit/writ` and listed on
[Glama](https://glama.ai/mcp/servers/withwrit/pywrit).
## Python client
```python
from pywrit import WritClient
client = WritClient(api_key="writ_...")
result = client.check(
sponsor_id="acme",
agent_id="agent-7",
verb="db.write",
target="prod.customers",
purpose="backfill region field",
)
if result.decision == "ALLOW":
# result.auth_token is a short-lived token bound to this exact write
perform_write(...)
elif result.decision == "STEP_UP":
# a human sponsor must approve first: client.grant(...), then re-check
...
else:
# DENY
...
```
No API key yet? Try the keyless sandbox:
```python
client = WritClient()
client.sandbox({
"sponsorId": "acme",
"agentId": "agent-7",
"verb": "demo_write", # sandbox only allows demo_write ...
"target": "demo-customers", # ... on targets starting with demo-
"purpose": "trying the gate",
})
```
What's covered:
- `check(...)`: the gate. `ALLOW` / `DENY` / `STEP_UP`, plus a receipt every time
- `verify_token(...)`: validate an `ALLOW` auth token (catches purpose drift)
- `grant(...)`: human-sponsor approval for the `STEP_UP` path
- `get_policy()` / `set_policy(...)`: manage the tenant policy
- `revoke(...)` / `reinstate(...)` / `revoked()`: the kill switch
- `receipts()` / `receipt(id)` / `verify_chain()` / `stream_receipts()`: the audit log
- `sandbox(...)`: keyless trial, no API key required
## CLI reference
```bash
writ wrap . # scan, diff, approve, apply, verify coverage
writ wrap . --dry-run # preview only
writ wrap . --yes # non-interactive CI mode
writ check --key writ_... --sponsor acme --agent agent-7 \
--verb db.write --target prod.customers --purpose "backfill region field"
writ policy --key writ_... --set payments.refund require_grant
writ revoke --sponsor acme --agent agent-7 --reason "runaway loop" # kill switch (sponsor token)
writ grant --sponsor acme --agent agent-7 --verb payments.refund \
--target ch_123 --purpose "approved refund" # STEP_UP approval (sponsor token)
```
Sponsor-token commands (`revoke`, `reinstate`, `revoked`, `grant`) read
`--sponsor-token` or `WRIT_SPONSOR_TOKEN`. Run `writ --help` for the full command list.
## README badge
Show that your agent's writes are gated by Writ. Two flavors:
**Static** (works today, no API key) — same design, no live count:
```md
[](https://withwrit.com)
```
**Dynamic** (live 30-day gated-write count from your audit log) — mint a badge
token, then embed the snippet the API returns:
```bash
curl -s https://api.withwrit.com/v1/badge/tokens \
-H "Authorization: Bearer writ_..." \
-H "Content-Type: application/json" \
-d '{}'
```
The dynamic endpoint is live: `POST /v1/badge/tokens` mints a token and returns the embed snippet. The static badge above still works with no key.
See [`badge/`](badge/) for embed docs and the verification model (what the
badge proves — and what it doesn't).
## Docs
Full docs: [docs.withwrit.com](https://docs.withwrit.com) ·
Quickstart: [docs.withwrit.com/quickstart](https://docs.withwrit.com/quickstart) ·
Site: [withwrit.com](https://withwrit.com)
## License
MIT
TDQS
Scored across 29 tools
Most tools map to distinct resources or steps (check, verify_token, lease, execute form a clear chain), but writ_policy and writ_policies both read policy and are easy to confuse. The dual-mode read/write tools (writ_policy_env, writ_policy_principal) also blur whether they read or mutate.
All tools use a consistent writ_ snake_case prefix, which is predictable. There is a minor mix of noun-style (writ_policies, writ_keys, writ_verbs) and verb-style (writ_check, writ_execute) names, but within each functional group it is coherent.
29 tools is on the heavy side, exceeding the 16-25 'feels heavy' band. The breadth is justified by covering policy, enforcement, audit, GitHub integration, badges, and team management, but the surface is large enough to feel sprawling for an agent.
The authorization lifecycle is well covered: check, verify, lease, execute, grant/revoke/reinstate, receipts plus chain verification, and three policy layers. Minor gaps remain, such as no explicit API-key revocation or principal creation/removal tools.