Skip to Content
ZeroLeaksDocs
Shield SDKProvider wrappers

MCP

Check MCP tool lists for tool poisoning, tool results, resources, and prompts for injection, and tool calls against a tool policy.

shieldMcpClient wraps a Client from @modelcontextprotocol/sdk and replaces listTools, callTool, readResource, and getPrompt. It excludes flagged tools from tool lists and checks what the server returns before your agent passes it to a model. With a tool policy, it refuses tool calls the policy doesn't allow.

Usage

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { shieldMcpClient } from "@zeroleaks/shield/mcp";

const client = shieldMcpClient(new Client({ name: "agent", version: "1.0.0" }), {
  onToolFlagged: (tool, result) => {
    console.warn(`Dropped MCP tool ${tool.name}`, result.issues, result.result.matches);
  },
});
await client.connect(new StreamableHTTPClientTransport(new URL(serverUrl)));

const { tools } = await client.listTools(); // flagged tools left out
const result = await client.callTool({ name: "search", arguments: { query } }); // checked

What Shield checks

MethodCheck
listToolsscanTools() on the tools the server returned. See Tool lists.
callToolBefore the server is called: the tool, its arguments, and the tool policy. See Tool calls. After it returns: detection on the text of the result.
readResourceDetection on the text of every entry in contents
getPromptDetection on the prompt's description and the content of every message, whatever its role

With onDetection: "block", an injection throws InjectionDetectedError with source: "tool" and the result is not returned. With "warn", it is returned.

Tool lists

A tool is flagged when detection finds instructions in its description or input schema, or when scanTools() reports an issue, such as a duplicate name or a definition that changed since it was pinned. onFlaggedTools sets what happens to flagged tools:

ModeBehavior
"drop" (default)Returns a copy of the result without the flagged tools
"throw"Throws one InjectionDetectedError with source: "tool" for every flagged tool in the list
"warn"Returns the list unchanged

Pinning

The first time listTools returns a tool unflagged, the client pins its definition. When a later list returns a different definition for that name, the tool is flagged as changed_since_pinned until you delete its entry from pins.

By default, pins last for the lifetime of the wrapped client. To keep them across restarts, pass your own object and save it:

import { readFile, writeFile } from "node:fs/promises";

const pins = JSON.parse(await readFile("mcp-pins.json", "utf8").catch(() => "{}"));
const client = shieldMcpClient(mcp, { pins });
const { tools } = await client.listTools(); // new tools are added to pins
await writeFile("mcp-pins.json", JSON.stringify(pins));

pins: false turns pinning off.

When a server's tools change

A server that sends notifications/tools/list_changed can change its tools after you listed them. The SDK's listChanged option refreshes the list automatically by default, but it calls the unwrapped client, so the tools it passes to onChanged are not checked. Disable that refresh and call the wrapped client's listTools() instead:

const mcp = new Client(
  { name: "agent", version: "1.0.0" },
  {
    listChanged: {
      tools: {
        autoRefresh: false,
        onChanged: async () => {
          const { tools } = await client.listTools(); // checked
          setTools(tools);
        },
      },
    },
  }
);
const client = shieldMcpClient(mcp);

Tool calls

Before callTool reaches the server, the wrapper runs three checks in order:

CheckBehavior
Flagged toolThrows InjectionDetectedError for a tool the latest listTools flagged. This blocks calls by name to a tool that was dropped from the list.
ArgumentsRuns scanOutputText() on the arguments and throws OutputBlockedError for any high or critical finding, such as a credential.
Tool policyWith policy, throws ToolPolicyError when the tool policy refuses the call.

Tool policy

Pass a policy from createToolPolicy() as policy:

import { createToolPolicy } from "@zeroleaks/shield";

const policy = createToolPolicy({
  deny: ["delete_*"],
  rules: {
    get_issue: { labels: ["untrusted"] },
    create_issue: { labels: ["sink"], maxCalls: 3 },
  },
});
const client = shieldMcpClient(mcp, { policy });
const { tools } = await client.listTools(); // declared to the policy
await client.callTool({ name: "get_issue", arguments: { number: 7 } }); // recorded as untrusted
await client.callTool({ name: "create_issue", arguments: { title, body } }); // throws ToolPolicyError

Each listTools declares the tools it returns to the policy. Each callTool is checked with policy.checkAsync() before the server is called, and each result is recorded, flagged when detection found an injection in it.

A policy holds one session's state, while an MCP client often serves many sessions. Wrap the shared Client once per session with a separate policy.

Options

shieldMcpClient takes detect, scanToolResults, onDetection, and onInjectionDetected from the shared options. The other shared options don't apply: nothing is hardened, and the wrapper doesn't guard model output.

OptionTypeDefaultDescription
detectLocalDetectOptions | false{}Sets the options that scanToolResults: true (the default) uses. There are no user messages to check.
scanToolsScanToolsOptions | falsethe tool result detect optionsscanTools() options for tool lists, or false to leave them unchecked. Defaults to scanToolResults when that is an object, else detect.
onFlaggedTools"drop" | "throw" | "warn""drop"What happens to flagged tools. See Tool lists.
onToolFlagged(tool: ToolDefinition, result: ToolScanResult) => voidnoneCalled with each flagged tool and its scan result, in every mode
pinsToolPins | falsepins kept for the life of the clientPass an object to keep pins across sessions. The client adds new tools to it. See Pinning.
blockFlaggedToolCallsbooleantrue, except with onFlaggedTools: "warn"Refuse callTool for a tool the latest listTools flagged
scanArgumentsScanOutputOptions | falsesecrets and exfiltrationscanOutputText() options for tool call arguments, or false to skip the scan
policyToolPolicynoneA policy from createToolPolicy() for this session. See Tool policy.

Limitations

  • A blocked tool call has already run on the server. Shield only keeps its result from reaching the model.
  • Each listTools call checks only the page of tools it returns, so duplicate names across two pages are not detected.
  • listResources(), listResourceTemplates(), listPrompts(), complete(), experimental.tasks.callToolStream(), and raw request() calls are not checked.
  • Sampling and elicitation requests from the server, and notifications such as log messages, are not checked.
  • Tool call arguments are checked for high and critical output findings only, not for injection or prompt leaks.
  • A tool policy checks arguments against the tool's schema only for the keywords under Argument schemas.
  • Images, audio, and blobs with other MIME types are not read. The resources that resource links point to are not fetched.
  • The SDK's automatic list refresh calls the unwrapped client. See When a server's tools change.

See Limitations for what no integration scans.

On this page