--- title: Develop an Agent with FastAgent description: "Complete executable playbook for coding agents (Claude Code, Codex, Cursor, Pi) and engineers to design, build, unit-test, gate, and ship a production FastAgent." status: current --- # Develop an Agent with FastAgent Executable end-to-end workflow for **coding agents** (Claude Code, Codex, Cursor, Pi) and human engineers. Every step ends with a deterministic, non-interactive CLI check (`exit 0` pass, `exit 1` runtime/check failure, `exit 2` missing flag or human action required). ```text scope & boundaries → scaffold / adopt → prompts, skills, tools & config → unit test → info & build --json → live invoke & interrupt check → deploy check --json ``` ## 1. Map responsibilities to files Never invent framework glue. Reuse an existing agent directory if `fastagent.config.ts`, `AGENTS.md`, or `SYSTEM.md` is already present. | Concern | File | Rules | | --- | --- | --- | | Identity, goal, approval boundaries | `SYSTEM.md` & `AGENTS.md` | Re-read on every turn; never hardcode secrets | | Reusable domain playbooks | `skills//SKILL.md` | AAIF frontmatter (`name` matching folder, `description` ≤ 1024 chars); progressive load | | Slash prompt templates | `prompts/.md` | Expanded when a message starts with `/` | | Typed in-process tools | `src/tools/.ts` | Default-export `defineTool(...)` (optionally wrapped in `needs([...], fn)`). Put shared helpers in `lib/`, never directly in `src/tools/` | | External MCP servers | `.mcp.json` or `fastagent.config.ts` | Use `${SECRET_NAME}` placeholders for headers/env; gate mutating tools with `requiresApproval` | | Runtime settings | `fastagent.config.ts` | Default-export `defineAgent({ model, harness, sandbox, codingTools, codemode, providers, mcpServers, starters })` | ### Choose isolation & tool batching up front - **Tool-only / embedded SaaS agent:** Set `codingTools: false`. - **File/shell agent in local or read-only mode:** Set `codingTools: ["read", "bash"]` and `sandbox: "read-only"` (or `"workspace"`). - **Multi-tenant untrusted code execution:** Offload coding tools to a cloud MicroVM (`sandbox: "e2b"` / `"vercel"` / `"modal"` / `"opensandbox"` / `"cloudflare"`). - **Data-heavy multi-hop read/filter workflows:** Set `codemode: true` so the model batches parallel non-interactive calls in QuickJS-WASM while keeping `requiresApproval` mutations as top-level calls. ## 2. Scaffold or adopt the directory ```bash npm create fastagent@latest my-agent -- --no-input cd my-agent ``` - Adopting an existing folder in place: `npx @fastagent-sh/fastagent init . --no-input` (preserves existing `AGENTS.md`, `SYSTEM.md`, `skills/`, `.mcp.json`, and `src/`). - Always run CLI commands via `npx @fastagent-sh/fastagent ` or `pnpm exec fastagent ` (never `npx fastagent`). - Use `.ts` extensions on relative imports (`../../lib/batches.ts`) and `import type` for type-only imports (`verbatimModuleSyntax` + erasable TypeScript syntax only: no `enum`, `namespace`, or parameter properties). - Install TypeScript and Node types for offline type-checking and zero-dependency `node:test` unit tests: ```bash npm install --save-dev typescript @types/node npm pkg set 'scripts.typecheck=tsc --noEmit' 'scripts.test=node --test test/*.test.ts' mkdir -p lib test skills/review-batches src/tools ``` **`tsconfig.json`** ```json { "compilerOptions": { "target": "ES2025", "module": "NodeNext", "strict": true, "noEmit": true, "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "erasableSyntaxOnly": true, "skipLibCheck": true, "types": ["node"] }, "include": ["src/**/*.ts", "lib/**/*.ts", "test/**/*.ts", "fastagent.config.ts"] } ``` ## 3. Author configuration, skills, and tools ### `fastagent.config.ts` (including custom OpenAI-compatible gateways & `codemode`) ```ts import { defineAgent, defineOpenAICompatibleProvider, needs } from "@fastagent-sh/fastagent"; export default defineAgent({ model: "anthropic/claude-sonnet-4-6", codingTools: false, codemode: true, // optional: QuickJS-WASM batching/filtering for non-interactive tools starters: ["Audit open enterprise renewals"], // Optional: custom vLLM / Ollama / LiteLLM gateway (no @earendil-works/pi-ai dependency needed) providers: [ needs(["INTERNAL_GW_KEY"], ({ INTERNAL_GW_KEY }) => defineOpenAICompatibleProvider({ id: "internal-gw", baseUrl: "https://llm.internal.example.com/v1", apiKey: INTERNAL_GW_KEY, models: [{ id: "qwen-coder-32b", contextWindow: 131072, maxTokens: 8192 }], }), ), ], }); ``` *(For unauthenticated local gateways such as `http://127.0.0.1:11434/v1`, omit `apiKey` and `needs()`.)* ### `src/tools/` (`defineTool`, `needs()`, `requiresApproval`, and `api.requestInput`) 1. **Read-only tool with `needs()` secret declaration** (callable both directly and inside `codemode` scripts): ```ts // src/tools/lookup-account.ts import { defineTool, needs } from "@fastagent-sh/fastagent"; export default needs(["CRM_API_KEY"], ({ CRM_API_KEY }) => defineTool({ name: "lookup_account", description: "Fetch account ARR and renewal date by account ID.", parameters: { type: "object", properties: { accountId: { type: "string" } }, required: ["accountId"], additionalProperties: false, } as const, async execute({ accountId }) { // Call external API using CRM_API_KEY return JSON.stringify({ accountId, arrUsd: 48_000, keyLoaded: CRM_API_KEY.length > 0 }); }, }), ); ``` 2. **Mutating / interactive tool with `requiresApproval` or `api.requestInput()`** (`api.requestInput` is required on `ToolExecutionApi`—call it directly without `?.`): ```ts // src/tools/apply-discount.ts import { defineTool } from "@fastagent-sh/fastagent"; export default defineTool({ name: "apply_discount", description: "Apply a renewal discount percentage to an account.", parameters: { type: "object", properties: { accountId: { type: "string" }, percent: { type: "number", minimum: 1, maximum: 50 }, }, required: ["accountId", "percent"], additionalProperties: false, } as const, requiresApproval: ({ accountId, percent }) => percent > 15 ? { summary: `Approve ${percent}% discount for ${accountId}`, includeArgs: true, policy: { ruleId: "renewal-discount", ruleVersion: "v1", requiredRole: "revops" }, } : false, async execute({ accountId, percent }, api) { if (percent > 30) { const note = await api.requestInput({ prompt: "Provide executive deal-desk justification", schema: { type: "object", properties: { justification: { type: "string" } }, required: ["justification"], additionalProperties: false, } as const, }); return `Applied ${percent}% to ${accountId} (${note.justification})`; } return `Applied ${percent}% to ${accountId}`; }, }); ``` ## 4. Worked offline example & unit test (`ToolInvocationApi`) Below is a complete, credential-free agent (`SYSTEM.md` + `SKILL.md` + `lib/` helper + `defineTool` + `node:test` unit test using `ToolInvocationApi`) that type-checks and runs completely offline: **`SYSTEM.md`** ```markdown # Review assistant Help the owner review project proposals in manageable batches. Separate evidence from assumptions, use `review-batches` when planning a review, and call `plan-batches` for exact batch counts. ``` **`skills/review-batches/SKILL.md`** ```markdown --- name: review-batches description: Plan manageable batches when the owner asks to review a set of proposals. --- Confirm which proposals are in scope and the preferred batch size. Call `plan-batches` for the count, group related proposals, and present a draft plan before any external action. ``` **`lib/batches.ts`** ```ts export function batchCount(items: number, size: number): number { return Math.ceil(items / size); } ``` **`src/tools/plan-batches.ts`** ```ts import { defineTool } from "@fastagent-sh/fastagent"; import { batchCount } from "../../lib/batches.ts"; export default defineTool({ name: "plan-batches", description: "Count review batches for a non-negative item count and a positive batch size.", parameters: { type: "object", properties: { items: { type: "integer", minimum: 0 }, size: { type: "integer", minimum: 1 }, }, required: ["items", "size"], additionalProperties: false, } as const, execute: async ({ items, size }) => JSON.stringify({ batches: batchCount(items, size) }), }); ``` **`test/batches.test.ts`** *(For `needs([...], fn)` tools like `lookup-account.ts` above, call `lookupFactory.build({ CRM_API_KEY: "test-key" })` first to obtain the `PortableTool`.)* ```ts import assert from "node:assert/strict"; import { test } from "node:test"; import type { ToolInvocationApi } from "@fastagent-sh/fastagent"; import { batchCount } from "../lib/batches.ts"; import planBatches from "../src/tools/plan-batches.ts"; const stubApi: ToolInvocationApi = { output: () => {}, executeTool: async () => ({}), }; test("batch planning calculates counts, and the tool answers with them", async () => { assert.equal(batchCount(5, 2), 3); const result = await planBatches.execute({ items: 5, size: 2 }, stubApi, { sessionId: "ses_test" }); assert.deepEqual(result.output, [{ type: "text", text: '{"batches":3}' }]); }); ``` ## 5. Run deterministic verification gates Run these commands in order before reporting completion: ```bash # 1. Type-check src/, lib/, test/, and fastagent.config.ts npm run typecheck # 2. Run offline unit tests npm test # 3. Inspect resolved tools, skills, MCP servers, codemode, and required secrets (read-only) npx @fastagent-sh/fastagent info --json # 4. Compile and emit immutable SemVer package in dist/ npx @fastagent-sh/fastagent build --json # 5. Check model-provider auth readiness without blocking on a terminal npx @fastagent-sh/fastagent login anthropic/claude-sonnet-4-6 --check --json ``` - **Never ask the human to paste API keys into chat.** If `info --json` reports `unsetSecrets` or `login --check --json` exits `1` (`not_ready`), instruct the human to set secrets in `.env` or run `npx @fastagent-sh/fastagent login` in their own terminal, then re-run `--check`. - When credentials are ready, smoke-test live execution (note: if a tool hits `requiresApproval` or `requestInput`, `invoke` exits `2` immediately and prints `{ "type": "unfinished", ... }` in `--json` mode—resolve it with `fastagent interrupt approve|submit`): ```bash npx @fastagent-sh/fastagent invoke --no-input --json "Look up acc_1" ``` ## 6. Prepare deployment & leak checks ```bash # Optional: scaffold Dockerfile / .dockerignore / fly.toml / compose.yml npx @fastagent-sh/fastagent deploy init docker # Verify zero .env*, .fastagent/, or .state/ files can leak into the container build context npx @fastagent-sh/fastagent deploy check --json ``` See [Deploy](deploy.md) for stateless PostgreSQL containers, Fly.io / Railway scale-to-zero, and AWS Bedrock AgentCore, or [Frontend & multi-agent protocols](protocols.md) to expose `useChat()`, `AG-UI 1.0`, and `A2A 1.0`.