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():
| Group | Tools | Registered when |
|---|---|---|
| Sandbox | bash | any sandbox or sandbox-backed workspace |
computer | a machine sandbox | |
browse | browser.enabled; CLI sync refuses the agent, and core fails the run, unless the first sandbox can run Obscura | |
read, glob | any workspace (mount when it has a sandbox, else S3 or a read-only mount) | |
write, edit, grep | a workspace with a sandbox | |
memory_save | a sandbox-backed workspace with the memory harness on | |
| Channel | send-files, send-images, send-reactions, send-sticker, send-update | a channel turn. send-update always; send-files also needs a workspace; the rest are gated on adapter capabilities. See channels |
send-message | the agent has channels and the request can dispatch to another session | |
| Subagent | run_subagent; persistent mode adds stop_subagent, message-agents | subagent.enabled and a dispatcher; the persistent controls also need the run's account and session; a persistent subagent run gets message-agents to "parent" |
| Skills | load_skill | skills.enabled with allowed paths |
| Scheduler | schedule, list_schedules, update_schedule, cancel_schedule | scheduler.enabled, not on a cron-fired run |
| Provider | every enabled config.tools key | a 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 |
| Questions | ask_questions | the 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 |
| Async | async_status | a 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):pendingfrom the settle,storedonce the conversation's saved history holds the result.async_statuswrites 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 (updateAsyncAgentResultwithtoolResultIds, 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 astoolResultIdson the row, andinsertConversationEventsmarks the resultstoredin the same transaction, only when the row's conversation is the one being written, andinsertOwnedEventscompletes 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 astoolResultIdtoruntimeIngress.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'sresumeLostAsyncToolResults(async-tools.ts) runs after the subagent pass, over rowspendingfor 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, acapacityorduplicateadmission 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 markedstoredand 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
tokenUrlgets the same check (oauth.tsmints and caches refresh-grant tokens). - Sign-in:
mcp/connection.tsserves/v1/mcp-connections/{serverId}. Core discovers the authorization server, registers a public client, and holds the PKCE verifier sealed inside the OAuthstate(AES-GCM, key HKDF-derived fromMEDIA_TICKET_SECRET), so a sign-in in progress has no row. Tokens live sealed on the server's ownmcprow (connectionplus theconnectionCiphertextcolumns), so they go when the row goes. The<server>__sign_intool (mcp.tool.ts) starts the same sign-in from inside a run, only when an account key started it.connections.tstokenFetchrefreshes ahead of expiry and once on a 401, for ChatGPT plan connections too.account/mcp.tsclears 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-Idand, when the chain is known,X-Broods-Principal. See security. A hosted request also carriesX-Broods-User-Credentialwhen the run came with a user token holding acredential; 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 withinwithImageLimitsintools/utils.ts(PNG, JPEG, GIF or WebP, at most 8000 px a side, 8 images and 6 MB per result). An imageresource_linkover 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 (sealConversationMediainchannel-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. MRTRinput_requiredsurfaces 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.
| Limit | Lambda (apps/lambda) | Cloudflare (apps/cloudflare-mcp) |
|---|---|---|
| Bundle | 50 MB (MAX_MCP_BUNDLE_BYTES) | 10 MB |
| Batch in | 6 MiB invoke payload | 6 MiB |
| Batch out | 16 MiB of frames | 16 MiB of frames |
| Deadline | 30 s for the batch, child aborts 2 s earlier | 30 s per request, 5 s CPU, 50 subrequests |
| Core timeout | 45 s request timeout | 45 s |
| CPU reported | yes, split evenly across the batch's calls | no |
| Warm unit | one child process per tenantId:sha256 | one 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-rantag, or a connection that never opened, proves no tool ran. Fallback logshosted 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
errorframe, 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-32602like an unknown one. -
Tools:
tools/listreadsagents.listForAccountfor an account key andlistForEndpointfor a stage key, filtered to public agents for the embeddable key. Abrt_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 sayingawaiting_input, sotasks/getfollows that id to the continuation. -
Approvals: a reply is a new run with nothing pointing back.
tasks/updatesends it under the event id<waiting eventId>:approval, andtasks/getfollows that id. -
Both links are found with
getIngressStatusByEventIdfrom run to run. No row or schema field records them, and the fixed approval id makes a retried update a duplicate admission. -
Cancel:
stopIngressOwneron the task's conversation, the path/stopandstop_subagenttake, for a key that may start runs. The run endsfailedwithstoppedByUser, which maps tocancelled. -
Timestamps:
createdAtandlastUpdatedAtcome fromGET /v1/runs/{runId}.lastUpdatedAtis 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.tsserves 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. Itssubmaps throughcli.auth.resolveUserLogin(cliLoginTarget, thebroods loginrule) 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/mcponly: 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.
- Create
src/harness/tools/<name>.tool.tswith a header comment, the model-facing schema and the execution logic. - Export a factory that takes only the context it needs and returns a
ToolSet. - Register it in
createTools()behind the config or session condition that enables it.config.toolsis only for provider-defined tools. - If users configure it: add the field to
AgentConfiginsrc/shared/domain/agent-config.ts, validate it inpackages/convex/model/agentRules.ts, expose it inpackages/broods/src/resources.ts, run Convex codegen. - 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 inharness.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.