One workflow, three ways
Run the same step from the CLI, from your own program, and from an MCP client.
A definition does not depend on what launches it. This page runs one step,
count, three ways: through the CLI, an embedded engine, and an MCP server.
The example needs no agent.
The step
count counts the files in the workspace that end with an extension. It
needs zod installed beside it.
import { step } from "@foundry.sh/marbles";
import { z } from "zod";
export const count = step("count")
.input(z.object({ extension: z.string() }))
.do(async ({ input, workspaces }) => {
const files = await workspaces.current.files();
return {
extension: input.extension,
files: files.filter((file) => file.path.endsWith(input.extension)).length,
};
});
Calling step(...) registers the definition with whichever host loads the
module; the export lets your own program take it too.
1. From the CLI
Save the module as .foundry/marbles/count.ts and roll it from the project
root:
marbles roll count --input '{"extension":".ts"}'
roll attaches the workspace to the Marbles process, starting it when none
runs, runs count in its current engine generation, prints the step’s status lines
and its result as JSON, and exits. The workspace stays hosted;
marbles stop ends the process. See the CLI reference.
2. From your own program
@foundry.sh/marbles/lib builds an Engine from explicit instances. This
one keeps everything in memory, uses no agent, and has no sandbox runtime:
import {
ArtifactManager,
Engine,
InMemoryArtifactStore,
InMemorySessionStore,
ModelManager,
} from "@foundry.sh/marbles/lib";
import { count } from "./count";
export interface CountResult {
readonly extension: string;
readonly files: number;
}
export async function countFiles(
root: string,
extension: string
): Promise<CountResult> {
const engine = new Engine({
artifacts: new ArtifactManager({ store: new InMemoryArtifactStore() }),
askable: false,
containers: () => Promise.reject(new Error("no sandbox runtime here")),
models: new ModelManager(),
root,
sessions: new InMemorySessionStore(),
workspaceId: "count-example",
});
engine.define(count);
try {
await engine.start();
return await engine.run<CountResult>("count", { extension });
} finally {
try {
await engine.stop();
} finally {
await engine.dispose();
}
}
}
Nothing here starts the Marbles process, reads .foundry/marbles, or writes
state. engine.run waits for the result; engine.launch returns a run ID
first, and engine.execute(count, input) runs a definition you have not
registered. Embedding the engine covers
persistence, agents, and shutdown.
To load a whole .foundry/marbles folder and run its triggers in your
process instead, use hostWorkspace,
using the package’s /workspace entry.
3. From an MCP client
An MCP client, usually an agent, starts the Marbles MCP server with
marbles mcp over STDIO and names the source. The server starts nothing,
so the workspace must already be hosted: run marbles attach first. This
program plays that client:
import { setTimeout as sleep } from "node:timers/promises";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
export interface McpCountOptions {
readonly home?: string;
readonly source: string;
}
const POLL_MS = 250;
function json(result: unknown): Record<string, unknown> {
const [block] = CallToolResultSchema.parse(result).content;
if (block?.type !== "text") {
throw new Error("The tool answered without text.");
}
return JSON.parse(block.text);
}
export async function countOverMcp(
options: McpCountOptions
): Promise<Record<string, unknown>> {
const args = ["mcp", "--source", options.source];
const env =
options.home === undefined
? undefined
: {
...Object.fromEntries(
Object.entries(process.env).filter(
(entry): entry is [string, string] => entry[1] !== undefined
)
),
FOUNDRY_HOME: options.home,
};
const client = new Client({ name: "count-example", version: "0.0.0" });
await client.connect(
new StdioClientTransport({
args,
command: "marbles",
...(env === undefined ? {} : { env }),
})
);
try {
const { runId } = json(
await client.callTool({
arguments: { input: { extension: ".ts" }, name: "count" },
name: "dispatch_workflow",
})
);
const deadline = Date.now() + 30_000;
for (;;) {
const run = json(
await client.callTool({ arguments: { runId }, name: "get_run" })
);
if (run.status !== "queued" && run.status !== "running") {
return run;
}
if (Date.now() >= deadline) {
throw new Error(
`Run ${String(runId)} did not settle within the polling window.`
);
}
await sleep(POLL_MS);
}
} finally {
await client.close();
}
}
dispatch_workflow returns a runId straight away; it is an
acknowledgement, not the result. get_run reads the run’s status and, once
it settles, its output. A run waiting on a person reports suspended, so
the loop stops there too. From a terminal, marbles watch <runId> follows
the same run’s output until it ends.
The run belongs to the Marbles process, not to the MCP connection. Closing
the client leaves the workspace hosted, its schedules and monitors running,
and any dispatched run going. Without a process that hosts the workspace,
dispatch_workflow returns an error that names marbles attach. The MCP reference
lists every tool, including the task tools.
What changes between them
| CLI | Embedded engine | MCP | |
|---|---|---|---|
| Where the step runs | The current engine generation of the Marbles process | Your process | The current engine generation of the Marbles process |
| Run history on disk | Yes, under the state root | Only if you pass state |
Yes, under the state root |
| Schedules and monitors | Run in the current generation | Only if you drive them | Run in the current generation |
| Who answers questions | The dashboard’s Feed | Your program, with askable: true |
The dashboard’s Feed |
| Waits for the result | Yes | run yes, launch no |
No; poll get_run |