Skip to main content

Tools and MCP

How core builds a run's tool set, how a tool call executes, and where MCP servers run. What users configure is in the tools guide. Paths are relative to apps/core/.

Registry​

harness.ts calls createTools() in src/harness/tools/index.ts once per run, then wraps the result before it reaches streamText():

GroupToolsRegistered when
Sandboxbashany sandbox or sandbox-backed workspace
computera machine sandbox
browsebrowser.enabled; CLI sync refuses the agent, and core fails the run, unless the first sandbox can run Obscura
read, globany workspace (mount when it has a sandbox, else S3 or a read-only mount)
write, edit, grepa workspace with a sandbox
memory_savea sandbox-backed workspace with the memory harness on
Channelsend-files, send-images, send-reactions, send-sticker, send-updatea channel turn. send-update always; send-files also needs a workspace; the rest are gated on adapter capabilities. See channels
send-messagethe agent has channels and the request can dispatch to another session
Subagentrun_subagent; persistent mode adds stop_subagent, message-agentssubagent.enabled and a dispatcher; the persistent controls also need the run's account and session; a persistent subagent run gets message-agents to "parent"
Skillsload_skillskills.enabled with allowed paths
Schedulerschedule, list_schedules, update_schedule, cancel_schedulescheduler.enabled, not on a cron-fired run
Providerevery enabled config.tools keya descriptor names its tool by id on the provider's tools namespace (a bare entry by its key), else the run fails listing the ids; a client-executed tool runs as the sandbox tool it stands for (tools/sandbox-stand-in.ts), approval and OPA judge the call as that tool, and a tool.call.started hook gets it as runsAs
Questionsask_questionsthe session has a delivery (channel, WebSocket or direct API polling), so not a subagent, and is not cron-fired
MCP<server>__<tool>each enabled config.mcp server
Asyncasync_statusa workspace on a persistent sandbox, where bash starts background jobs; logs and stop only with live job controls

withholdTools runs after every group is registered, so a channel record's denyTools also covers sandbox and MCP tools.

Provider-defined tools​

A provider tool serializes to { type: "provider", id: "google.google_search", args }, which loses its schemas, so provider-tool.ts rebuilds it from the live provider factory with those args. Core keeps no list of names.

A tool call​

A sync tool runs inside the model step:

Two tools return a status id at once and settle outside the model step: bash with background: true and ask_questions. Each writes a detached row (async-tool-result.ts). A background job settles it through POST /v1/sandbox-jobs/:resultId/complete (see sandboxes), an answer through questions.ts. Either way continueAfterAsyncToolSettlement in handler.ts resumes the conversation with the result; an answer joins a live run at its next step boundary. The model can read a row early with async_status.

  • A settled row carries handback, the same field a subagent result row has (see subagents): pending from the settle, stored once the conversation's saved history holds the result. async_status writes nothing when it reads a finished row: it always answers the result and records the call's id with the row's id in the turn's read ledger (Session.recordToolResultRead), and a call whose output a hook turned into an error or a denial stores nothing. A read never stores the row itself, not even in a session that saves no history: an ephemeral subagent child's reads ride the write of its answer to the parent (updateAsyncAgentResult with toolResultIds, the rows of the child's own conversation only), and a child that fails or dies first leaves them to the sweep. The write that saves the call's tool message (the step boundary, or the turn's last append) carries the id as toolResultIds on the row, and insertConversationEvents marks the result stored in the same transaction, only when the row's conversation is the one being written, and insertOwnedEvents completes any continuation of it still queued there, with the queue counters; so does a write that stores it under its key. So a turn that dies between the read and the save leaves the row as it was, and the continuation or the sweep tells it once.
  • A continuation (continueAfterAsyncToolSettlement, admitted once per result as <root event>:async-tools:<resultId>) passes the row as toolResultId to runtimeIngress.accept, which refuses it as a duplicate once the row is stored or while another continuation of it is queued or applied. Its message carries the result's key (async-tool:<resultId>:<status>), so the write that saves that message stores the row, once even when a retry follows a lost reply; handing it to an owner stores nothing. A continuation that ends before it is saved, expired, failed or settled, leaves the row for the sweep, whose retry replaces that envelope. The ingress recovery sweep's resumeLostAsyncToolResults (async-tools.ts) runs after the subagent pass, over rows pending for longer than one run budget plus wind-down plus the 2 minute grace, each written within a day; each resumes its conversation through the same continuation, a capacity or duplicate admission keeps the row for the next pass (admission stores the row of a result the conversation has), and a row refused as a conflict or with nothing to resume is marked stored and logged once.

MCP servers​

Core is a stateless MCP client over Streamable HTTP only (src/harness/mcp/client.ts). As a client, core and the broods machine --mcp host negotiate: 2026-07-28 when the server offers it, else the older initialize handshake, since nobody here controls third-party servers. A hosted row stays pinned to 2026-07-28. An older server's verdict is cached so it is probed once. As a server, Broods speaks only MCP_PROTOCOL_VERSION (src/shared/mcp-protocol.ts): /mcp, broods mcp and hosted templates all pass legacy: "reject". The MicroVM host behind mcp/sandbox.ts lives in lambda-sanbdox and still speaks 2025-06-18 until it moves there. Each run lists tools (cached per row for the listing's ttlMs) and registers them as <server>__<tool>. Against a 2026-07-28 server every tools/call is one POST with no session; an older server gets its initialize handshake first. The row's transport decides where that POST goes:

  • External URLs: the host is resolved first and private, loopback, link-local and metadata addresses are refused, as are redirects. The OAuth tokenUrl gets the same check (oauth.ts mints and caches refresh-grant tokens).
  • Sign-in: mcp/connection.ts serves /v1/mcp-connections/{serverId}. Core discovers the authorization server, registers a public client, and holds the PKCE verifier sealed inside the OAuth state (AES-GCM, key HKDF-derived from MEDIA_TICKET_SECRET), so a sign-in in progress has no row. Tokens live sealed on the server's own mcp row (connection plus the connectionCiphertext columns), so they go when the row goes. The <server>__sign_in tool (mcp.tool.ts) starts the same sign-in from inside a run, only when an account key started it. connections.ts tokenFetch refreshes ahead of expiry and once on a 401, for ChatGPT plan connections too. account/mcp.ts clears them when the URL changes or the server is removed.
  • Headers: a credential-bearing header must be a ${NAME} env ref. Inline secrets and URL userinfo are refused at registration.
  • Every remote request carries X-Broods-Agent-Id and, when the chain is known, X-Broods-Principal. See security. A hosted request also carries X-Broods-User-Credential when the run came with a user token holding a credential; see end-user tokens. All three names are reserved and a tenant copy is dropped.
  • Results: structuredContent, or the text blocks. Images reach the model only within withImageLimits in tools/utils.ts (PNG, JPEG, GIF or WebP, at most 8000 px a side, 8 images and 6 MB per result). An image resource_link over http(s) is read by core with the same address checks and limits, and keeps its link line. Stored history keeps each picture in the attachment store behind a sealed link (sealConversationMedia in channel-media.ts); later turns read the newest back as images, up to 20, and older ones become a line of text ten at a time, so the prompt prefix stays cached.
  • Not supported: subscriptions/listen. MRTR input_required surfaces as a tool error.

Server on a lambda sandbox​

When a sandbox row names a persistent lambda sandbox, the VM's image runs the stdio server and keeps it for the VM's lifetime:

The POST is resent only when the connection never opened, because a later 502 may hide a tool that already ran. The body carries the sandbox env without the BROODS_* run identity. A call gets the sandbox timeout, default 120 s. sandboxMcpTarget resolves the row for runs and for the dashboard explorer; explorerSandboxTarget in src/accounts/mcp-service.ts picks the explorer's VM.

Hosted servers​

A hosted row runs an account-uploaded bundle on one of two runtimes. Both take the same McpHostPayload and answer with the same NDJSON frames (src/harness/frames.ts), so hosted.ts reads either one the same way.

LimitLambda (apps/lambda)Cloudflare (apps/cloudflare-mcp)
Bundle50 MB (MAX_MCP_BUNDLE_BYTES)10 MB
Batch in6 MiB invoke payload6 MiB
Batch out16 MiB of frames16 MiB of frames
Deadline30 s for the batch, child aborts 2 s earlier30 s per request, 5 s CPU, 50 subrequests
Core timeout45 s request timeout45 s
CPU reportedyes, split evenly across the batch's callsno
Warm unitone child process per tenantId:sha256one isolate per tenantId:sha256

tenantId is accountId:agentId (the account alone for a probe), so two agents never share a child or isolate. Both runtimes are metered on wall time at the Lambda memory size (HOSTED_MCP_MEMORY_GB), one request per batch.

Which runtime a row uses​

The scan in packages/convex/model/isolateSafety.ts refuses require, node: imports, process and Buffer members, setImmediate, __dirname, bare package imports, eval and new Function. Every upload path goes through putMcpBundle, so a row's flag never depends on which client uploaded it. Bundles over 10 MB upload through POST /v1/mcp/uploads instead of the request body. A self-hosted stack without the Worker runs everything on Lambda, see self-hosting.

One batch​

The parallel calls of one model step reach hosted.ts together. enqueueCall parks them under tenantId:runtime:sha256 for MCP_BATCH_WINDOW_MS (10 ms) or until MCP_BATCH_MAX (8) calls, then flushBatch sends one invoke. MCP_BATCH_MAX=1 turns batching off.

  • Only the Worker's own x-broods-nothing-ran tag, or a connection that never opened, proves no tool ran. Fallback logs hosted MCP batch fell back to Lambda.
  • A timeout, an abort, or a broken stream after a 200 fails the batch and is never retried, because a tool may already have acted.
  • A batch that ends on a batch-level error frame, or without a terminal frame, fails every call it has no answer for.
  • The handler factory must build a fresh server per request. One process or isolate serves a batch's calls concurrently, and a shared instance would be aborted when one request's transport closes.

Lambda warm child​

Before every spawn the handler also kills every other process of its user (reapStrays), so a bundle that escaped its group never sits next to the next child. It does so only inside Lambda (LAMBDA_TASK_ROOT set): on a dev box or CI runner that user owns the shell and everything else. MCP_CHILD_MAX_CALLS and MCP_CHILD_IDLE_SECONDS set the bounds, and MCP_CHILD_REUSE=0 makes every child one-shot. The isolation model is in security.

defineTool and POST /v1/tools are retired; hosted MCP servers replace them.

MCP Tasks server​

Core is also an MCP server: POST /mcp (src/harness/mcp-tasks.ts) serves the account's agents through a fixed set of tools: list_agents, ask_agent and, for a client without tasks, get_run and continue_run in place of tasks/*. The tool list reads nothing, so it is the same for every caller; list_agents joins each agent to its project and stage (agents.scopes). A client declaring io.modelcontextprotocol/tasks gets a task handle back from ask_agent; any other polls inline up to 50 s (waitForRun) and gets continue_run for what is left. It is a translator with no state of its own. A low-level SDK Server behind createMcpHandler(factory, { legacy: "reject" }) answers each request; McpServer would reshape the resultType: "task" result. Every run read and write is replayed through core's own handler as POST /v1/runs or GET /v1/runs/{runId} with the caller's resolved credential, so stage scope, public access, user tokens, plan limits and the run-token rules stay in integrations.ts.

  • Task id: the run id, 122 random bits. There is no tasks/list, and every task call replays the caller's credential, so a task one key cannot read is -32602 like an unknown one.

  • Tools: tools/list reads agents.listForAccount for an account key and listForEndpoint for a stage key, filtered to public agents for the embeddable key. A brt_ run token lists none until peer calls land with their own allow-list and cycle guard.

  • Questions: an answer goes back as POST /v1/runs {answers}. Core continues the run under <root eventId>:async-tools:<statusId> (asyncToolContinuationEventId), and the asking run's row keeps saying awaiting_input, so tasks/get follows that id to the continuation.

  • Approvals: a reply is a new run with nothing pointing back. tasks/update sends it under the event id <waiting eventId>:approval, and tasks/get follows that id.

  • Both links are found with getIngressStatusByEventId from run to run. No row or schema field records them, and the fixed approval id makes a retried update a duplicate admission.

  • Cancel: stopIngressOwner on the task's conversation, the path /stop and stop_subagent take, for a key that may start runs. The run ends failed with stoppedByUser, which maps to cancelled.

  • Timestamps: createdAt and lastUpdatedAt come from GET /v1/runs/{runId}. lastUpdatedAt is the later of the envelope and its polling row, since an answered question moves only the row.

  • Sign-in: WorkOS AuthKit is the authorization server, the same login as the dashboard and broods login. src/harness/mcp/authkit.ts serves the RFC 9728 metadata at /.well-known/oauth-protected-resource/mcp, names it in every 401, and verifies an AuthKit JWT against <WORKOS_AUTHKIT_DOMAIN>/oauth2/jwks, audience <PUBLIC_BASE_URL>/mcp. Its sub maps through cli.auth.resolveUserLogin (cliLoginTarget, the broods login rule) to an account: the one org the user administers, or the one ?org=<slug> names. The dashboard's active org plays no part, so switching there never repoints a client. The token is good at /mcp only: its replays carry the resolved credential, and no other route accepts it.

Not built: client-side elicitation pushed to the caller mid-run, and Broods calling remote task servers.

Add a built-in tool​

Most integrations belong in an MCP server, external or hosted. Add a built-in tool only for behavior that needs core internals: the session, a sandbox or a channel.

  1. Create src/harness/tools/<name>.tool.ts with a header comment, the model-facing schema and the execution logic.
  2. Export a factory that takes only the context it needs and returns a ToolSet.
  3. Register it in createTools() behind the config or session condition that enables it. config.tools is only for provider-defined tools.
  4. If users configure it: add the field to AgentConfig in src/shared/domain/agent-config.ts, validate it in packages/convex/model/agentRules.ts, expose it in packages/broods/src/resources.ts, run Convex codegen.
  5. Update the API reference, the tools guide and focused tests.
/**
* Example lookup tool. Keeps the model-facing schema and the service call together.
*/

import { tool, type ToolSet } from "ai";
import { z } from "zod";

interface ExampleLookupContext {
apiKey: string;
}

export default function exampleLookupTool(
context: ExampleLookupContext,
): ToolSet {
return {
example_lookup: tool({
description: "Look up Example records.",
inputSchema: z.object({ query: z.string().min(1) }),
execute: async ({ query }) => {
const response = await fetch("https://api.example.com/search", {
method: "POST",
headers: {
Authorization: `Bearer ${context.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ query: query }),
});
if (!response.ok) {
throw new Error(`Example lookup failed: ${response.status}`);
}

return response.json();
},
}),
};
}

Rules:

  • One tool per <name>.tool.ts. Orchestration stays in harness.ts.
  • No new Lambda, queue or worker for an ordinary external-service tool. Use an MCP server.
  • Reuse provider or service SDK types. Return structured data, not prose.
  • Per-account credentials live in encrypted agent config or account env vars. SST secrets are only service-wide fallbacks.
  • Approval goes through needsApproval (AI SDK tool approval), never a question inside the tool.