Connect your agent
Mastyf sits between your agent and the tools it uses. Pick how your agent gets its tools and follow that section; the rest of the page doesn’t apply to you.
How it connects
Mastyf doesn’t sit next to the AI model. It sits between the agent and its tools. Whether the agent runs on Claude, GPT or a local model, every time it tries to do something (read a file, query a database, call an API), that call goes through the Mastyf gateway first. The gateway checks it against your policy, then either passes it to the tool or blocks it before the tool runs.
- 1. Your agent
- Any model and any framework. It asks to call a tool with some arguments.
- 2. Mastyf gateway
- Checks the call: patterns, schema and your policy, then an optional AI review for borderline cases. Every decision is logged.
- 3. Your tools
- MCP servers, APIs, databases, files. They only see calls the gateway allowed.
Supported clients
Find your agent below; the link takes you to its section.
| Your agent | How it connects |
|---|---|
| Claude Desktop, Cursor, Windsurf, Cline | Wrap its MCP servers with the CLI, or let the Shield app do it |
| An agent built with the OpenAI Agents SDK | Wrap its tool definitions |
| A LangChain agent | Guard each tool’s function |
| Your own code calling the Claude or OpenAI API | One HTTP check before each tool runs |
| Any other MCP client | Point it at the gateway instead of the MCP server; the gateway speaks stdio, HTTP, SSE, streamable HTTP and WebSocket |
Install the gateway
Every method except the Shield app needs the gateway running. It needs Node.js 18 or newer. Start it with your policy file; it listens on http://localhost:4000, where its local dashboard also runs.
npm install -g @mastyf_ai/server@4.1.12 mastyf-ai start --policy ./default-policy.yaml
Starting templates ship in the package’s policy-templates/ folder. Add --blocking-mode audit to record decisions without blocking while you tune the policy; the default is block.
Claude Desktop, Cursor, Windsurf, Cline
These apps get their tools from MCP servers listed in a config file. mastyf-ai wrap rewrites that file so each server is started through the gateway, which then starts the real server.
# See what would change (writes per-server configs, leaves the app's config alone) mastyf-ai wrap --client claude-desktop --policy "$PWD/default-policy.yaml"
# Apply it (backs up the app's config first) mastyf-ai wrap --client claude-desktop --policy "$PWD/default-policy.yaml" --apply
On Windows, wrap doesn’t work in this version because a script it needs is missing from the package. Use the manual setup in the developer quickstart instead, and start each server with node and its script path, because the gateway crashes on npx there.
Use --client cursor, windsurf, cline or auto for the other apps, then restart the app. Each server entry changes like this:
Before
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}After
"filesystem": {
"command": "<mastyf proxy wrapper>",
"args": ["--config", "mastyf-ai-configs/examples/filesystem.json", "--policy", "/path/to/default-policy.yaml"]
}| App | Config file it changes |
|---|---|
| Claude Desktop (macOS) | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Claude Desktop (Windows) | %APPDATA%\Claude\claude_desktop_config.json |
| Claude Desktop (Linux) | ~/.config/Claude/claude_desktop_config.json |
| Cursor | ~/.cursor/mcp.json |
| Windsurf | ~/.windsurf/mcp.json |
| Cline | ~/.config/cline/mcp_config.json |
To undo, restore the timestamped .bak copy that --apply saved next to the config file, then restart the app.
Shield desktop app
The no-terminal option. Shield finds Claude Desktop, Cursor and Windsurf on your machine and routes their MCP servers through itself. Decisions run locally, with no cloud round trip. Activate it with the license key from your dashboard.
OpenAI Agents SDK
With the gateway running, wrap your tool definitions before you turn them into tools. Each tool then asks the gateway before it runs, and only runs on a pass.
npm install @mastyf_ai/openai-agents-middleware
import { Agent, tool } from '@openai/agents';
import { z } from 'zod';
import { wrapToolsWithMastyfGuard } from '@mastyf_ai/openai-agents-middleware';
// Wrap the tool definitions, then build the tools from them.
const definitions = wrapToolsWithMastyfGuard(
[
{
name: 'read_file',
description: 'Read a file from the project',
parameters: z.object({ path: z.string() }),
execute: async ({ path }) => readFile(path, 'utf8'),
},
],
{
proxyUrl: 'http://localhost:4000',
apiKey: process.env.MASTYF_GATEWAY_KEY, // the gateway's DASHBOARD_API_KEY, if you set one
},
);
const agent = new Agent({ name: 'assistant', tools: definitions.map((d) => tool(d)) });
// A denied call throws "Mastyf blocked …" inside the tool instead of running it.| Option | Default | What it does |
|---|---|---|
proxyUrl | — | Where the gateway listens, usually http://localhost:4000. |
mode | 'block' | block: run only what the policy allows. warn: log denials and run anyway. audit: don’t check. |
failOpen | false | Run the tool when the gateway can’t answer. By default the call is blocked. |
apiKey | — | The gateway’s DASHBOARD_API_KEY, sent as a Bearer token, if you set one. |
timeoutMs | 10000 | How long to wait for the gateway. |
identityContext | — | userId and clientId of the person or app behind the call, for the audit log. |
blockedTools | [] | Tool names that are always denied, without asking the gateway. |
LangChain
Guard each tool’s function with a small helper that asks the gateway first, then build the tool with LangChain’s tool() as usual. Save the helper once and reuse it for every tool:
/** Run fn only if Mastyf passes the call. Anything else, including errors, blocks it. */
export function guarded<A extends Record<string, unknown>, R>(name: string, fn: (args: A) => Promise<R>) {
return async (args: A): Promise<R> => {
let verdict: { action?: string; reason?: string } = {};
try {
const res = await fetch('http://localhost:4000/api/policy/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tool: name, server: 'langchain-agent', arguments: args }),
signal: AbortSignal.timeout(10_000),
});
verdict = res.ok ? await res.json() : { reason: `HTTP ${res.status}` };
} catch (err) {
verdict = { reason: `Mastyf unreachable: ${err}` };
}
if (verdict.action !== 'pass') throw new Error(`Blocked by Mastyf: ${verdict.reason ?? 'denied'}`);
return fn(args);
};
}import { tool } from '@langchain/core/tools';
import { z } from 'zod';
import { guarded } from './guarded';
const readProjectFile = tool(
guarded('read_file', async ({ path }: { path: string }) => readFile(path, 'utf8')),
{
name: 'read_file',
description: 'Read a file from the project',
schema: z.object({ path: z.string() }),
},
);
// Give readProjectFile to your agent like any other tool.A blocked call throws, and LangChain reports the error back to the model as the tool’s result, so the agent can try something else. The same helper works for any framework whose tools are async functions.
Your own agent
If you wrote the tool-calling loop yourself against the Claude or OpenAI API, ask the gateway before you run each tool the model requests. Run the tool only when the answer is pass, and tell the model when a call was blocked so it can choose another approach.
POST http://localhost:4000/api/policy/test
Authorization: Bearer <DASHBOARD_API_KEY> (only if the gateway has one)
Content-Type: application/json
{ "tool": "delete_file", "server": "my-agent", "arguments": { "path": "/etc/passwd" } }
→ { "action": "block", "rule": "...", "reason": "...", "mode": "block" }Claude (TypeScript)
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
/** Ask Mastyf before running a tool. Anything but a clear "pass" is a no. */
async function mastyfAllows(tool: string, args: unknown) {
try {
const res = await fetch('http://localhost:4000/api/policy/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tool, server: 'my-agent', arguments: args }),
signal: AbortSignal.timeout(10_000),
});
const verdict = await res.json();
return res.ok && verdict.action === 'pass'
? { allowed: true }
: { allowed: false, reason: verdict.reason ?? `HTTP ${res.status}` };
} catch (err) {
return { allowed: false, reason: `Mastyf unreachable: ${err}` }; // fail closed
}
}
const message = await anthropic.messages.create({ model, max_tokens: 1024, tools, messages });
const results = [];
for (const block of message.content) {
if (block.type !== 'tool_use') continue;
const verdict = await mastyfAllows(block.name, block.input);
results.push({
type: 'tool_result',
tool_use_id: block.id,
is_error: !verdict.allowed,
content: verdict.allowed
? await runTool(block.name, block.input)
: `Blocked by Mastyf: ${verdict.reason}`,
});
}
// Send results back to Claude as the next user message.OpenAI (Python)
import json, requests
from openai import OpenAI
client = OpenAI()
def mastyf_allows(tool, args):
"""Ask Mastyf before running a tool. Anything but a clear "pass" is a no."""
try:
r = requests.post(
"http://localhost:4000/api/policy/test",
json={"tool": tool, "server": "my-agent", "arguments": args},
timeout=10,
)
verdict = r.json()
if r.ok and verdict.get("action") == "pass":
return True, ""
return False, verdict.get("reason", f"HTTP {r.status_code}")
except Exception as err:
return False, f"Mastyf unreachable: {err}" # fail closed
response = client.chat.completions.create(model=model, messages=messages, tools=tools)
for call in response.choices[0].message.tool_calls or []:
args = json.loads(call.function.arguments)
allowed, reason = mastyf_allows(call.function.name, args)
content = run_tool(call.function.name, args) if allowed else f"Blocked by Mastyf: {reason}"
messages.append({"role": "tool", "tool_call_id": call.id, "content": content})Send the tool’s arguments as arguments. Argument rules (paths, shell commands, injected text, secrets) only fire when the gateway can see them.
Link to Mastyf Cloud
Linking a gateway to your workspace syncs its policy from the dashboard, reports its decisions to Fleet, and lets you open its local dashboard from the cloud. Create an API key under Settings → API key, then set these on the gateway host. The Link a proxy page fills in your workspace ID.
MASTYF_AI_CONTROL_PLANE_URL=https://www.mastyf.ai MASTYF_AI_MULTI_TENANT_ENABLED=true MASTYF_AI_TENANT_ID=<your workspace ID> MASTYF_AI_CLOUD_API_KEY=<API key from Settings → API key> DASHBOARD_JWT_SECRET=<random, this host only: openssl rand -base64 32>
The gateway only ever needs your workspace’s API key. Never put Mastyf Cloud’s own secrets (AUTH_SECRET, LICENSE_JWT_SECRET) on a gateway host.
If the proxy is down
Mastyf is a security control, so when it can’t decide, the default is to block.
- OpenAI Agents SDK: the wrapped tools don’t run when the gateway is unreachable, errors, times out or gives an unexpected answer. Set
failOpen: trueto let calls through instead, ormode: 'warn'to log denials without blocking. - LangChain and other frameworks using the
guardedhelper: anything but apass, including a network error, blocks the call. - Wrapped desktop apps reach their MCP servers through the gateway, so if it stops, those tools stop with it until it’s running again.
- Your own agent: treat a network error or a non-
passanswer as a block, as the examples above do.