MCP server security best practices for third-party servers
How to connect a third-party MCP server safely: review the catalog for tool poisoning, scope the credential, enforce authorization and approval on the server, with the AIVAX gateway settings checked against the code.
Most MCP server security best practices are written for whoever builds the server. Connecting someone else's server is the other half of the problem, and it starts before the first tool call: the moment a gateway lists a server's tools, that server's descriptions become text in the model's context, written by a party you may not control. I treat a third-party MCP source as two grants at once. The server gets to talk to the model, and the model gets to propose arguments to whatever systems stand behind that server.
The official Security Best Practices page for the current 2026-07-28 revision covers the server-side attacks in detail. What follows is the connecting side, worked through on the AIVAX gateway.
A tool description is input the model obeys
Microsoft's write-up of indirect prompt injection in MCP calls the attack tool poisoning: instructions hidden in a tool's description, which the model reads when it decides what to do next. Nothing has been called yet and the user has typed nothing suspicious. Tool results can carry the same payload later, and so can server instructions and skills wherever a host imports them.
Before enabling a server I read its whole catalog the way I would read a new dependency: tool names, descriptions, the description of every schema property, and any usage instructions the server advertises. Anything that addresses the model about secrets, other tools or policy is a reason to walk away.
That review only holds while the catalog stays the one you read. A remote server can edit a description without changing its URL, and a gateway that re-lists tools will pass the edit along. Anthropic's connector has a beta that pins a server's tool list for this reason. An AIVAX MCP source caches discovery for 600 seconds by default (0 to 86400). To catch an edit sooner than that, I keep a digest of the reviewed catalog and compare it on a schedule shorter than cacheDuration:
const [url, token] = [process.argv[2], process.env.MCP_TOKEN];
const headers = {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
...(token && { Authorization: `Bearer ${token}` })
};
async function rpc(body, extra = {}) {
const res = await fetch(url, { method: "POST", headers: { ...headers, ...extra }, body: JSON.stringify(body) });
const text = await res.text();
const data = text.startsWith("event:") || text.startsWith("data:")
? text.split("\n").find(l => l.startsWith("data:"))?.slice(5)
: text;
return { session: res.headers.get("mcp-session-id"), json: data ? JSON.parse(data) : null };
}
const init = await rpc({
jsonrpc: "2.0", id: 1, method: "initialize",
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "catalog-review", version: "1" } }
});
const session = init.session ? { "Mcp-Session-Id": init.session } : {};
await rpc({ jsonrpc: "2.0", method: "notifications/initialized" }, session);
const tools = [];
for (let cursor; ;) {
const page = (await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list", params: cursor ? { cursor } : {} }, session)).json.result;
tools.push(...page.tools);
if (!(cursor = page.nextCursor)) break;
}
tools.sort((a, b) => a.name.localeCompare(b.name));
const canonical = JSON.stringify(tools.map(t => [t.name, t.description, t.inputSchema]));
const digest = new Bun.CryptoHasher("sha256").update(canonical).digest("hex");
console.log(`${tools.length} tools, ${canonical.length} characters`);
console.log(`sha256:${digest}`);
Run with bun catalog-hash.js <endpoint> and the server's bearer token in MCP_TOKEN. It performs the initialize handshake the AIVAX gateway also uses, so it will not reach a server that accepts only the stateless 2026-07-28 flow. Against the AIVAX documentation MCP it printed 2 tools, 800 characters and the same digest on two consecutive runs. A changed digest tells you the catalog moved, and the gateway will list the new catalog once its cache expires. When the digest changes, I disable the source until someone has read the diff.
What the spec asks of each side
The tools page of the 2026-07-28 spec splits the work by side. Servers must validate inputs, enforce access controls, rate-limit invocations and sanitize outputs; clients only should, which is why products differ on confirmation and tool selection. OpenAI's Responses API MCP tool asks for approval of each call by default and accepts allowed_tools, while Anthropic's connector can allowlist or denylist individual tools. On the AIVAX gateway, a worker on tool.called can enforce an allowlist and require an approval before a call leaves the gateway, and the server keeps its own checks, as described below.
The authorization spec makes it optional, and where an HTTP server implements it, clients must send resource indicators and servers must reject tokens issued for anyone else. Token passthrough is forbidden outright. That matters to you as a consumer: a server that forwards your token downstream turns one leak into access to several services. OAuth identifies the caller; whether a description is honest, or whether this user may refund this payment, is outside what it decides.
The page's SSRF section applies if your integration follows URLs found in tool results: an approved server can still return an unsafe one, so restrict where those fetches may go.
Give the source a credential that only does one job
The gateway sends a source's headers on every connection to the server, for discovery and for each call. It does not run OAuth consent or refresh a token for you, so a bearer token in headers is a credential you rotate yourself.
On a test gateway, reading the configuration back returned the header value exactly as I had stored it, which follows from the gateway replaying it on every connection, so I treat the stored token as readable by whoever can read that gateway. Those readers are a private key, an application key whose owner approved ResourcesRead through OAuth, and the dashboard. A public key cannot read account resources and never uses a gateway's MCP sources, so these credentials do not ride on browser traffic, and the model sees tool names, descriptions and schemas without the headers; see authentication for the key types.
Since the November 2 permission change a private key can no longer list, create or delete API keys (changelog), so a leaked private key cannot mint new credentials, though it can still read and edit gateways. I create the token for this one server, scoped to the workflow, short-lived where the provider allows it and revocable without touching anything else, and I grant ResourcesRead only to applications that need it.
Custom request metadata deserves the same care. AIVAX copies it into params._meta on every tools/call, so whatever you put there reaches the remote server.
The server enforces and the model proposes
Take a support gateway wired to an internal server that exposes lookup_customer_by_email, create_support_ticket and issue_refund. The model can propose any of them with any arguments that fit the schema. This diagram marks which side of the boundary runs each check; it shows the architecture to build, not controls that appear because a gateway connected to a server.
A call to issue_refund reaches the server like this. The server is yours in this example, and the values are fictional. AIVAX sends the original remote tool name and adds the _meta fields; the model supplies the arguments.
{
"jsonrpc": "2.0",
"id": 41,
"method": "tools/call",
"params": {
"name": "issue_refund",
"arguments": {
"payment_id": "pay_8f21c",
"amount_minor": 4200,
"reason": "duplicate_charge"
},
"_meta": {
"_aiv_external_user_id": "agent-7734",
"_aiv_call_source": "WebChatClient",
"_aiv_conversation_token": "cnv_01J9Q8V2",
"_aiv_nonce": "<BCRYPT_HASH_OF_ACCOUNT_HOOK_KEY>",
"_aiv_moment": "2026-11-17T10:00:00.0000000-03:00"
}
}
}
The server has to authenticate the connection, map _aiv_external_user_id through your own records, confirm that this user may refund pay_8f21c, validate the amount, and require an approval recorded in your system before it moves money. The external user ID is a lookup key into those records. _aiv_nonce is a BCrypt hash of the account's hook key, or null when none is set; verify it against the key to confirm who sent the call, and add your own replay protection, since it does not cover the arguments. _aiv_moment comes from the AIVAX server's clock, and _aiv_conversation_token correlates a conversation without identifying one operation.
Derive the idempotency key on the server from the actor and the canonical refund parameters, since the model cannot be relied on to repeat one; the idempotency guide walks through the pattern. Handles that a stateless server hands back need the same ownership check on every call, which is the argument of the guide to MCP's stateless core.
I do not exempt read-only tools. A lookup can disclose another customer's record, a query argument can carry sensitive text to a third party, and the returned text can steer the next call. I set approval requirements from the data a tool exposes, with writes as one input among several.
Gate tool calls with a worker on tool.called
An MCP source takes name, url, description, headers, cacheDuration, prefixTools, allowClientInstructions and allowRemoteSkills. To restrict tools or require an approval, use the two mechanisms below.
The source has no per-tool allowlist. To keep a tool out of the model's context altogether, cut the catalog on the server, or through an intermediary you have reviewed, so that tools the model must not call are never listed. That also trims the tokens each request spends on tool definitions, as the guide to reducing MCP tool-definition tokens measures.
To require an approval, add a gateway worker. Its tool.called event fires before any server-side tool runs, MCP tools included, and carries the tool name (with the source prefix, such as mcp_support_issue_refund), the arguments, the external user ID and the metadata. A non-OK response blocks the call, and the model is told the gateway blocked it. A worker can check an allowlist, or look up an approval your application recorded, and refuse otherwise. The companion tool.fetched event fires after the tool returns and can discard or replace the result before the model reads it, which is the place to strip content you do not want in context.
A worker leaves the tool in the model's context, so the model can still propose a blocked tool. A call refused by an allowlist on tool.called never reaches the MCP server, so that is enforcement at the gateway. I keep the server's own checks behind it for the calls the worker allows.
Settings that decide what enters the model's context
Both imports below default to true. allowClientInstructions adds the instructions a server advertises to the gateway's system instructions. allowRemoteSkills imports a server's root SKILL.md documents after checking size, SHA-256 digest and frontmatter against the server's own manifest, and wraps them as untrusted reference material. A matching digest shows the file agrees with the manifest and says nothing about the author, so I switch both off for a server I have not audited and enable each one deliberately. MCP skills vs tools explains what the extension adds.
{
"parameters": {
"mcpSources": [
{
"name": "support",
"url": "https://mcp.example.com/mcp",
"headers": {
"Authorization": "Bearer <MCP_SERVER_TOKEN>"
},
"cacheDuration": 600,
"allowClientInstructions": false,
"allowRemoteSkills": false
}
]
}
}
This is the parameters fragment of a gateway create or edit request, with a placeholder endpoint and token. It switches the two imports off and leaves everything else as it was. An edit shallow-merges parameters, so a top-level key such as mcpSources is replaced as a whole, which the edit endpoint's description in the API reference states. I sent a PATCH with one new source to a gateway that had another, and the gateway ended up with only the new one. To add a source I read the gateway first, append to the array and send the whole list back.
To confirm the wiring I created a gateway on @qwen/qwen3.7-flash with the AIVAX documentation MCP as a source named docs, both imports off, and asked it to look up how an MCP source is configured. The model chose mcp_docs_aivax_search_documentation (the pattern is mcp_<source>_<tool>) and the answer came back in about 12 seconds. Results from a source can include text, structured content, images and audio, and all of it goes into the conversation, so review results as input to the model. The MCP configuration reference lists every field.
The gateway opens a new client to list tools and another for every tools/call, so a server cannot count on a transport session surviving between two calls.
Run the failure cases before production
With test credentials and sandbox records, I ask for another user's payment ID and expect the server to refuse even though the JSON matches the schema. I request a refund with no recorded approval and look for an external write, since the assistant's answer says nothing about that. I replay an approved operation and expect a single side effect, with a changed amount under the same key rejected. I return a harmless test instruction telling the model to ignore policy and check that a following unauthorized call still fails outside the model. Last, I revoke the token while the discovery cache is warm; calls must fail at the server even though the gateway still lists the old catalog.
Run on the live AIVAX API on November 17, 2026 (a gateway with one MCP source, a PATCH of mcpSources, the catalog script run twice); the rest checked against the docs and implementation that day.