Beyond the defaults
Calling an MCP
Call tools on external MCP servers from within a capability.
How it works
The mcp key in craft.config.ts connects your Routecraft context to one or more remote MCP servers. Once they are registered, you can call any tool on those servers using .to(mcp('server:tool')) or .enrich(mcp('server:tool')) inside any capability.
Install
bun add @routecraft/ai
Register remote servers
List the servers your capabilities need to reach under the mcp key's clients in craft.config.ts:
// craft.config.ts
import { defineProject } from '@routecraft/routecraft'
import '@routecraft/ai'
export default defineProject({
mcp: {
clients: {
browser: { url: 'http://127.0.0.1:8089/mcp' },
search: { url: 'http://127.0.0.1:9000/mcp' },
github: { url: 'https://api.githubcopilot.com/mcp/', auth: { token: process.env.GITHUB_TOKEN! } },
},
},
})
Each key under clients is the server alias you use in your capabilities.
Call a tool
Use the server:tool shorthand in .to() to send the exchange body as tool arguments and replace it with the result:
// capabilities/web-search/route.ts
import { craft, simple } from '@routecraft/routecraft'
import { mcp } from '@routecraft/ai'
export default craft()
.id('web-search')
.from(simple({ query: 'Routecraft documentation' }))
.to(mcp('search:web_search'))
.log('info', 'Done', (ex) => ({ result: ex.body }))
Or use .enrich() with an aggregator such as only() to merge the result into the exchange body instead of replacing it:
// capabilities/enrich-order/route.ts
import { craft, http, only } from '@routecraft/routecraft'
import { mcp } from '@routecraft/ai'
export default craft()
.id('enrich-order')
.from(http({ path: '/orders/:id', method: 'GET' }))
.enrich(mcp('search:lookup_customer'), only((customer) => customer, 'customer'))
.to(http({ method: 'POST', url: 'https://crm.example.com/orders' }))
Bare .enrich(mcp(...)) behaves like .to(): the tool result replaces the body.
Custom argument mapping
By default, the exchange body is passed as-is to the tool. Use the args option to map the body to the exact shape the tool expects:
.to(mcp('browser:navigate', {
args: (exchange) => ({ url: exchange.body.targetUrl }),
}))
Full URL (no registration required)
If you only need to call a single external tool and do not want to register it globally, pass the URL directly:
.to(mcp({ url: 'http://127.0.0.1:8089/mcp', tool: 'navigate' }))
A URL that is not on this machine is https, on an inline call and on a registered client alike. Plain http to another host needs allowHttp: true beside the URL, and a redirect to another origin fails the call, except an http URL upgraded to https on the same host; the mcp adapter reference has the rule.
Servers behind a login
Some MCP servers take no API key: a person logs in once with OAuth, and the server accepts the tokens that login produced. Declare such a client with connect(), giving the client id you registered with its authorization server:
// craft.config.ts
import { defineProject } from '@routecraft/routecraft'
import { connect } from '@routecraft/ai'
export default defineProject({
mcp: {
clients: {
mail: {
url: process.env.MAIL_MCP_URL!,
auth: connect({
clientId: process.env.MAIL_CLIENT_ID!,
scopes: ['mail.read'],
}),
},
},
},
})
Then log in from the project directory, on a machine with a browser:
craft connect mail
The command opens the authorization page, waits for the redirect on http://127.0.0.1/callback (register that as a redirect URI; a server that follows RFC 8252 accepts any port on it, and --port pins one for a server that does not), and writes the credential to the credential store. The application reads it from there, refreshes the access token when the server answers 401, and writes the rotated refresh token back. The write is a compare-and-swap on the record's version, so an instance holding an older credential never writes it over a newer one. Two instances that refresh at the same moment both send the same refresh token; a server that rotates refresh tokens refuses the later one, and that instance reads what the other stored and carries on.
A client with no stored credential, or whose refresh the authorization server refuses, is disabled with the reason run craft connect mail: its tools leave every agent with a warning, a call to it is refused, and the rest of the application runs. It stays disabled until the application restarts, so restart after craft connect to bring it back. An authorization server that does not answer fails that one call and leaves the client enabled. craft connect --list shows what each client holds, craft connect --all logs in every client that holds nothing, and craft disconnect mail removes a credential.
Getting the credential to a server
A server has no browser. Log in on your own machine with a key set, export the credential, and hand the server the seed and the same key:
export ROUTECRAFT_CREDENTIALS_KEY="$(openssl rand -base64 32)"
craft connect mail --export
The command prints one line, the seed, sealed with AES-256-GCM under the key. Set ROUTECRAFT_CREDENTIALS_SEED to it and ROUTECRAFT_CREDENTIALS_KEY to the key on the server. On boot the server imports the seed into its store when the store holds nothing for the client, or holds a credential from an earlier login. A credential the server has refreshed since keeps its login time, so restarting with the same seed never overwrites a newer refresh token. Mount the store's directory (.routecraft/ by default, or the path in credentials.store) on a volume, so a redeploy keeps the refreshed credential. Instances that share the store must share it on one host: SQLite locking over a network file system such as NFS is unreliable, so a store on NFS can lose a refresh.
The machine you exported from still holds the same refresh token. Most authorization servers rotate it on every refresh, so whichever side refreshes first leaves the other with a refused token. After exporting, run craft disconnect <client> there, or do not run the application on that machine.
With the key set, the store also seals every credential at rest. A credential written before the key was set stays plain until it is next written, by a refresh or a login; run craft connect <client> to seal it now. Without the key the store is a plain file readable by its owner only (mode 0600), and --export refuses. The key must be random, at least 32 characters, such as openssl rand -base64 32 prints: it is used as given, not stretched like a password.
Options
connect() works on a client registered under mcp.clients or mcpPlugin({ clients }). An inline mcp({ url }) has no name to keep a credential under, so it takes a static auth only.
Guardrails: raw, guarded, or wrapped
A raw MCP tool carries no per-call policy. When an agent calls one, the credentials registered on the client are what reach the server; the agent does not forward the caller's principal to the MCP hop (this keeps the two trust boundaries separate: see Securing capabilities). So a raw tool has no identity check, no caching, and no timeout of its own. You add those on the Routecraft side, and there are three tiers to choose from.
Pick the lowest tier that covers what you need. The moment you need caching, a timeout, throttling, retry, a fallback, or an audit trail, you are at tier 3: a guard is a single predicate with no state and no clock, so it can answer "may John call this?" but it cannot hold a cache or a deadline.
Tiers 1 and 2 are covered on the agent plugin reference. For tier 3, put a route in front of the tool. A route per tool starts at a direct() endpoint, ends in the .to(mcp(...)) call you have already seen, and keeps the guardrails on the steps between; a route over a vendor's whole server starts at the proxy source instead, shown below.
// capabilities/github-create-issue/route.ts
import { mcp } from '@routecraft/ai'
import { craft, direct } from '@routecraft/routecraft'
export default craft()
.id('github-create-issue')
.authorize({ roles: ['maintainer'] }) // per-call principal check, before the source
.from(direct())
.to(mcp('github:create_issue'))
Hand the agent the governed route instead of the raw tool. The same underlying tool can be exposed both ways: wrap the ones that need policy, leave harmless read-only tools raw. A route per tool is the shape for a tool whose schema or name you want to change; for a vendor's whole server, or a tool you want exposed under the remote's own contract, a proxy route governs it without a route per tool, and an agent's MCP(server:tool) reference goes through it on its own.
agent({
tools: tools([
'Direct(github-create-issue)', // governed: authorized and auditable
'MCP(github:list_issues)', // raw: read-only, fine ungoverned
]),
})
Why a route and not a richer guard? A guard runs once and holds no state. Caching, timeouts, throttling, retries, and fallbacks each need something wrapped around the call with its own state and lifecycle, which is exactly what a route step is. A wrapped route gives you authorize(), error() fallbacks, cache(), throttle(), timeout(), retry(), and .log('info', 'Seen', (ex) => ({ body: ex.body })) for an audit trail, all without changing how the agent consumes the tool. The route is the only place that behaviour can ever live.
Governing a remote server's tools
A vendor's server lists dozens of tools, and wrapping each in a route is the slow way to put policy on them. A route can instead be the tools of a client registered under the mcp key's clients, or one of them: the source names the client, the hop forwards the call, and the chain and the steps between are the policy.
// capabilities/github/route.ts
import { mcp, McpHeadersKeys, type McpToolAnnotations } from '@routecraft/ai'
import { craft, type Exchange } from '@routecraft/routecraft'
const readOnlyTool = (ex: Exchange) =>
(ex.headers[McpHeadersKeys.ANNOTATIONS] as McpToolAnnotations | undefined)?.readOnlyHint === true
export default craft()
.id('github')
.authorize({ scopes: ['github:read'] })
.cache({ ttl: '2m', when: readOnlyTool })
.from(mcp({ proxy: 'github:*' }))
.to(mcp('github:*'))
Every tool the github client lists is now served by your MCP server as github_<tool>, authorized on the caller's principal, with the read-only ones cached; the exceptions are the server's own tools filter, a name a local route already holds, and a prefixed name that is not a valid tool name, each skipped with a warning. A tool that needs its own shaping gets its own route, which wins over the star route for that tool, live or not: while its own route is held back by .enabled(), nothing serves the tool, and the star route does not take it over:
// capabilities/github-create-issue/route.ts
import { mcp } from '@routecraft/ai'
import { craft } from '@routecraft/routecraft'
export default craft()
.id('github-create-issue')
.authorize({ roles: ['maintainer'] })
.from(mcp({ proxy: 'github:create_issue' }))
.transform((args) => {
const issue = args as { title: string; body?: string }
// A compact uppercase IBAN never reaches GitHub; a real redaction normalises first.
return { ...issue, body: issue.body?.replace(/\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b/g, '[iban]') }
})
.to(mcp('github:create_issue'))
Steps above the hop see the arguments; throw to refuse, return to rewrite. Steps below it see the result, with the same two moves. A .defer() before the hop, or an approval hook on a tag, parks the call until a person answers. The caller's principal selects policy and never reaches the remote; the hop authenticates with the client's registered auth.
An agent that lists MCP(github:create_issue) goes through that route too, so your own agent is under the same policy as an external client. The mcp adapter reference has the options, the headers a proxied exchange carries, the naming rules, and the migration from a hand-written wrapping route or a former mcpPlugin({ proxy }) entry.
Pinning a server's tools
A remote server decides what its tools are called, what their descriptions say and what arguments they take, and it can change any of that between two listings. A description is text a model reads, so a server that changes one changes what your agent is told. Pinning holds a client to the definitions someone reviewed.
Set pins on the client, write the lockfile, and commit it:
// craft.config.ts
import '@routecraft/ai'
import { defineProject } from '@routecraft/routecraft'
export default defineProject({
mcp: {
clients: {
books: {
url: 'https://mcp.example.com/mcp',
pins: { added: 'hold', changed: 'hold' },
},
},
},
})
craft mcp pin
git add mcp.lock && git commit -m "chore: approve the books tools"
craft mcp pin lists every pinned client and writes mcp.lock: each tool's full definition, a hash of it, and a class. Approval is the commit. The file is JSON with sorted keys, and every character outside printable ASCII is escaped (\n and the other short JSON escapes, \u for the rest), so the diff of a later craft mcp pin shows exactly what the server changed, including a character you could not otherwise see.
From then on each listing is compared with the file:
A withheld tool is not listed by your MCP server, and is not offered to an agent. A caller of your MCP server is told the tool is unknown, and a call that names it from inside the application, a route's own .to(mcp('books:new_tool')) included, is refused with AI2004. A locked tool the server stops listing is reported and is no longer callable. Nothing is approved at run time: to accept a change, run craft mcp pin, read the diff, commit, and restart.
With pins set and no readable lockfile, the application does not start. A client without pins is not pinned, and with no pinned client no file is read.
The class of a tool
Each locked tool has a class: read, write or destructive. craft mcp pin proposes one for a new tool from the server's hints (readOnlyHint: true gives read, destructiveHint: false gives write, anything else destructive), you correct it in the file, and a later pin keeps what the file says. It is the reviewer's statement about the tool, where annotations are the server's.
A proxy route reads it from the routecraft.mcp.class header, and a star route's exclude function is handed it:
// capabilities/books/route.ts
import { mcp, McpHeadersKeys } from '@routecraft/ai'
import { craft, type Exchange } from '@routecraft/routecraft'
const reads = (ex: Exchange) => ex.headers[McpHeadersKeys.CLASS] === 'read'
export default craft()
.id('books')
.authorize({ roles: ['finance'] })
.cache({ ttl: '2m', when: reads })
.from(mcp({ proxy: 'books:*', exclude: (tool) => tool.class === 'destructive' }))
.to(mcp('books:*'))
The class is destructive whenever nobody approved what is being served: the client is not pinned, the tool is new and served under added: 'serve', or its definition changed and is served under changed: 'serve' or 'warn'. A rule written on read therefore never applies to a definition nobody read. For a pinned client the tags an agent's tool selector sees (read-only, destructive) come from the class too, not from the server's annotations.
The mcpPlugin reference has the options and the lockfile format, and craft mcp pin the command.
Related
Expose to an agent
Run your own capabilities as MCP tools for AI clients.
MCP tool
A copyable capability exposed as an MCP tool, and one that calls a remote MCP server.
mcp
The mcp() adapter: every option for serving a tool and for calling one.