Skip to content

Tools

Author typed extension tools with @buildr/sdk, choose repo scopes, and call the Forge API as the caller.

Updated

An extension’s index.ts defines its public interface as tools using the @buildr/sdk module. The repo that defines an extension calls its tools on any branch, main included, at the version that the branch’s head commit publishes. Releasing distributes a version to other repos, which call its tools through their installation, with the HTTP API, the forge CLI, or the MCP server’s tools["<repo slug>.<name>"].<repoId>.<tool> namespace.

Tool definitions in index.ts

Every extension with code has an index.ts at its root whose default export comes from defineExtension(requirements, definition). You define each tool with tool(options, handler) and group them into a flat or nested tools object:

import {
  array,
  boolean,
  defineExtension,
  integer,
  literal,
  number,
  object,
  record,
  string,
  tool,
} from "@buildr/sdk";

const LineItemSummary = object({
  id: string().describe("The line item record ID"),
  description: string().nullable(),
  amountCents: integer(),
});

export default defineExtension(
  {},
  {
    tools: {
      orders: {
        summarize: tool(
          {
            description: "Lists line items above a minimum cent threshold",
            input: object({
              minAmountCents: integer().optional().describe("Minimum amount in cents"),
              status: literal("draft", "approved").optional(),
            }),
            output: array(LineItemSummary),
          },
          async (ctx, { minAmountCents = 0 }) => {
            const page = (await ctx.forge.customRecords.searchRepoCustomRecordsAtBranch({
              repo_id: ctx.repo.id,
              branch: ctx.branch,
              model_api_name: "procurement__line_item",
              body: { where: { field: "amount", op: "gte", value: minAmountCents } },
            })) as {
              data: ReadonlyArray<{
                id: string;
                fields: { description?: string | null; amount?: number | null };
              }>;
            };
            return page.data.map((row) => ({
              id: row.id,
              description: row.fields.description ?? null,
              amountCents: row.fields.amount ?? 0,
            }));
          },
        ),
      },
    },
  },
);

Nesting tools inside objects groups their names with dots. In the example above, orders.summarize is the tool’s name when listing or calling it.

A tool takes three options: description, input, and the optional output. Any other option, such as a misspelled one, is refused when the extension loads, with an error that names it. Every other builder refuses an option it doesn’t take the same way, from openapiTools, workflow, cron, webhook, and room to defineExtension and defineProvider.

Value types for inputs and outputs

@buildr/sdk provides schema builders that validate tool inputs before the handler runs, validate the handler’s return value when output is specified, and generate the JSON Schema and TypeScript declarations shown by the API and MCP’s search tool:

Builder TypeScript type Description
string() string Any UTF-8 string
number() number Any finite floating-point or integer number
integer() number Any safe whole number
boolean() boolean true or false
literal("a", "b") "a" | "b" Exact string, number, or boolean literal union
array(itemType) ReadonlyArray<T> Array whose elements match itemType
record(valueType) Readonly<Record<string, T>> Object with arbitrary string keys and values matching valueType
object({ key: type }) { readonly key: T } Closed struct with exact keys (excess properties in input are refused)
json() Json Any valid JSON value without structural checks

Every ValueType<T> supports three modifiers, which chain in any order, so string().optional().describe("Note") and string().describe("Note").optional() are the same value type:

  • .describe(text): Annotates the value or object property in JSON Schema and MCP declarations.
  • .nullable(): Accepts T | null.
  • .optional(): Marks an object({...}) property as optional so callers may omit the key.

You can extract the TypeScript type of any value type using the Infer<typeof MyType> type helper exported by @buildr/sdk.

Tool context (ctx)

A tool handler receives (ctx, input). The ctx object provides:

  • ctx.orgId: The ID of the organization (org_…).
  • ctx.principal: Who asked for the call. { kind: "member", user: { id } } for a person’s own call, { kind: "automation" } for a call that no person asked for just then, such as a schedule’s, trigger’s, webhook’s, or mailbox’s run, or { kind: "guest" } for a call from a public share of the extension’s UI.
  • ctx.actingAs: Whose access ctx.forge uses. { kind: "member", userId } when a member calls, or { kind: "extension", name } when an automation or a guest acts as the extension itself.
  • ctx.extension.sourceRepoId: The ID of the repo that defines the extension (repo_…).
  • ctx.branch: The branch whose data and tools the code works with: the branch a call names in the repo that defines the extension, or "main" for a call on an installation, which is the installing repo’s main. A background run’s ctx.branch is its own branch. A UI’s page reads the same value as context.branch.
  • ctx.repo.id: The repo that the call runs in and acts on. See Where a tool runs.
  • ctx.forge: A client for the Forge API that runs as ctx.actingAs says (ctx.forge.<group>.<operation>(input)).
  • ctx.org.connections: Connections bound to the extension’s org requirements, keyed by requirement name.
  • ctx.user.connections: The calling user’s own connections bound to the extension’s user requirements, keyed by requirement name.
  • ctx.workflows: Provides ctx.workflows.start(workflowName, input, { key }) to start a durable workflow run, which runs the version the tool ran on the branch it read, as whoever started it, and ctx.workflows.signal({ run, signal, payload }) to answer a run’s signal wait.
  • ctx.browser: A headless browser that reads rendered web pages and saves screenshots and PDFs as attachments. See Web pages with ctx.browser.
  • ctx.email: Sends email from Forge’s no-reply address. See Email with ctx.email.
  • ctx.systemOne: Asks a System One model typed questions about a state. See System One models with ctx.systemOne.
  • ctx.rooms: Broadcasts to the extension’s realtime rooms (ctx.rooms.<name>(params).broadcast(data)). See Streams and rooms.
  • ctx.events: Publishes extension events into the repo’s event log (ctx.events.publish(name, data, { branch })). Publishing an event and broadcasting into a room both take update on the extension, which neither the default Editor policy nor an extension’s built-in policy grants. See Streams and rooms.

Forge API calls with ctx.forge

ctx.forge exposes the exact same <group>.<operation>(input) methods as the MCP execute sandbox. Every call through ctx.forge is authorized as ctx.actingAs, which is the calling member for a member’s call, or the extension itself for an automation or a public share’s guest:

  • For a member’s call, the tool cannot read or write a repo unless that member is allowed to by the org’s policies. For an automation or guest call, policies must allow the extension itself.
  • If an API call fails, the promise rejects with a ForgeError (exported from @buildr/sdk), which carries operation (such as "forge.commits.createRepoCommit"), status (the HTTP status code), and error (the tagged error JSON body).
  • Request bodies and query parameters are strict: a key or parameter the operation doesn’t declare is refused with 400 InvalidRequest, never ignored. Send only the fields an operation takes; for example, don’t spread a record you read (with its id and formulas) into an update’s body.

An operation’s input is one object: the path and query parameters by name, such as repo_id, branch, and record_id, and the request body, when the operation takes one, as body. It resolves to the response body. In TypeScript, @buildr/sdk types each ctx.forge operation as taking a JsonObject (so omit optional keys instead of passing undefined) and resolving to Json; cast or narrow the result to the response shape listed in the API reference or MCP search.

These operations read, change, and commit records, which is what most tools do:

To Call Resolves to
List a model’s records in working state customRecords.listRepoCustomRecordsAtBranch({ repo_id, branch, model_api_name, cursor?, limit? }) { data, next_cursor }, each record as { id, fields, … }
List a model’s records at a commit customRecords.listRepoCustomRecordsAtCommit({ repo_id, commit_id, model_api_name, cursor?, limit? }) The same page, as the commit saved them
Create a record customRecords.createRepoCustomRecord({ repo_id, branch, model_api_name, body: { fields } }) The record
Change some of a record’s custom field values customRecords.updateRepoCustomRecord({ repo_id, branch, record_id, body: { fields } }) The record
Delete a record customRecords.deleteRepoCustomRecord({ repo_id, branch, record_id }) Nothing
Commit the branch’s working state commits.createRepoCommit({ repo_id, branch, body: { message } }) The commit, with its id
Read a branch, and its head commit as head_commit_id branches.getRepoBranch({ repo_id, branch }) The branch
Read the caller users.getUser({}) { id, display_name, email, … }
Create or update records by a unique custom field customRecords.upsertRepoCustomRecords({ repo_id, branch, model_api_name, match_on, body: { records } }) { data }, each row in order as { action, record }, where action is "created" or "updated" and record is { id, fields, … }
Find a tag by its family and name tags.listRepoTagFamiliesAtBranch({ repo_id, branch }), then tags.listRepoTagsAtBranch({ repo_id, branch, family_id }) The families, each with id and name, then the family’s tags, each with id and name
Tag a record, or take a tag off tags.createRepoRecordTag({ repo_id, branch, record_id, tag_id }), or tags.deleteRepoRecordTag with the same input Nothing
List a record’s tags tags.listRepoRecordTagsAtBranch({ repo_id, branch, record_id }) Each tag

No operation reads one record by its ID. To act on one record, page through listRepoCustomRecordsAtBranch until you find it, or search with customRecords.searchRepoCustomRecordsAtBranch on a unique custom field that it holds.

A write changes the branch’s working state and nothing else. Other members, other branches, and reads at a commit don’t see it until a commit saves it, so a tool that changes records and means them to last commits them with commits.createRepoCommit. fields holds custom field values by API name, in the same JSON as the API: a picklist value is one of the custom field’s options, such as "closed", and a multi_picklist value is an array of them. See Schema and records for every type.

const close = tool(
  {
    description: "Closes a company and commits the change",
    input: object({ id: string() }),
  },
  async (ctx, { id }) => {
    const where = { repo_id: ctx.repo.id, branch: ctx.branch };
    await ctx.forge.customRecords.updateRepoCustomRecord({
      ...where,
      record_id: id,
      body: { fields: { status: "closed" } },
    });
    const commit = (await ctx.forge.commits.createRepoCommit({
      ...where,
      body: { message: "Close a company" },
    })) as { id: string };
    return { commit_id: commit.id };
  },
);

Where a background run writes

A tool that a schedule, a trigger, a webhook, or a mailbox runs, and every workflow run, works on a branch of its own, cut from the head of the branch it runs on, and ctx.branch names it. Write to ctx.branch (s.branch in a workflow step): it holds what the branch had committed when the run began, plus the run’s own writes, but none of the edits members haven’t committed yet. Branch lists don’t show a run’s branch.

  • It writes only its own branch: A write that names any other branch, in this repo or another, such as branch: "main", is refused with RunBranchRequired, so a run never commits members’ uncommitted edits. It still reads any branch, including the one it merges into, but only at that branch’s head commit: it sees what members committed, never their uncommitted edits. Only its own branch reads with its uncommitted writes. Only the run reaches its own branch: any other request that names it is refused with Forbidden.
  • A run that succeeds merges: Forge merges what the run committed into the branch it runs on, as the extension.
  • What it leaves uncommitted is dropped: When the run ends, Forge discards whatever it wrote and didn’t commit. A workflow’s steps share the run’s branch, so a later step reads what an earlier one wrote.
  • A run that fails merges nothing: A run that fails or is interrupted, or a workflow run that errors or is terminated, ends its branch without merging.
  • Members’ uncommitted edits stay theirs: The run merges into its branch under members’ uncommitted edits there and leaves them uncommitted on top of its commit. When those edits touch a record the run changed, the run’s changes would leave them invalid, such as a new tag in a family the run deleted, or the merge conflicts, the run fails, leaves the branch as it was, and its error says why. Commit or discard the edits, then run it again.

A tool a member calls directly writes on the branch it names, as that member would.

Read an attached file

An attachment custom field gives a tool the file’s metadata, not its bytes. To read the bytes, ask for a signed URL and fetch it. A tool needs no connection for this, because the API checks the caller’s read access when it signs the URL:

const download = (await ctx.forge.attachmentBlobs.getRepoAttachmentBlobDownload({
  repo_id: ctx.repo.id,
  attachment_blob_id: file.id,
})) as { url: string };
const response = await fetch(download.url);
const bytes = await response.arrayBuffer();

A signed URL lasts five minutes, so request it right before you read the file. Attachment storage accepts only GET and HEAD from a tool, and each read counts toward the run’s outbound fetch limit.

Tools from an OpenAPI document

openapiTools(options) defines a tool for each operation of an OpenAPI 3 document that you name, of any method, so you don’t write a tool for each endpoint of a large API. Spread what it returns into tools:

import { defineExtension, defineProvider, openapiTools } from "@buildr/sdk";
import { document } from "./openapi.ts";

const acme = defineProvider({ name: "Acme", hosts: ["api.acme.example"], auth: { /* ... */ } });

export default defineExtension(
  { user: { connections: { acme } } },
  {
    tools: {
      ...openapiTools({
        document,
        tools: {
          "projects.list": "GET /v1/projects",
          "projects.get": "GET /v1/projects/{project_id}",
          "projects.create": "POST /v1/projects",
        },
        connection: (ctx) => ctx.user.connections.acme,
      }),
    },
  },
);

Each tool’s input holds its operation’s parameters. Path, query, and header parameters become camelCase fields, such as projectId for {project_id}. A bracketed query parameter such as filters[status] becomes a field of its group, as filters: { status }, and an array in the query is sent as filters[status][]=… once per item. A parameter that accepts one value or an array of them takes an array. An operation’s JSON request body is the body field, with the document’s property names, and its schema follows the document’s schema components, recursive ones included. A call sends the connection’s credentials and answers the response’s body: its JSON, its text when it isn’t JSON, or null when it’s empty. A failing status fails the call with the status and the start of the body.

The options are:

  • document: The OpenAPI document, or the part of it that holds the operations you name. Keep only those operations in the extension, since source files total at most 8 MiB. Rather than cut it yourself, import the document with createOrgOpenApiImport and write the extension’s files with createOrgOpenApiImportExtensionFiles. Forge fetches the document from its URL and writes openapi.ts, which exports tools and document, and an index.ts that declares a provider for the document’s security schemes and turns every tool into the extension’s. It names each tool for its operation’s tag and operation id. It takes every operation, up to 500, or those with the tags, path prefixes, or operations you pass.
  • tools: Each tool’s dotted name, to the operation’s method and path, such as POST /v1/projects. An operation whose required body isn’t JSON is refused when the extension loads, since a tool sends JSON only.
  • connection: Picks the connection whose credentials each call sends, from the call’s ctx.
  • origin: Optional. Picks the origin each call goes to, from the connection, such as a sandbox host for a sandbox sign-in method. The document’s first server by default, unless its host is a placeholder, such as Jira’s your-domain.atlassian.net or {tenant}.vendor.io: then openapiTools throws as the extension loads, because that host may be someone else’s.
  • shared: Optional. Inputs that fill several parameters at once, by their names in the document, such as { companyId: { parameters: ["Procore-Company-Id", "company_id"] } } for an API that reads the same company from a header and a query parameter.
  • result: Optional. Shapes what a call answers from the JSON body and the Response, such as a page of results with the next page’s number from a Link header.

Where a tool runs

Every tool runs wherever its extension runs, and acts on the repo that the call runs in, which its handler reads as ctx.repo.id:

Called ctx.repo.id Version that runs
On a branch of the defining repo The defining repo What the branch’s head commit publishes
On an installation, by a member, a schedule, a trigger, a webhook, a mailbox, a UI, or a dependent extension through peerTools The installing repo The release that the installing repo’s main pins
On a service, by anyone in the org through callOrgExtensionServiceTool or serviceTools The defining repo What the defining repo’s main head commit publishes

Installed code acts on the installing repo’s own records, including its copies of the extension’s models. It never reaches into the defining repo. Who may call a tool is up to the org’s policies, through call on the tool (Actions). The default Editor policy doesn’t grant call, so until a policy allows it, only org owners and members with the Admin policy call tools, and anyone else gets Forbidden.

A branch call, POST /repos/:repo_id/branches/:branch/extensions/:name/tools/:tool (forge extensions call-extension-tool), runs the branch’s head commit, never its uncommitted edits. An installation call, POST /repos/:repo_id/extension-installations/:name/tools/:tool (forge extensions call-extension-installation-tool, or MCP tools["<repo slug>.<name>"].<repoId>.<tool>(input)), names the extension by its qualified name, <repo slug>.<name>, such as acme-standards.procurement, and runs the version that the installing repo’s main head commit pins. Its callers need no access to the defining repo.

Each call runs within the sandbox’s limits: 30 seconds of wall-clock time, its ctx.forge calls included, and 10 seconds of CPU. Its input and result nest at most 256 levels deep, and its result is at most 10 MiB of JSON text. Source, bundle, and execution limits lists every limit.

CLI tool commands

Use extensions commands to call a tool on a branch or on an installation:

# Call a tool at the head commit of a branch of the defining repo
forge extensions list-extension-tools --repo "$SOURCE_REPO" --branch main --name directory
forge extensions call-extension-tool --repo "$SOURCE_REPO" --branch main --name directory \
  --tool companies.search --data '{"query":"Beacon"}'

# List the tools of your repos' installations, and call one on a repo that installed it
forge registry list-installation-tools --org "$ORG"
forge extensions call-extension-installation-tool --repo "$OPS_REPO" --name acme-standards.procurement \
  --tool orders.summarize --data '{"minAmountCents":50000}'

Type to search…

↑↓ navigate↵ selectEsc close