# Capabilities

> For agents: start with the [agent guide](https://ratstack.sh/llms.txt). Every page is Markdown by default; add `Accept: text/html` for HTML.

New on /news: [Foldkit 0.171.0 requires result Message schemas](/news).

## What it does

A capability is one named action with a contract and a server-side handler.
The contract declares the name, input, output, failure, and metadata. The handler implements the action on the server.

Effect is a library for describing work with typed failures and required services.
A service is a named interface for one job.
Schema describes accepted values, their TypeScript types, and the rules for checking and converting them at runtime.

`defineContract` declares input, output, and failure with Effect Schema.
It sets metadata describing the action, such as whether it is read-only, and any approval requirements.
`implement` connects the contract to one handler.

A projection builds a callable interface from a capability.
The projections in `packages/capability` provide:

- A command line.
- An HTTP API with OpenAPI, which describes its routes, inputs, outputs, and errors.
- MCP tools. Model Context Protocol lets an agent discover and call tools.
- RPC calls. Remote procedure call lets a client call a named server operation.
- Code mode, which combines capability calls in one program inside a restricted environment.
  See [one capability, every surface](/lore/one-capability-every-surface) for why.

The hosted registry includes content search and graph traversal, flags, prompts, CAFE news and profiles, learning, code mode, and `joinInterest`.
[`apps/site/src/capabilities/index.ts`](https://github.com/joelhooks/rat-stack/blob/main/apps/site/src/capabilities/index.ts) composes that registry.
[Live OpenAPI](/openapi.json) lists its HTTP operations. Optional feedback operations depend on the auth configuration.

The local command line projects the core registry in `apps/cli/src/surfaces.ts`.

## The standard

- Application actions exposed through generated routes, tools, and commands come from capabilities. Static pages, discovery documents, result pages, and protocol routing are composed separately. `Rpc.make`, `RpcGroup.make`, `HttpApi*`, `Tool.make`, and `Toolkit.make` outside `packages/capability` fail lint (`rat-stack-boundaries/no-hand-rolled-surface`).
- Input, output, and failure are Effect schemas. JSON Schema, OpenAPI, and the code-mode declarations are derived from them, never written by hand.
- Invalid input is rejected before the handler runs.
- A declared failure returns the declared error type. MCP returns it as a tool error.
- A capability that needs approval adds an `Approval` requirement and an `ApprovalDenied` failure on every interface. Approval is denied by default. HTTP answers a denial with 403.
- Browser code imports contracts only, never handlers (`rat-stack-boundaries/no-browser-server-imports`).
- Code mode reaches only capabilities, through their schemas.

## Code-mode discovery and execution

Code mode derives tool declarations from capability schemas.
The default discovery budget is 2,000 estimated tokens.
The estimate uses four characters per token.

Discovery selects the shortest declarations and gives each namespace a turn.
Namespace summaries mark the selected tools as `COMPLETE` or `PARTIAL`.

`catalogBudget` sets the budget.
`declarations: "inline"` includes all declarations; `"search"` includes none.
An explicit `catalogBudget` takes precedence over either setting.
The declarations resource always contains the full catalog.

Programs can call `tools.$codemode.search` to find declarations.
An exact tool path returns only that tool.
Other queries rank path segments, path substrings, descriptions, then input fields.

`limit` and `offset` bound each page.
`next` holds the next offset; `remaining` counts matching tools after this page.
`total` keeps its meaning as the full catalog size.

Successful execution returns `result`, `logs`, `toolCalls`, and `truncated`.
Failed execution raises the typed `ExecuteError` with `kind`, `message`, optional `tag`, `logs`, `toolCalls`, and `truncated`.
A declared tool failure retains its tag and a safe message.
Parse errors, invalid data, timeouts, and program failures all use this failure channel.

Host cancellation still interrupts execution.

The HTTP execute response uses status 200 for success and 422 for `ExecuteError`.
Failure bodies carry `_tag: "ExecuteError"` and have no `result`.
MCP reports `isError: true`, CLI exits non-zero, and RPC returns the typed failure.

Consumers of the old success-envelope `diagnostic` field must read the failure response instead.
Health checks require HTTP 422 and decode the complete failure schema.

`toolCalls` lists admitted calls in dispatch order, including failed calls.
`maxToolCalls` rejects extra calls before their handlers run.
Both sandbox adapters run at most eight tool calls at once.
`maxOutputBytes` bounds returned JSON and log content by UTF-8 bytes.

Output cuts set `truncated` and keep the diagnostic and call history.
The budget excludes diagnostic, call-history, and transport-envelope bytes.
Both limits are optional; zero is a valid limit.

Handlers keep the services captured when the program starts.
Devtools records each handler's duration and outcome through the existing `CallWatch`.
A downstream storage adapter owns its statement and row limits.

## How to check

- `curl -sS https://ratstack.sh/openapi.json | jq -r '.paths | keys[]'` lists the current HTTP operations. Compare them with MCP `tools/list` using the request in the [agent guide](/llms.txt). Do not assume a fixed capability count.
- `pnpm --filter @rat-stack/capability test` covers input rejection before the handler and typed failures as tool errors. It checks approval denial as a 403 and a typed tool error, denial by default, and code-mode calls through capability schemas.
- `pnpm lint` fails on any callable interface built outside `packages/capability`.
- `pnpm --filter @rat-stack/capability exec vitest run test/catalog.test.ts test/sandbox-limits.test.ts test/sandbox-conformance.test.ts test/code-mode-context.test.ts` checks discovery, search pages, limits, and captured services.
- `pnpm --filter @rat-stack/site exec vitest run test/code-mode-runtime.test.ts` checks the same diagnostics, limits, and concurrency in local workerd.
- `pnpm --filter @rat-stack/devtools test` checks handler duration and failure recording during code-mode execution.

## Removing an interface

The README's Keep or cut table lists the files for "No HTTP", "No MCP", and "No code mode." Cutting MCP cuts code mode, because code mode is built on the MCP toolkit.

## Sources

1. [rat-stack/packages/capability/src/contract.ts at main · joelhooks/rat-stack · GitHub](https://github.com/joelhooks/rat-stack/blob/main/packages/capability/src/contract.ts)
   GitHub joelhooks/rat-stack. Contract definition; used for schemas, annotations, and approval settings. Accessed 2026-10-01.

2. [rat-stack/packages/capability/src/implement.ts at main · joelhooks/rat-stack · GitHub](https://github.com/joelhooks/rat-stack/blob/main/packages/capability/src/implement.ts)
   GitHub joelhooks/rat-stack. Handler binding; used for schema validation and declared failures. Accessed 2026-10-01.

3. [rat-stack/apps/site/src/capabilities/index.ts at main · joelhooks/rat-stack · GitHub](https://github.com/joelhooks/rat-stack/blob/main/apps/site/src/capabilities/index.ts)
   GitHub joelhooks/rat-stack. Hosted registry; used to identify the capabilities served by ratstack.sh. Accessed 2026-10-01.

4. [rat-stack/apps/cli/src/surfaces.ts at main · joelhooks/rat-stack · GitHub](https://github.com/joelhooks/rat-stack/blob/main/apps/cli/src/surfaces.ts)
   GitHub joelhooks/rat-stack. CLI composition; used to show the local projections. Accessed 2026-10-01.

5. [rat-stack/packages/capability/test at main · joelhooks/rat-stack · GitHub](https://github.com/joelhooks/rat-stack/tree/main/packages/capability/test)
   GitHub joelhooks/rat-stack. Projection tests; used to check validation, approvals, and sandbox calls. Accessed 2026-10-01.

## Lore on this page

- [Handle expected failures without hiding defects](/lore/error-model)
- [MCP is another surface](/lore/mcp-is-another-surface)
- [One program can replace several tool calls](/lore/one-program-can-replace-several-tool-calls)
- [CAFE names the Cloudflare, Alchemy, Foldkit and Effect stack](/lore/cafe-stack)
- [OpenAPI describes the refusal too](/lore/openapi-describes-the-refusal-too)

## Linked from

- A browser send follows one path to the capability → In the Foldkit docs browser, a search is a Message, then an update, then a named Command that calls the search capability over RPC on a cache miss and returns a result Message. → [Read page](https://ratstack.sh/lore/a-browser-send-follows-one-path)

- A clean playground → rat-stack does real work with packages that stay easy to add and remove. → [Read page](https://ratstack.sh/lore/a-clean-playground)

- add-a-capability → Learn how one contract and its handler become a command, HTTP route, MCP tool, browser RPC, and sandbox call. → [Read page](https://ratstack.sh/skills/add-a-capability)

- add-a-feature-flag → Declare a typed feature flag, its scoped evidence ladder, approval roles, removal date, and durable ledger adapter. → [Read page](https://ratstack.sh/skills/add-a-feature-flag)

- Agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms.txt)

- Agent rules for rat-stack (AGENTS.md) → What you may change, which commands to run, and which changes need approval. → [Read page](https://ratstack.sh/AGENTS.md)

- An MCP your users want → Rhys Sullivan's practical guide gives rat-stack a checklist for useful MCP tools. → [Read page](https://ratstack.sh/lore/an-mcp-your-users-want)

- Build and run rat-stack (README.md) → What is in the repo, how the example works, and how to run it. → [Read page](https://ratstack.sh/README.md)

- CAFE all stars → Public profiles of people and channels who build with Cloudflare, Alchemy, Foldkit and Effect, served by five read-only capabilities. → [Read page](https://ratstack.sh/systems/all-stars)

- Change log → What changed in the files served here, newest first. → [Read page](https://ratstack.sh/log)

- Choose the check that can catch the failure → Use the testing ladder to choose between lint, types, behavior tests, runtime integration, and deployed checks. → [Read page](https://ratstack.sh/lore/testing-ladder)

- Cleanup can be an idempotent postcondition → Already-absent state can be success when absence is the operation’s intended result. → [Read page](https://ratstack.sh/lore/cleanup-can-be-an-idempotent-postcondition)

- durability → Keep a rat-stack app standing when a provider, pool, or dependency slows down or a worker dies. Use at any I/O boundary, connection pool, provider call, shared waiter, fan-out, flag, gate, or work that can outlive a request, or when asked "what happens when this is slow", "add a timeout", "make this durable", or "what survives a crash". → [Read page](https://ratstack.sh/skills/durability)

- Effect + Alchemy peer patterns → Source-grounded patterns from repos on nearby Effect and Alchemy pins. → [Read page](https://ratstack.sh/resources/same-version-repos)

- Feature flags → Typed feature flags with owners, removal dates, and stable subject rollouts. → [Read page](https://ratstack.sh/systems/flags)

- Flags climb on evidence → A flag ladder connects each rollout step to scoped measurements, approval, and a durable receipt. → [Read page](https://ratstack.sh/lore/flags-climb-on-evidence)

- Full agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms-full.txt)

- learn → Present Effect, Alchemy, XState, and application-design concepts during real work when the operator enables learn mode. Use for adaptive explanations and local learning progress. → [Read page](https://ratstack.sh/skills/learn)

- learn-rat-stack → Trace a capability through Effect, XState, five projections, the CLI, and Alchemy. Try hosted search and read. → [Read page](https://ratstack.sh/skills/learn-rat-stack)

- One capability, every surface → A schema-typed contract and one handler feed every interface rat-stack keeps. → [Read page](https://ratstack.sh/lore/one-capability-every-surface)

- One schema, three surfaces → A capability contract feeds CLI, HTTP, and MCP; OpenAPI is generated output, not their input. → [Read page](https://ratstack.sh/lore/one-schema-three-surfaces)

- Private catalog → An authenticated Alchemy Domain model records observations and decisions, with a replayable D1 index for trends. → [Read page](https://ratstack.sh/systems/catalog)

- Property tests for the UI with Bombadil → Check search counts and video consent with generated browser actions, then choose the right test layer for server races. → [Read page](https://ratstack.sh/resources/bombadil-ui-property-tests)

- Property-based testing → State a rule that must hold for every input, then let a generator search for a failing input. → [Read page](https://ratstack.sh/lore/property-based-testing)

- query-design → Design or review SQL reads, writes, scans, backfills, and slow database paths. Use before changing a store method or any loop that queries. Covers round-trip arithmetic, batching, keyset paging, index evidence, row budgets, PlanetScale Vitess limits, Hyperdrive connections, statement-count tests, and statement-template fences. → [Read page](https://ratstack.sh/skills/query-design)

- Rat Stack lore | rat-stack → Short, source-grounded notes on the ideas and decisions behind rat-stack. → [Read page](https://ratstack.sh/lore)

- Rat Stack systems | rat-stack → The systems rat-stack ships, the standard each keeps, and how to check it. → [Read page](https://ratstack.sh/systems)

- Run Effect at the integration boundary → Build the runtime where a calling framework enters, reuse its services, and dispose it when that integration ends. → [Read page](https://ratstack.sh/lore/run-effect-at-the-boundary)

- Schemas define the boundary → Define accepted data with Schema, decode unknown input before dispatch, and encode results through the declared contract. → [Read page](https://ratstack.sh/lore/schemas-define-the-boundary)

- Source change history (log.md) → The generated change log as Markdown. → [Read page](https://ratstack.sh/log.md)

## Unlinked mentions

- [A browser send follows one path to the capability](https://ratstack.sh/lore/a-browser-send-follows-one-path) → The contract is the one Schema set that the browser and the server share.¶

- [A cartridge owns one job and its resources](https://ratstack.sh/lore/cartridges) → See one capability, every surface for the shared contract and a clean playground for the house rule behind these boundaries.¶

- [A service captures its construction dependencies](https://ratstack.sh/lore/services-capture-dependencies) → rat-stack also uses capability projections, cartridge packages, and a no-comments rule.¶

- [add-a-capability](https://ratstack.sh/skills/add-a-capability) → A capability is one named action with a contract and a server-side handler.

- [add-a-lifecycle-machine](https://ratstack.sh/skills/add-a-lifecycle-machine) → watchActor does nothing until devtools runs the capability.

- [add-a-store](https://ratstack.sh/skills/add-a-store) → A capability is one named action with shared value definitions and a server-side implementation.¶

- [Agent rules for rat-stack (AGENTS.md)](https://ratstack.sh/AGENTS.md) → @rat-stack/auth/devtools adds runAsPerson, the dev-only rat\_test\_person capability, and testPersonLayer

- [An MCP your users want](https://ratstack.sh/lore/an-mcp-your-users-want) → rat-stack today: Each interface uses the same contract and handler.

- [Analytics](https://ratstack.sh/systems/analytics) → withEventCapture wraps the Worker’s fetch handler.¶

- [Auth](https://ratstack.sh/systems/auth) → A capability is one named action with shared value definitions and a server-side implementation.

- [Build and run rat-stack (README.md)](https://ratstack.sh/README.md) → Bind a server-side handler, then project the capability onto every agent surface.

- [CAFE names the Cloudflare, Alchemy, Foldkit and Effect stack](https://ratstack.sh/lore/cafe-stack) → rat-stack: One contract projected to RPC, HTTP, MCP, and CLI by packages/capability¶

- [Database](https://ratstack.sh/systems/database) → RunLog records a capability run with its outcome and lists a person’s recent runs.

- [Devtools](https://ratstack.sh/systems/devtools) → A capability is one named action with shared value definitions and a server-side handler, the code that implements it.

- [durability](https://ratstack.sh/skills/durability) → Passing an in-memory test does not prove the backend’s crash contract.¶

- [Effect + Alchemy peer patterns](https://ratstack.sh/resources/same-version-repos) → Keep capability schemas in packages/core, the toRpc projection in packages/capability, and UI atoms in the web app.

- [Effect basics](https://ratstack.sh/lore/effect-basics) → Handle expected failures without hiding defects shows the file error and its CLI handler.¶

- [Effect keeps the surfaces on one contract](https://ratstack.sh/lore/how-we-do-it-with-effect) → A projection builds an interface from a capability, a named action with a contract and handler.

- [Feature flags](https://ratstack.sh/systems/flags) → Climbs use the capability approval service.

- [Flags climb on evidence](https://ratstack.sh/lore/flags-climb-on-evidence) → off still passes through the shared capability implementation and attempt audit.

- [HATEOAS](https://ratstack.sh/lore/hateoas) → txt, the markdown variant, MCP responses, and capability responses.

- [Hexagonal architecture](https://ratstack.sh/lore/hexagonal-architecture) → Applications now use the agent-only joinInterest capability.

- [Hosted agent interfaces](https://ratstack.sh/systems/agent-front-door) → A capability is one named action with shared input, output, and failure definitions and a server-side implementation.¶

- [Infrastructure as effects](https://ratstack.sh/lore/infrastructure-as-effects) → Contract → surfaces: What the program checks: Shared input and failure schemas¶ Where to read more: One capability, every surface¶ ¶

- [Interest signup](https://ratstack.sh/systems/interest) → An agent applies for a person through the joinInterest capability.

- [keep-or-cut](https://ratstack.sh/skills/keep-or-cut) → A capability is one named action with a contract and a server-side handler.

- [Learn mode presents concepts at useful depths](https://ratstack.sh/systems/learn) → A capability is one named action with shared value definitions and a server-side implementation.

- [learn-alchemy](https://ratstack.sh/skills/learn-alchemy) → A capability is one named action with shared value definitions and a server-side implementation.¶

- [learn-rat-stack](https://ratstack.sh/skills/learn-rat-stack) → The command-line interface (CLI) projects capability lists for each server interface.

- [Lifecycles are machines](https://ratstack.sh/lore/lifecycles-are-machines) → See one capability, every surface for how a capability can own a machine and the fence for the rule that protects it.¶

- [Lint and type escape ledger (debt.md)](https://ratstack.sh/debt.md) → This is the sandbox’s way out, so input arrives untrusted and is parsed as JSON before any capability sees it.

- [MCP is another surface](https://ratstack.sh/lore/mcp-is-another-surface) → The job does not need a protocol-specific handler.¶

- [One capability, every surface](https://ratstack.sh/lore/one-capability-every-surface) → A capability is one named action with a contract and a server-side handler.

- [One program can replace several tool calls](https://ratstack.sh/lore/one-program-can-replace-several-tool-calls) → A capability is a named action with a typed contract and a handler.

- [One prompt serves people and agents](https://ratstack.sh/systems/prompts) → A capability is one named action with shared value definitions and a server-side implementation.

- [One schema, three surfaces](https://ratstack.sh/lore/one-schema-three-surfaces) → A capability is a named action with a contract and handler.

- [Oxlint rule limits](https://ratstack.sh/resources/lint-rule-limits) → It recognizes this template’s paths; package exports, conditions, and custom aliases need their own resolver contract.

- [profile-a-worker](https://ratstack.sh/skills/profile-a-worker) → A capture samples one isolate, and a cron or queue handler can run in a different one from the isolate serving fetch.

- [Purpose and boundaries of rat-stack (VISION.md)](https://ratstack.sh/VISION.md) → Capability and MCP next-action links are a direction to prove, not something the projections guarantee today.

- [query-design](https://ratstack.sh/skills/query-design) → Caller: Capability, scan, export, or background job¶

- [rat-stack-mode](https://ratstack.sh/skills/rat-stack-mode) → A capability is one named action with shared value definitions and a server-side implementation.

- [Run Effect at the integration boundary](https://ratstack.sh/lore/run-effect-at-the-boundary) → This module keeps only the handler; the excerpt does not prove explicit disposal on development-server shutdown.

- [Schema projections: 2026-09-18 history](https://ratstack.sh/resources/schema-projections-and-code-mode) → Deliberately compact MCP surface: search (discovery over Vectorize plus lexical) and execute (sandboxed capability calls).

- [Schemas define the boundary](https://ratstack.sh/lore/schemas-define-the-boundary) → A contract declares an action’s input, output, and failures.

- [security-audit](https://ratstack.sh/skills/security-audit) → If every control cannot be enforced, do not execute target code: report the missing sandbox capability as a needs-validation blocker and give a safe validation plan.¶

- [Shared caches hold completed values](https://ratstack.sh/lore/cache-completed-values) → Keep request-local work inside its request handler.¶

- [ShitRat's canon is an incident log](https://ratstack.sh/lore/shitrat-canon) → The patch runs the exact known migration first, retains the hold, and leaves release to separate validation under the current contract.

- [Structure an Effect codebase by domain](https://ratstack.sh/lore/structure-effect-by-domain) → Schema-backed boundaries: Capability contracts and derived interface projections¶

- [Tests prove behavior through supplied services](https://ratstack.sh/lore/tests-that-earn-their-place) → A capability is a named action; a projection converts it into an interface.¶

- [Trace operations where they mean something](https://ratstack.sh/lore/trace-meaningful-operations) → Devtools records capability calls and watched actor lifecycles.

- [Turbo remote cache](https://ratstack.sh/systems/turbo-cache) → The adapter adds no application capability or alternate agent route.¶

- [uncomplect](https://ratstack.sh/skills/uncomplect) → Capability: One named action with a contract and a server-side handler.¶

- [use-a-prompt](https://ratstack.sh/skills/use-a-prompt) → Call listPrompts through an available capability surface.¶

- [Worker init runs twice](https://ratstack.sh/lore/init-runs-twice) → The check now surrounds the rate-limit declarations and WorkerLoader declaration; the request-serving handler remains available at runtime.¶

- [write-a-wiki-page](https://ratstack.sh/skills/write-a-wiki-page) → A handler implements an action on the server.¶
