Skip to content

Call an MCP tool from a Machine ​

Call a tool of an MCP server as an Effect, after a person approves the call, and route the Machine on its output.

An Agent that holds MCP tools calls them with no approval, within its allowlist. When a call needs the approval of a person, the Machine makes the call: the Agent picks, a Gate waits for the approval, and an mcp Effect calls the tool. The output of the Effect is the answer to the pick. Thus the approval is in the record of the run, it stays across a restart, and the Machine routes on it.

In this Workflow, the Machine first reads a resource and gets a prompt from the server. Then a writer finds the channel with find_channel, and asks to post the announcement with post_message. A person approves the message, and the Machine posts it. Save the file as workflows/announce.ts in your Instance:

ts
import { assign } from "xstate";
import { z } from "zod";
import {
  agent,
  answer,
  defineEvent,
  fail,
  fromPick,
  jr2Setup,
  mcp,
  type McpCallOutput,
  type McpReadOutput,
} from "@jr2/orchestrator";

// The writer's picks. Each one is a tool on its Menu, and the Machine makes the MCP call.
const findChannel = defineEvent({
  name: "find_channel",
  description: "Find a channel by a part of its name. The answer lists the channels that match.",
  input: z.object({ query: z.string().describe("A part of the channel's name.") }),
});
const postMessage = defineEvent({
  name: "post_message",
  description: "Post one message to a channel. A person approves it first. The answer tells if it went out.",
  input: z.object({ channel: z.string().describe("The channel id."), text: z.string().describe("The message.") }),
});
const finished = defineEvent({
  name: "finished",
  description: "Call this after the announcement went out.",
  input: z.object({}),
});

// The answers of the person at the Gate. The writer cannot send them.
const approve = defineEvent({ name: "approve", description: "Post this message.", input: z.object({}) });
const reject = defineEvent({
  name: "reject",
  description: "Do not post this message. Say why.",
  input: z.object({ reason: z.string().min(1) }),
});

const door = z.object({ version: z.string().describe("The version to announce, such as 1.4.0.") });

type Input = z.infer<typeof door>;
type Ctx = Input & { rules?: string; brief?: string; channel?: string; text?: string; posted: boolean };

// What the writer reads when the server did not answer as a tool does. `reason` says why.
const notReturned = (output: McpCallOutput): string =>
  output.outcome === "unknown"
    ? `jr2 cannot tell if the call acted: ${output.reason}. Do not call it again.`
    : `The call did not run: ${"reason" in output ? output.reason : output.outcome}`;

// The text of a read or a prompt, or undefined when the server did not give it.
const textOf = (output: McpReadOutput): string | undefined => (output.outcome === "returned" ? output.text : undefined);

export const machine = jr2Setup({
  types: {} as { context: Ctx; input: Input },
  events: [findChannel, postMessage, finished, approve, reject],
  actors: {
    writer: agent({
      model: "anthropic/claude-haiku-5-5",
      instructions: "You write short release announcements for the team chat.",
      workspace: "none",
    }),
    // A resource and a prompt of the server: the Machine reads them before the writer starts.
    rules: mcp.read("slack-acme", "guide://announcements", { idempotent: true }),
    brief: mcp.prompt("slack-acme", "announcement", { input: z.object({ version: z.string() }), idempotent: true }),
    // A search changes nothing, so it is safe to send two times.
    search: mcp.call("slack-acme", "find_channel", { input: z.object({ query: z.string() }), idempotent: true }),
    // A post changes the channel, so jr2 sends it at most one time.
    post: mcp.call("slack-acme", "post_message", { input: z.object({ channel: z.string(), text: z.string() }) }),
    fail: fail(),
  },
}).createMachine({
  id: "announce",
  input: door,
  context: ({ input }) => ({ version: input.version, posted: false }),
  on: { "agent.fault": ".failed" },
  initial: "reading",
  states: {
    reading: {
      invoke: {
        src: "rules",
        onDone: [
          {
            guard: ({ event }) => textOf(event.output) !== undefined,
            target: "briefing",
            actions: assign({ rules: ({ event }) => textOf(event.output) }),
          },
          { target: "failed" },
        ],
      },
    },
    briefing: {
      invoke: {
        src: "brief",
        input: ({ context }) => ({ version: context.version }),
        onDone: [
          {
            guard: ({ event }) => textOf(event.output) !== undefined,
            target: "writing",
            actions: assign({ brief: ({ event }) => textOf(event.output) }),
          },
          { target: "failed" },
        ],
      },
    },
    // The writer's state. Its Turn lasts until `finished` leaves it.
    writing: {
      invoke: {
        src: "writer",
        input: ({ context }) => ({ prompt: `${context.brief}\n\nThe rules of the channel:\n${context.rules}` }),
      },
      on: { finished: { guard: ({ context }) => context.posted, target: "done" } },
      initial: "ready",
      states: {
        ready: {
          on: {
            find_channel: "searching",
            post_message: {
              target: "approving",
              actions: assign({ channel: ({ event }) => event.channel, text: ({ event }) => event.text }),
            },
          },
        },
        // The pick enters the Effect's state, so fromPick gives its `query` to the tool's arguments.
        searching: {
          invoke: {
            src: "search",
            input: fromPick(findChannel),
            onDone: {
              target: "ready",
              // The writer reads this text as the answer to its find_channel pick.
              actions: answer(({ event }) =>
                event.output.outcome === "returned" ? event.output.text : notReturned(event.output),
              ),
            },
          },
        },
        // A person approves the message. While the Gate is open, the post_message pick is outstanding.
        approving: {
          invoke: {
            src: "gate",
            input: ({ context }) => ({ meta: { channel: context.channel, text: context.text } }),
          },
          on: {
            approve: "posting",
            reject: { target: "ready", actions: answer(({ event }) => `The editor rejected it: ${event.reason}`) },
          },
        },
        // The Gate came between the pick and the Effect, so the input comes from the context.
        posting: {
          invoke: {
            src: "post",
            input: ({ context }) => ({ channel: context.channel!, text: context.text! }),
            onDone: [
              {
                guard: ({ event }) => event.output.outcome === "returned" && !event.output.isError,
                target: "ready",
                actions: [assign({ posted: true }), answer(() => "The message went out.")],
              },
              {
                target: "ready",
                actions: answer(({ event }) =>
                  event.output.outcome === "returned"
                    ? `The tool failed: ${event.output.text}`
                    : notReturned(event.output),
                ),
              },
            ],
          },
        },
      },
    },
    done: { type: "final" },
    // Not a final state: the run ends `failed`, with the reason.
    failed: { invoke: { src: "fail", input: { reason: "the announcement did not go out" } } },
  },
});

The writer uses the model of the tab. The mcp Effects name the server slack-acme. Declare it in the mcp block of jr2.config.ts, beside the fields and the entries that are there:

ts
import { defineConfig } from "@jr2/orchestrator";

export default defineConfig({
  // The two tokens. The values come from .env.
  secrets: [
    { name: "SLACK_ACME_TOKEN", value: process.env.SLACK_ACME_TOKEN },
    { name: "SLACK_PARTNER_TOKEN", value: process.env.SLACK_PARTNER_TOKEN },
  ],
  // Two servers of one service, each with its own token. The names are yours.
  mcp: {
    "slack-acme": { url: "https://mcp.slack.example/mcp", secret: "SLACK_ACME_TOKEN" },
    "slack-partner": { url: "https://mcp.slack.example/mcp", secret: "SLACK_PARTNER_TOKEN", timeout: "90s" },
  },
});

https://mcp.slack.example/mcp is an example. Write the URL of the MCP endpoint of your service, and put the token in .env. Give an Agent MCP tools tells what each field of the block does. guide://announcements and announcement are examples too: write a resource and a prompt that your server has.

Call a tool ​

mcp.call(server, tool, options) calls one tool. server is a name of the mcp block, and tool is the name of the tool on the server. Put the Effect under actors in jr2Setup, and invoke it by its key from a state. The options:

  • input: the zod schema of the input of the Effect. jr2 parses the input with it before the call. The parsed input is the arguments of the tool. With no schema, the input of the invoke is the arguments as it is.
  • timeout: how long jr2 waits for the answer, such as "30s". The default is the timeout of the server in jr2.config.ts, 60 seconds when it sets none. After it, the outcome is unknown.
  • maxBody: how many bytes of text, and of structured as JSON, the output keeps. The default is 65536.
  • idempotent: true when it is safe to send the call two times, such as a search. The default is false. jr2 does not read the idempotentHint of the tool, because the server is not the author of the Machine.

An mcp Effect runs in the Instance Effector. The secret of the server is its Effect secret: jr2 up puts it in the Instance Effector, and the Effector sends it as Authorization: Bearer <value>. The Agent and the Orchestrator never read the value. You can invoke an mcp Effect in a Machine with no Workspace. An mcp Effect calls a remote server only.

Route on the output ​

Each outcome is output for onDone. Route on outcome (McpCallOutput):

  • returned, with isError, text, and structured when the result has structuredContent. isError is true when the tool ran and says that it failed. text joins the text of the result. A part that is not text is one line that names its kind. Past maxBody, jr2 cuts text, drops structured, and sets truncated.
  • refused: the call did not run. The server answered an HTTP 3xx or 4xx status, such as 401 for a wrong token. Or it refused the request as one that it cannot run, such as an unknown tool or bad arguments.
  • unreachable: jr2 sent nothing of the call. The server did not answer, or it does not speak MCP, or it speaks a revision of MCP that jr2 does not speak.
  • input-required: the server asked for input, which jr2 does not give. The tool can have started. jr2 does not send the call again.
  • unknown: jr2 sent the call, and no answer came, or the server answered with an error after it got the call. The tool can have acted. jr2 does not send it again, unless it is idempotent.

Each outcome other than returned has a reason in words. The union is open: give the rest a last arm with no guard. jr2 changes each value of an Effect secret in the output to [secret:<name>].

In the example, the writer reads the result of each call as the answer to its pick. After unknown, it reads that jr2 cannot tell if the call acted. The Machine does not send the call again by itself: the writer decides if it posts again.

Approve the call first ​

The post_message pick goes to approving, a child state of the writer's state that invokes a Gate. The writer waits for the answer to its pick while the Gate is open. A person answers the Gate with approve or reject:

  • approve goes to posting, which invokes the mcp Effect. Its output is the answer to the pick.
  • reject goes back to ready, and the writer reads the reason as the answer.

The pick enters approving, and approve enters posting. Thus the input of post comes from the context, where the pick put the channel and the text. Answer a Gate tells how a person answers.

Give the input from a pick ​

When a pick enters the state of the Effect, fromPick(def) gives each param of the pick to the key of the same name. In searching, the query of find_channel goes to the query of the tool's arguments. fromPick(def, fill) adds the keys that fill gives, so that the Machine sets a key that the Agent cannot choose. TypeScript checks the keys against the input of the Effect. A Gate between the pick and the Effect gives a different event, so use the context there, as posting does. Run a command or call a URL with an Effect gives the rules of fromPick.

Read a resource and get a prompt ​

  • mcp.read(server, uri, options) reads one resource. uri is the URI of the resource on the server. The output (McpReadOutput) is returned with text, the text of the contents, and structured, the list of the contents. A binary part is given only as its type and its size.
  • mcp.prompt(server, name, options) gets one prompt. name is the name of the prompt. The input schema is the arguments of the prompt, and each field is a string. The output is returned with text, the text of the messages, and structured, the list of the messages.

Their other outcomes are those of a call, with no isError. uri and name are always yours. The options are the options of a call: input for a prompt, timeout, maxBody and idempotent. A read and most prompts change nothing, so the example marks them idempotent.

Bind the server or the tool of a packaged Machine ​

A Machine from a package can leave the server and the tool of an mcp Effect Open: mcp.call(open, open, { input }). Bind them with effects, by the slot of the Effect, on the line that registers the Machine, such as customize(machine, { effects: { post: { server: "slack-acme", tool: "post_message" } } }). Bind only the part that is Open: { server } or { tool }. The server of mcp.read and mcp.prompt can be Open too. Bind a shipped Machine's Open parts tells more.

What jr2 check shows ​

Run jr2 check. It reads each Effect without running it, and it shows what the Effect runs, and where. jr2 up runs the same check before it converges:

sh
jr2 check
text
jr2 check — instance "my-instance" (no cluster)
typecheck: tsc --noEmit (the instance's own compiler)
effects: workflow "announce" — what it runs outside itself (ADR-0067)
  rules: mcp read slack-acme — the server's timeout, in the Instance Effector, idempotent
  brief: mcp prompt slack-acme — the server's timeout, in the Instance Effector, idempotent
  search: mcp call slack-acme/find_channel — the server's timeout, in the Instance Effector, idempotent
  post: mcp call slack-acme/post_message — the server's timeout, in the Instance Effector
failures: workflow "announce" — the states that fail the run (ADR-0073)
  announce.failed: invokes fail
seats: workflow "announce" — who may send what, per state (ADR-0015)
  announce.writing agent:writer: [find_channel, finished, post_message]
  announce.writing.approving gate: [approve, reject]
agents: writer (carried by 2 workflow machine(s))
check: passed — 2 workflow(s): announce, ping; `jr2 up` stages the Assembly and converges the cluster after the same check

seats shows that only the Gate takes approve and reject. Thus the writer cannot approve its own message.

Rules ​

When you call mcp.call(), mcp.read() or mcp.prompt(), it refuses:

  • a server name that does not have the form of a name of the mcp block, or that is jr2: mcp.<op>(server): "<server>" is not a server name — a name of the mcp block of jr2.config.ts, lowercase letters, digits and -, not "jr2"; or `open`, which the composer binds (ADR-0079)
  • an empty tool, URI or prompt name. <what> is tool, uri or prompt name: mcp.<op>(): the <what> is a non-empty string
  • open for a URI or a prompt name: mcp.<op>(): its <what> is the author's, never Open — only a call's tool is (ADR-0079)
  • a timeout that is not a positive duration: mcp: timeout "<timeout>" is not a positive duration (like "30s", "2m")
  • a maxBody that is not a positive whole number: mcp({ maxBody }): a positive number of bytes
  • a field of a prompt's input that is not a string: mcp.prompt("<name>"): the input field "<key>" is not a string schema, and a prompt's arguments are strings (MCP's prompts/get)

jr2 check and jr2 up refuse:

  • a server that the mcp block does not declare: refusing: workflow "<workflow>": the mcp Effect "<slot>" names the MCP server "<server>", which the mcp block declares "<names>" — declare it in jr2.config.ts: mcp: { "<server>": { url: "https://<host>/mcp", secret: "<SECRET>" } }, or name a declared remote server (ADR-0079)
  • a stdio server: refusing: workflow "<workflow>": the mcp Effect "<slot>" names the stdio MCP server "<server>" — an mcp Effect runs in the Instance Effector, which starts no program, so it calls a remote server only: declare one for it in jr2.config.ts, mcp: { "<server>": { url: "https://<host>/mcp", secret: "<SECRET>" } } (ADR-0079)
  • an Open part that nobody bound. <parts> is server, tool, or server and tool: refusing: workflow "<workflow>" leaves the <parts> of Effect "<slot>" open — bind it where the Machine is registered: export const machine = customize(<import>, { effects: { <slot>: { server: "<name>", tool: "<tool>" } } }) (ADR-0054). The binding holds only the parts that are Open.

customize() refuses a binding that has no key, or a key that is not an Open part of the Effect. <parts> is the Effect's Open parts: customize(): the mcp Effect "<slot>" leaves its <parts> Open — bind it with <binding> (ADR-0054). A binding that leaves out one Open part leaves that part Open, and jr2 up refuses it as above.

When an mcp Effect starts, it refuses an input that its input schema does not accept. The Effect takes its onError route, and each problem is <path>: <message>, with ; between them: mcp "<slot>": its input does not match the definition's input schema — <path>: <message>. With no schema, it refuses an input that is not an object: mcp "<slot>": its input is the request's arguments, an object. A prompt refuses an argument that is not a string: mcp.prompt: the argument "<key>" is <type>, and a prompt's arguments are strings.

The docs of Kit version 0.8.0. Each page is also at its .md URL.