mlld speaks MCP in both directions: serve your exe functions as tools for any MCP client, or import tools from external servers as callable functions. Tool collections control what agents see. Reshaping customizes tool interfaces.
MCP
mlld speaks MCP in both directions: serve your functions as tools, or import tools from external servers.
Export — serve functions as MCP tools:
exe @greet(name: string) = js { return "Hello " + name; }
export { @greet }
mlld mcp tools.mld
Any MCP client can now call greet. See mcp-export.
Import — use external MCP tools as functions:
import tools { @echo } from mcp "npx -y @modelcontextprotocol/server-everything"
show @echo("hello")
A local server runs sandboxed, as run cmd does: it may write only inside the project, and on Linux not as a new file directly in the project's root folder (see enforcement-planes). npx gets a private package cache inside the sandbox, so it needs nothing extra; using { box: { … } } gives one server more room when it does. See mcp-import.
Imported tool outputs carry the .src:mcp provenance label automatically — an origin marker, not a trust verdict. See mcp-import.
Reading order:
| Want to... | Read |
|---|---|
| Serve functions as tools | mcp-export |
| Import external MCP tools | mcp-import |
| Control what agents see | mcp-tool-gateway, tool-reshaping |
| Secure MCP data flows | mcp-security, mcp-policy, mcp-guards |
| Track tool usage | tool-call-tracking |
| End-to-end example | pattern-guarded-tool-export |
Exporting MCP Tools
Export exe functions, run mlld mcp. Every exported function becomes an MCP tool.
exe @status() = js { return "ok"; }
exe @greet(name: string) = js { return "Hello " + name; }
export { @status, @greet }
mlld mcp tools.mld
Clients see two tools: status (no params) and greet (one string param). Name conversion is automatic — @greetUser becomes greet_user over MCP.
Descriptions and parameter types:
exe @search(query, limit) = cmd {
gh issue list --search "$query" -L "$limit" --json number,title
}
exe @summary(topic) with { description: "One-line summary of a topic" } = `Summary of ${@topic}`
export { @search, @summary }
The with { description } clause, written between the signature and =, sets the tool description, whatever the body: a template like @summary's, or a cmd, sh or js block. See exe-metadata.
A parameter's declared type is its served input schema. limit: number is a number, tags: string[] is an array of strings, and a record type (opts: @options) is an object with that record's fields written out in full. A field with a kind says in its description what proof the call needs. A parameter written n: number?, or given a default, is not required. Every call is checked against the declared types: a client that sends "5" for limit: number gets an error result, not a converted value. A parameter with no annotation, like limit above, is listed as a string ("type": "string") and is not checked; a js body receives what the client sent, with its JSON type. An llm call's tools are shown to the model with the same schema. See exe-metadata for the type forms, including field types that need proof.
Serve a directory:
mlld mcp llm/mcp/
mlld mcp "llm/mcp/*.mld"
If llm/mcp/ exists, mlld mcp with no arguments serves every module in it.
Environment overrides:
mlld mcp tools.mld --env MLLD_GITHUB_TOKEN=ghp_xxx
Keys must start with MLLD_. Modules read them with import { @MLLD_GITHUB_TOKEN } from @input.
Filter tools:
mlld mcp tools.mld --tools status,greet
Serve reshaped tool collections:
mlld mcp tools.mld --tools-collection @agentTools
Uses the bind definitions and input records from a tools collection instead of raw exports. See mcp-tool-gateway and tool-reshaping.
Keep a session's restrictions across a restart:
mlld mcp tools.mld --session 3f2a9c
A served session builds up labels as it goes: once a tool returns web data, the client's later calls carry that data's labels, so a policy can stop it reaching a destructive tool. Those labels live in the server process. Without --session, nothing is written to disk, and when the server restarts the session starts clean: a client that read untrusted data before the restart looks untouched after it.
--session <id> closes that gap. The host that launches the server picks the id and passes the same one each time it restarts the server for that client (fray passes its own session id). The server records each tool call and what the call returned, with their labels, on a tape under .llm/tapes/mcp-<module>-<key>/, where <module> is the module file's name and <key> comes from where the module sits in the project, so two modules of the same name in different folders keep separate sessions. When a server starts with an id it has seen, it reads that session's earlier tapes and starts with their labels, so the restart restricts exactly as the old process did.
- What comes back only restricts. A label read from a tape never lets a call through that would otherwise be refused, even when the tape is sealed.
- When the project's config policy lists
signers, each record is sealed as it is written (seepolicy-signers). A sealed tape that has been edited does not verify, and the server refuses to start, naming the file. A tape that is not sealed, or that was cut short by a crash, is still read, since it can only add restrictions. - A secret result's labels are recorded and its value is not.
- The id must not be empty, and must not contain
/,\,..or start with.; the server refuses to start otherwise. - When a sealed tape in the module's tape folder has been edited, or cannot be read, no session of that module starts until it is removed: which session such a tape belongs to cannot be known, so the server refuses rather than guess. The same happens when the config stops listing
signers, or lists a different key, while sealed tapes remain: they can no longer be verified. Removing the tapes lets sessions start again, and drops the restrictions those sessions recorded. Entries in that folder that are not ordinary files are ignored. - One server records a session at a time. A server started under an id another server is still running waits up to 60 seconds for it to exit, which covers a host that restarts the server before the old one has quit, and refuses to start if it has not. While the server runs, nothing else can write to its session: a
mlld tapecall or a livetape:opennaming it is refused. - Anyone who can delete the session's tape files can reset its restrictions.
- A host on a machine whose config names no signers can give the keys it trusts for the session's earlier tapes with
--trusted-signers <file>({"<principal>": {"key": "ssh-ed25519 ..."}}, ascli-tapedescribes). They only check what the server reads back; a config that names signers is the whole set, and they never seal. - A host that keeps the session itself passes
--store <file>with the session's bytes ({"files": {"<run id>": "<base64>"}, "payloads": {...}}, ascli-tapedescribes) and--stored-to <file>, where the server appends one JSON line in the same shape for each write, holding only what that write added (a file, a fifo or/dev/fd/<n>). Add them up and hand the whole back as--storeon the next start. Nothing is written under.llm/tapes, and the lock is yours: start one server per session at a time. The server does not take verified heads: it reads back every line's labels, which a head does not carry. - Answers to questions asked over MCP (below) are not recorded.
Client configuration (Claude Code):
{
"mcpServers": {
"my-tools": {
"command": "mlld",
"args": ["mcp", "tools.mld"]
}
}
}
Questions to a person (elicitation): a served tool can need a person's answer: a guard's or a policy's ask on the call (offered as Approve or Deny), or a match ask in the tool's body (see match-ask). When the client advertised the elicitation capability at initialize, mlld mcp sends each question to it as an elicitation/create request and the tool call waits for the reply. The request's message is the question, with any piece an agent wrote shown as [written by an agent: …]; its schema has a single-choice field, choice, whose values are the option ids and whose titles are the labels. Where the question takes the person's own words it also has a text field, and neither is required; otherwise choice is required. An accept naming an offered option is the answer. decline, cancel, an error, or an accept naming nothing refuses, as no answer within 5 minutes does. A client without the capability is never asked, and the ask refuses as it does with no host.
An elicitation reply does not say who answered, so an answer through MCP has no principal and carries no proof: it never authorizes anything a pick needs proof for. These answers are not recorded, even with --session. Whatever answers the client is the person: a client that is itself an agent, or that answers elicitations automatically, approves its own guard and policy asks, since an Approve needs no proof. Serve a module to an elicitation-capable client only when a person answers its elicitations.
Security: MCP-served tool inputs keep the caller's existing labels/taint; they do not gain synthetic .src:mcp. .src:mcp is applied to values returned from imported MCP tools. See mcp-security.
Tool Collections
The tools directive defines a named collection of surfaced tools. Use it to choose the public tool names an agent sees, derive input metadata from records, attach operation labels, and add prompt/authorization metadata.
record @send_email_inputs [
recipient: string [ kind "email" ]
trusted subject: string
body: string?
labels .op:tool:w, .risk:exfil:send, .op:comm:w
validate "strict"
]
exe .op:tool:w @sendEmail(recipient, subject, body) = js { return "sent"; }
exe @draftEmail(recipient, subject, body) = js { return { recipient, subject, body }; }
tools @agentTools = {
send_email: {
call: @sendEmail,
draft: @draftEmail,
inputs: @send_email_inputs,
labels: [.op:execute:w],
description: "Send an outbound email",
instructions: "Prefer update_draft for in-progress composition."
}
}
show @agentTools.mx.tools
Output:
["send_email"]
Tool definition fields:
call— executable reference used for ordinary tool dispatchdraft— executable reference used when a tool call is routed to a draft handler, ortruefor runtime inert capture frominputs: @recordschemaOnly—truefor a build-time-only policy entry withinputsmetadata and no callable handlerinputs— input-capable record reference used to derive the surfaced tool argsreturns— output record reference used by tool docslabels— operation labels added to the invoked exe when the surfaced tool is calleddescription— explicit tool-doc / MCP description override; an empty string is treated as absent and the executable's ownwith { description }(if any) is served insteadinstructions— extra prompt guidance for explicit@fyi.tools()and MCP annotationscan_authorize— authorization shorthand for tools without an input record; a record-backed tool's authorizing role is declared in the base policy,.role:x { can_authorize: [...] }bind— pre-fill parameters (seetool-reshaping)
Labels in a tool entry are dotted, as everywhere else (labels: [.op:tool:w]). A misspelled handler key is refused (Tool 'f' is missing executable handler reference), and a removed key such as expose: is refused with advice. Any other key a tool entry does not recognize is refused too, at load and by mlld validate, naming the setting it nearly spells or listing the settings an entry takes. A removed setting such as controlArgs: still loads, with a warning that says what replaced it.
can_authorize and the two authorization surfaces
can_authorize on a catalog entry is one of two places tool
authorization is declared. They differ by who declares them and which tool kind
they apply to:
| Surface | Who declares it | Applies to | How it relates |
|---|---|---|---|
catalog can_authorize |
tool author, on a catalog entry | non-record-backed tools | author shorthand that merges into the active base policy; false adds the surfaced tool to the policy's authorizations.deny |
base-policy .role:x { can_authorize: [...] } |
the developer, in the base policy | tools a given exe actor (.role:*) may authorize |
the developer-scoped layer the catalog shorthand merges into; belongs only on the base policy and is not mergeable runtime state |
See config/07b-policy--authorizations.md
for the full authorization model; this table only summarizes how the two
surfaces relate. A record grant .role:x { write: { tools: [authorize] } } is retired:
it fails to load, naming the base-policy form.
A tool may define both call: and draft:; ordinary dispatch uses call:.
Draft-only entries are reserved for honeypot-style tools and do not
settle through a later call handler.
Use schemaOnly: true for catalog entries that exist only to carry an input
record contract. Schema-only entries must declare inputs: @record and cannot declare call,
draft, or bind. They are not served over MCP, do not appear in
@fyi.tools(), and cannot be called directly:
record @send_email_inputs [
recipient: string [ kind "email" ]
trusted subject: string
body: string?
validate "strict"
]
tools @policyTools = {
send_email: {
schemaOnly: true,
inputs: @send_email_inputs,
labels: [.op:tool:w, .risk:exfil:send],
description: "Build-time send email admission"
}
}
Use draft: true when the default draft behavior is enough. It requires a
call: handler and inputs: @record, captures the record-shaped visible
arguments into the draft result, and keeps the original arguments in the
runtime draft registry so @mx.drafts.settle() can later execute the real
call: handler:
tools @agentTools = {
send_email: {
call: @sendEmail,
draft: true,
inputs: @send_email_inputs
}
}
A draft-only tool omits call: entirely. The draft handler's output is returned
directly (no envelope wrapper) and the audit log records
settlement_status: "triggered" at creation:
record @canary_inputs [
target: string
validate "strict"
]
exe @honeypotHandler(target) = js { return { alerted: true, target }; }
tools @agentTools = {
send_email: {
call: @sendEmail,
draft: @draftEmail,
inputs: @send_email_inputs
},
canary_delete: {
draft: @honeypotHandler,
inputs: @canary_inputs,
description: "Delete all records"
}
}
canary_delete is a honeypot: any agent call executes @honeypotHandler immediately, records triggered, and never enters the settlement queue.
Draft handlers
Draft handlers let a surfaced tool produce an inert proposal instead of taking
the external side effect immediately. The catalog remains opaque to the agent:
MCP schemas, @fyi.tools(), and injected tool notes expose the surfaced tool
name and input schema, not whether draft: exists.
A draft-only entry (no call:, like canary_delete above) runs its draft
handler on every call. For an entry that also has call:, a policy's
draft_if_denied routes a label-flow denial to its draft handler, and the
caller gets a drafted result instead of an error (see Routing denials to
draft handlers).
A box's mode: "draft" and @mx.drafts do not route such an entry: they
refuse.
Draft handlers should be inert. Do not send email, write records, call external
systems, or perform any irreversible operation in draft:.
inputs: @record is the canonical shipped path for surfaced tool contracts. Add returns: @record when downstream code needs to know which record type the tool produces. To keep a tool's results in a state, declare the state from the same records (const @recs = { contact: @contact }, then state @found from @recs); a tool collection itself is not accepted after from.
Record-backed tool inputs
When a tool entry uses inputs: @record, the collection derives its visible arg surface from the record:
- record fields must match executable params
- every remaining executable param must be covered by either
inputsorbind - bound params cannot also appear in the record
- if the exe is a single-parameter wrapper (for example
exe @plannerTool(input) = ...),inputs: @recordimplies whole-object dispatch by default;direct: trueis redundant there, whiledirect: falseis an opt-out - on write surfaces, record fields with a kind become effective control args
- on read-only surfaces, record fields with a kind become effective source args
- the record's
labelsline and matchingrefinelabel actions contribute to the surfaced tool's effective operation labels, alongside tool-entrylabels - record
correlate(on by default) becomes the same-source check for multi-fact write tools - record lines such as
exact,update,allowlist, andblocklistfeed runtime validation,@fyi.tools(), and MCP descriptions from the same source definition; a?on a field's type (body: string?) marks it optional at dispatch - if the input record has an
updateline, the surfaced tool must include.op:update:winlabels
This keeps prompt docs, MCP schemas, runtime validation, and policy enforcement on one definition.
Scope tools to an agent with a box:
box @worker using { tools: @agentTools } [
run cmd { claude -p "$task" } using { env: { task: @task } }
]
The agent only sees tools in @agentTools. For a single llm call, pass the collection in the call config instead (@agent(@prompt, { tools: @agentTools })).
Tool collections are identity-bearing runtime values. Passing @agentTools through exe params, imports, module exports, and box/tool APIs preserves the collection metadata (inputs, surfaced names, bind shaping, labels, can_authorize defaults). This holds for handlers imported from another module and surfaced via call: before the collection is re-exported — the handler stays dispatchable across the second module boundary. Object spread does not: { ...@agentTools } materializes plain data and drops tool-collection identity.
Serve a collection over MCP:
mlld mcp tools.mld --tools-collection @agentTools
The --tools-collection flag serves the reshaped collection instead of raw exports. Bound parameters are hidden; only surfaced parameters appear in the tool schema. See mcp-export for basic serving, pattern-guarded-tool-export for a complete example.
For record-backed entries, the served schema comes from the input record fields after bind is applied. The same metadata also feeds injected tool notes and @fyi.tools().
Collections expose compiled reflection through .mx: @agentTools.mx.tools lists the surfaced names.
Guard on labels:
guard @blockDestructive = match [
* => deny "destructive tools are off"
]
policy @toolRules = {
.risk:destructive { before: @blockDestructive }
}
exe @wipe(target) = `wiped ${@target}`
exe @list(dir) = `listing ${@dir}`
tools @agentTools = {
wipe: { call: @wipe, labels: [.risk:destructive] },
list: { call: @list }
}
exe @tryTool(name, arg) = match [
denied => `refused: ${@mx.denial.reason}`
* => @agentTools[@name](@arg)
]
show @tryTool("list", "/tmp")
show @tryTool("wipe", "/tmp")
Output:
listing /tmp
refused: destructive tools are off
The policy binds the guard to every .risk:destructive operation. The wipe entry adds that label when the surfaced tool dispatches, so the guard runs for it and not for list. Labels from the tool definition apply to the call; they do not taint the collection variable itself, and calling @wipe directly does not carry them. See mcp-guards.
Use import tools from mcp "..." when you want callable functions or a namespace in the current scope. Use a tools collection when you want inputs, bind, descriptions/instructions, can_authorize defaults, or per-tool labels.
Direct collection dispatch also uses the surfaced collection key for policy matching:
show @agentTools["send_email"]({
recipient: @contact.email,
subject: "Hi",
body: "Hello"
}) using { policy: @taskPolicy }
A rule or authorization that names send_email matches this call even when the underlying executable has a different internal name. The same surfaced key is what catalog can_authorize defaults, injected <fyi_authorizations>, and @fyi.tools() refer to.
Tool Reshaping
Reshape tool interfaces with two independent mechanisms. bind pre-fills a parameter with a fixed value and hides it from the agent. A tool's input record declares the contract for the parameters that remain — their types, trust and classification. In the record-backed form this page is about, bind is the only one of the two that changes which parameters the agent sees; the form table below says where that stops holding. Used in tools collections (see mcp-tool-gateway).
bind - Pre-fill parameters:
exe @createIssue(owner: string, repo: string, title: string, body: string) = cmd {
gh issue create -R "$owner/$repo" -t "$title" -b "$body"
}
tools @agentTools = {
createIssue: {
call: @createIssue,
bind: { owner: "mlld", repo: "infra" }
}
}
The agent sees only title and body. The bound parameters owner and repo are fixed.
inputs - Declare the contract for the visible parameters:
An input record says what the remaining args are: their types, whether each is security-relevant (a field with a kind) or free payload (a field without one), how much the tool trusts them, and which are optional. In the record-backed form below — which is what this example is — it does not change which parameters the agent sees; bind is what does that.
The exe's own typed parameters (owner: string) are checked on every call too. An entry's inputs: record adds its checks on top of them and never replaces them, so a type the exe declares still holds when the entry's record says less (see exe-metadata).
exe @createIssue(owner: string, repo: string, title: string, body: string) = cmd {
gh issue create -R "$owner/$repo" -t "$title" -b "$body"
}
record @create_issue_inputs [
title: string
body: string
validate "strict"
]
tools @agentTools = {
createIssue: {
call: @createIssue,
inputs: @create_issue_inputs,
bind: { owner: "mlld", repo: "infra" }
}
}
Three forms, and which one an entry is decides what the record's field list means. These are all of them — the two flags that select between them, schemaOnly and whole-object dispatch, are mutually exclusive. Every example on this page is the first form.
| form | when | what the record's field list is |
|---|---|---|
| record-backed | anything not covered by the two rows below | a description of parameters the executable already has — see the three rules |
| whole-object | all four: exactly one parameter, no bind at all, the record does not name that parameter, and no direct: false |
the surface itself, replacing the parameter list. See mcp-tool-gateway |
schemaOnly: |
schemaOnly: true: the entry fronts no executable, and a call, mlld or draft handler is refused |
the parameter list itself, substituted for one |
In the record-backed form, the record's fields and the bind keys cover disjoint halves of the same parameter list, so the visible set is the same either way. Three rules enforce it, each refused when the collection is defined, not when the tool is called:
- in this form, every record field must be a parameter of the executable
- in this form, every parameter must be either a record field or a
bindkey - in this form, no parameter may be both — binding a param that the record also declares is refused
In the whole-object form none of the three applies: the record's fields need not be parameters, the one parameter need not be covered, and there is no bind to overlap with. Adding a bind, or direct: false, drops the entry back to the record-backed form — and then the record's own fields are illegal, because they are no longer parameters of anything. (direct: true is redundant; only false opts out.)
In the schemaOnly: form the three rules hold by construction, because the record's fields are the parameter list they are checked against.
See records-basics for the rule in full, and tool-definition for what a field's kind means and why it matters.
What the record changes, in the record-backed form:
Not which parameters the agent sees — bind is the only control over that. Adding the record above leaves the served parameters unchanged and adds [PAYLOAD: title, body] to the tool's description. The record does shape the rest of what the agent is shown: each parameter's type in the input schema (a number field is served as a number, a list as an array), which args are required, and that classification note, which also names non-string field types (limit?: number).
When the exe has its own typed signature and the entry also has inputs:, the entry's record is what the agent is shown. It only adds checks: the exe's own parameter types are still checked on every call, so an entry that marks a parameter optional serves it as optional, but a call that leaves it out is still refused if the exe requires it.
Variable binding:
Bound values can reference variables:
exe @createIssue(owner: string, repo: string, title: string, body: string) = cmd {
gh issue create -R "$owner/$repo" -t "$title" -b "$body"
}
const @org = "mlld"
const @defaultRepo = "main"
tools @agentTools = {
createIssue: {
call: @createIssue,
bind: { owner: @org, repo: @defaultRepo }
}
}
Variables are resolved when the tool collection is defined, not when called.
bind is a config/materialization boundary: bound values are stored as plain config data for the surfaced tool definition. If a value's wrapper metadata must survive until dispatch time, pass it as a normal argument instead of baking it into bind.
For record-backed write tools, do not resolve a stored record's address to a bare string inside bind: that strips the field-local .fact:* proof and the dispatch check will fail with proofless_control_arg. Trusted orchestrator code can explicitly resolve handles or addresses with @mx.handles.resolve or .mx.resolved, then pass the resulting live value as a normal tool argument. Untrusted/agent-tainted scopes cannot use those explicit resolver surfaces directly.
Nested objects in bind:
exe @configure(config: object, mode: string) = cmd {
configure-tool --mode "$mode" --config "$config"
}
tools @agentTools = {
configure: {
call: @configure,
bind: { config: { timeout: 30, retries: 3 } }
}
}
Complete example:
exe @searchDocs(index: string, query: string, limit: number, format: string) = cmd {
search-tool --index "$index" -q "$query" -n "$limit" --format "$format"
}
tools @agentTools = {
searchDocs: {
call: @searchDocs,
bind: { index: "production", format: "json" },
description: "Search documentation"
}
}
The agent sees:
query(required)limit(required)
query is served as a string and limit as a number, from their declared types.
Hidden from agent:
index(always "production")format(always "json")
The removed expose: entry field refuses at runtime and during validation.
For a multi-parameter executable, the served parameters are the executable
parameters minus bind: keys; an input record must cover that remaining set.
To serve a smaller contract, wrap the executable in a single-parameter tool
and define that whole-object input through its input record.
Importing MCP Tools
Import tools from an MCP server as callable exe functions. The server spec is a shell command that launches the server.
Selected import:
import tools { @echo } from mcp "npx -y @modelcontextprotocol/server-everything"
show @echo("hello")
npx keeps its cache in ~/.npm, outside the project, which the sandbox does not let it write. It gets a private cache inside the sandbox instead (see box-package-managers), so the server starts with no extra setting. With fence.caches set to false in mlld-config.json, it needs ~/.npm to be writable: see Giving one server more room below.
Namespace import:
import tools from mcp "npx -y @modelcontextprotocol/server-filesystem /workspace" as @fs
show @fs.listDirectory("/workspace")
Namespace import requires as @alias.
Dynamic specs through interpolation:
const @serverSpec = "node ./calendar-server.cjs"
import tools from mcp `${@serverSpec}` as @calendar
A quoted spec is always literal text; build one from variables with a backtick template.
Servers run sandboxed: a local server (one mlld starts from a command) runs under the same fence as run cmd. It starts in the project's root folder, so "node server.cjs" finds a server.cjs there whatever folder you ran mlld from. Modules and policy files the run loads after a server started are protected from it too: before the server's next call, mlld restarts it under a fence that protects them, so a server loses anything it held in memory when the run loads more code. The box.mcp.server_refenced trace event records each restart (see runtime-tracing). It may write only inside the project (on Linux, not as a new file or folder directly in the project's root folder; use a subfolder, see enforcement-planes), and mlld's own files there (.mlld/, .llm/, mlld-config.json) stay unwritable. It may read broadly. Its network is the policy's capabilities.network, or open when there is no policy. The policy that counts is the one where the server was imported: an imported tool runs under it wherever the tool is called from, so a module that imports a server under its own policy keeps that policy for every caller. One server command imported in two places under different policies runs as two separate processes, one per policy, which share no state; imported again under the same policy, it is the same process. A remote url server is not a process mlld starts, so none of this applies to it. fence.default: "off" in mlld-config.json runs servers outside any box on the host, as it does every command; a server a box declares, or a tool called inside a box, still runs under that box's limits. A policy's command denies do not stop a server or anything it starts; see mcp-policy. A server a box declares, and a tool you imported at the top level but call inside a box, run under that box's limits instead (the call inside the box starts a separate process of the server); see box-config.
Giving one server more room: add using { box: { … } } to the import, such as using { box: { fs: { write: ["~/.npm"] } } } for an npx server when fence.caches is false. It takes a box block's keys, fs and net, but it starts from the fence the server already has, not from a sealed box:
fs: { write: [...] }adds folders the server may write.~/is your home folder, and a relative folder is the project's. A folder that does not exist yet is created.netreplaces the server's network:"none","loopback","open", or an{ allow, deny }host list.fs: { read: [...] }is accepted, but reads are already broad, so it only meets the policy check below.- A key you leave out keeps the default.
This is different from a box block, which starts with nothing and gives only what it names. Any other key (provider, tools, …), or a box: that is not an object, is an error naming fs and net. Write it as using: with { box } on an MCP import is an error that names the using { box: { … } } form.
The policy is the ceiling. A write folder the policy's filesystem capabilities (fs:w:<glob>) do not cover all the way down, a read folder it does not let the program read, or a net wider than capabilities.network refuses the server before it starts, and the error names the folder or net setting the policy does not allow. With no policy the setting stands. The ceiling is the policy in force when the server is declared: a policy written after the import does not cap it.
On Linux, a write folder that holds or is inside a .llm/ or .mlld/ folder is refused, because Linux cannot keep mlld's own files unwritable inside a writable folder. macOS keeps them unwritable inside any folder you grant.
With fence.default: "off" the setting is not applied, the server runs on the host, and a warning says so. One server declared twice with different box: settings is an error, since one process serves both.
The same setting goes on a box's @mcpConfig() server entry ({ command: "srv", box: { … } }, see box-config) and on an mcpServers entry written as an object ({ "command": "srv", "box": { … } }, see config-live-stdio).
That form remains useful when you want imported functions or a namespace in the current scope.
A spec assembled at runtime from data the program did not write — a tool result, a model's reply, fetched content — is a different matter. Starting a server is the operation .op:mcp:spawn, so a policy block denying that operation to untrusted data (.untrusted { deny: [.op:mcp:spawn] }) refuses the import. A spec written as a literal is unaffected, and so is a policy that does not name the operation. See mcp-policy.
Name conversion is automatic. MCP's list_directory becomes mlld's @listDirectory. The mapping works in both directions.
Type coercion is automatic. Arguments are coerced to match the MCP tool's inputSchema types before dispatch. A string where the schema expects an array is wrapped ("x" → ["x"]), string numbers are parsed, "true"/"false" become booleans, and JSON strings are parsed for object/array types.
Argument matching: Positional arguments map to the tool's parameters in the order its schema declares them. The names of the variables you pass play no part: if the schema declares participants before title, then @mcp.createCalendarEvent(@title, @participants, @date) sends the title as participants. To match by name, pass one object whose keys are the parameter names:
exe @createEvent(title, participants, date) =
@mcp.createCalendarEvent({ title: @title, participants: @participants, date: @date })
When a tool schema has a single object-shaped parameter, passing one object can satisfy that parameter by name.
Null arguments: an explicit null is sent as null when the parameter's schema admits null (an anyOf/oneOf branch of type null, a type list such as ["string", "null"], or an enum listing null), whether or not the parameter is required. For a parameter whose schema does not admit null, null is left out of the call, the same as an argument you omit.
Remote servers: A bare https:// (or http://) URL connects to a streamable-HTTP MCP server instead of launching a command:
import tools { @search } from mcp "https://mcp.example.com/api"
show @search("quarterly report")
A remote server with credentials uses a JSON spec. env: header values resolve from the process environment when the request is sent, so the secret never appears in the script or its traces:
import tools from mcp '{"url":"https://mcp.example.com/api","headers":{"Authorization":"env:ACME_MCP_TOKEN"}}' as @acme
A header whose environment variable is unset fails with an error naming the header and variable — nothing is sent without it (the first send happens during the import itself, so that is where the error surfaces). Remote servers negotiate at protocol revision 2025-03-26 or later (the streamable-HTTP floor) and never restart on failure — each request surfaces its own error.
Named credentials: instead of an env: header, a remote spec can name a credential declared in policy secrets (see auth). The spec carries the NAME only — the secret is resolved from the credential's own source and delivered as Authorization: Bearer <secret> on every request, never appearing in the script, the spec string, or error text:
policy @keys = {
* {
secrets: {
acme: { from: "env:ACME_MCP_TOKEN", as: "ACME_MCP_TOKEN", for: ["mcp.example.com"] }
}
}
}
import tools from mcp '{"url":"https://mcp.example.com/api","secret":"acme"}' as @acme
secretHeader changes the delivery header (and drops the Bearer prefix):
import tools from mcp '{"url":"https://mcp.example.com/api","secret":"acme","secretHeader":"X-Api-Key"}' as @acme
Two rules govern where a named credential may be presented:
for:scoping is enforced per request. A credential declared withfor: ["mcp.example.com"]is checked against the destination host on every send; a host outside the list fails the send with an error naming the credential and its scope — never the secret.- An unscoped credential (no
for:) only reaches a literal destination. If the spec was assembled from untrusted data — interpolated from a tool result, a record field, an exe return — the import refuses before any request leaves the process. Afor:-scoped credential is exempt: the scope check is the protection.
A credential name that is not declared fails at the import itself, before the first request.
Protocol negotiation is automatic. mlld picks the newest revision both sides support (2024-11-05 through 2026-07-28), and a server that only speaks the stateless 2026-07-28 profile is detected by its refusal of the handshake and used statelessly. Notifications the server sends mid-call (progress updates and the like) surface on stderr — they are never silently dropped.
Structured results: When a tool returns a typed structuredContent result (and the negotiated revision supports it), the imported function returns that structure as a real mlld value — field access like @result.count works directly. Tools that return text only are unaffected.
SDK server injection: When using the SDK, mcpServers maps logical names to commands per-execution. import tools from mcp "name" checks the map before treating the spec as a shell command:
client.execute('./agent.mld', payload,
mcp_servers={'tools': f'uv run python3 server.py {config}'})
import tools from mcp "tools" as @t
Each execute() call gets an independent server lifecycle, enabling parallel executions with isolated MCP state.
Imported tool namespaces and discovered tool collections preserve their tool metadata across module/exe handoff. Treat them as identity-bearing values; don't object-spread them if you need the collection behavior to survive.
Tool errors: When an imported MCP tool fails — either the server returns a
JSON-RPC error or the tool returns an isError result — the call throws a
recoverable error you can catch with try. The
caught error is thin:
const @r = try @mcp.some_tool(@args)
if !@r.ok => show `MCP call failed: ${@r.error.message}`
Available fields are @r.error.class and @r.error.message. Tool identity,
server identity and a normalized MCP error code are not included. The caught fields are descriptive only
and confer no trust: trust still comes from the record or schema the data flows
through.
Returned error shapes. Some tools do not throw on failure — they return an
error-shaped value ({ isError: true }, { ok: false }, a non-empty error
field, an empty result, or ERROR:-prefixed text). Those produce a normal
protocol result, so try reports ok: true and hands you the error object as the
value. @isError from the @mlld/mcp module detects that returned shape:
import { @isError } from @mlld/mcp
const @raw = @mcp.some_tool(@args)
if @isError(@raw) => show "tool failed"
@isError is pure data inspection and confers no trust. The module's other
helpers, @normalizeError, @array and @object, stop with a JavaScript error
(errorMessage is not defined, isError is not defined); read the returned
fields yourself instead.
Security: All MCP tool outputs carry the .src:mcp provenance label automatically — an origin marker, not a trust verdict (it does not make the data untrusted; records and schemas set trust). Starting a server is separately labeled .op:mcp:spawn, so a policy naming that operation can refuse a server spec that came from untrusted data. See mcp-security for propagation details, mcp-guards for filtering, mcp-policy for flow restrictions and for what does and does not gate a spawn.