Skip to main content
Back to all articles
AI Engineering 17 min readUpdated November 23, 2026

The Last-Mile Tool Binding Gate: Preventing Wrong-Server MCP Execution

MCP tool names are only server-scoped. Build a secure host-side dispatch boundary that gives model tools unique names, pins provider identity, rejects schema drift, checks user authority, and traces every routed call.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#mcp#tool-routing#agent-security#tool-authorization#typescript#python#tool-catalog#multi-tenant#observability
On this page

When an AI agent has one MCP server, a tool name can feel like an identity. When it has several independently operated servers, the same string can refer to multiple capabilities. A model may generate a plausible tool call and still hit the wrong system because the host resolved that call against an ambiguous or stale catalog.

I would treat that as a binding problem at the execution boundary, not merely as a naming problem in the model prompt.

This article proposes a host-owned tool binding gateway for a hypothetical operations assistant that queries an incident-management system and a separate infrastructure inventory. Both connectors could reasonably expose a tool named find_record. The application must not guess which backend should receive a query after the model has emitted the call.

The architecture and examples below are original design sketches, not claims of a deployed system, a security audit, or measured production performance. The work builds on my earlier articles about MCP tool-definition fingerprints, retrieval-based tool selection, and action authorization for AI agents. Those concern approval, selection, and permission checks. Here the question is specific: what evidence lets the host execute exactly the tool the model was offered, on exactly the intended connector?

Names are presentation; bindings are authority

The MCP tools specification, revision 2026-07-28, states that tool names should be unique *within a server*. When clients aggregate several servers, collisions are possible. It recommends disambiguation such as a server prefix and warns that the server-reported server name is not guaranteed to be unique.

That distinction becomes important when a host builds one model-facing list from many independent tool catalogs.

Imagine that an operations assistant has two approved connectors:

Trusted connector identityNative toolIntended data
incident-systemfind_recordIncident timelines and ownership
asset-inventoryfind_recordManaged service and device records

The provider-facing tool list cannot safely expose both as one indistinguishable name. A host could reject the catalog or assign separate names. But even after assigning separate names, it must remember where they came from.

A string such as incident_find_record is a useful display alias. It is not itself proof that a server is authorized, that its current tool definition matches the reviewed version, or that the current user may access the requested record.

I would keep three concepts separate:

  1. The native name advertised by the MCP server.
  2. The model-facing alias that is unique in the assembled tool list.
  3. The trusted binding from that alias to a host-managed connector identity and an approved tool definition.

Only the third belongs in the dispatch authority path.

Give each tool a host-owned identity

A safe internal key is a tuple, not a concatenation of untrusted display text:

  • the approved connector ID, created from the application's controlled integration registry;
  • the native tool name, exactly as advertised by that connector;
  • the approved definition revision, whose canonical schema and description were reviewed;
  • the execution scope, including tenant, user authority, and intended data domain;
  • the catalog generation, identifying the exact list presented in this model step.

The connector ID should come from approved configuration and authenticated transport routing, not from a server-provided self-description. The MCP TypeScript SDK migration documentation explicitly describes serverInfo as self-reported, suitable for logging and display rather than security decisions.

This also means that changing the order in which connectors are discovered must not silently change the meaning of an alias. I would allocate names in a deterministic registry, persist the mapping, and reject duplicate or ambiguous aliases before constructing the prompt.

Do not rely on simply replacing punctuation in names to make them safe. Two different native names can normalize into the same string. Length limits can force truncation; two long identifiers might then become identical. If the model provider imposes a naming constraint, the registry should allocate and validate unique aliases under that constraint, with a stable collision-resistant suffix where necessary and a final uniqueness check. A hash alone is an identifier aid, not an authorization mechanism.

Architecture: the tool catalog is a signed-off execution snapshot

I prefer a tool-list snapshot that is built from *eligible* connectors, not directly from arbitrary server advertisements.

~~~text Authenticated user request | Workflow / data-domain policy | v Trusted connector registry | Approved tools + schema revisions | v Model-facing tool snapshot alias -> binding record immutable generation ID | LLM call | Model selects alias | v +------------------------+ | Binding dispatch gate | | 1. exact alias match | | 2. snapshot still live | | 3. connector eligible | | 4. definition unchanged| | 5. user scope allowed | | 6. arguments valid | +-----------+------------+ | Native MCP tools/call on the previously approved connection | Response provenance envelope | Model-visible result

Model text cannot choose connector credentials, destination URL, tenant identity, or approval scope. ~~~

This design has two useful properties. First, the model never supplies a raw MCP destination or a trusted server ID. It supplies only an alias that the host presented in this step. Second, the host can independently verify that the current connector and tool definition still match the policy that authorized that alias.

The system should fail closed when it cannot do either check. Asking the model to resolve the ambiguity after receiving an error can be appropriate for a *fresh* planning step, but should not be an excuse to route the original call to an arbitrary alternative backend.

TypeScript: compile a collision-free snapshot

The following pure function models the host-side catalog build. A production implementation needs trusted registry storage and an authenticated tool-discovery adapter around it; this function does not discover or approve servers.

~~~typescript type ApprovedTool = Readonly<{ connectorId: string; // Created by trusted configuration. nativeName: string; // Exact MCP name from verified discovery. modelAlias: string; // Allocated and approved by the host. definitionHash: string; // Canonical reviewed tool definition. capabilityId: string; // Stable application-level permission. dataDomain: string; // e.g. incident or infrastructure. }>;

type Binding = ApprovedTool & Readonly<{ snapshotId: string; }>;

type Snapshot = Readonly<{ snapshotId: string; byAlias: ReadonlyMap<string, Binding>; }>;

function validAlias(name: string): boolean { return name.length >= 1 && name.length <= 128 && /^[A-Za-z0-9_.-]+$/.test(name); }

export function buildToolSnapshot( snapshotId: string, approved: readonly ApprovedTool[], ): Snapshot { if (!snapshotId) throw new Error("Missing snapshot identity");

const byAlias = new Map<string, Binding>(); const nativePairs = new Set<string>();

for (const tool of approved) { if (!tool.connectorId || !tool.nativeName || !tool.definitionHash || !tool.capabilityId || !tool.dataDomain || !validAlias(tool.modelAlias)) { throw new Error("Invalid approved tool record"); }

// Structured tuple encoding avoids concatenation collisions. const pair = JSON.stringify([tool.connectorId, tool.nativeName]); if (nativePairs.has(pair)) { throw new Error("Duplicate connector/tool binding"); } nativePairs.add(pair);

if (byAlias.has(tool.modelAlias)) { throw new Error("Model alias collision"); }

byAlias.set(tool.modelAlias, { ...tool, snapshotId, }); }

if (byAlias.size === 0) { throw new Error("No eligible tools for this workflow"); }

return { snapshotId, byAlias }; } ~~~

The input is an *approved* list. If an untrusted process is allowed to populate it, this code only proves that the attacker avoided duplicate strings. The earlier admission service must bind each connector ID to an authenticated endpoint or launched workload, verify the definition hash, and enforce tenant-scoped eligibility.

The alias format and length above follow the relevant MCP recommendations as a conservative naming target. Actual model-provider limits may be narrower; the gateway must check each active model adapter's contract before exposing the names.

Keep snapshot IDs under the application's control. A stable snapshot identifier should also bind the exact list of tool descriptors, connector revisions, and authorization scope. A random-looking string created by an untrusted client is not integrity evidence.

Execute by a stored binding, never by searching for a name

The dangerous dispatcher is a routine that receives a tool name and searches connected servers until one claims it. The lookup may depend on connection order, startup timing, or which server responded first.

Instead, the dispatch service should resolve *the exact alias from the exact snapshot* and invoke the native name through a previously authenticated connector handle.

~~~typescript type CallRequest = Readonly<{ snapshotId: string; alias: string; arguments: unknown; }>;

type Actor = Readonly<{ tenantId: string; userId: string; requestedDomain: string; }>;

type LiveEvidence = Readonly<{ connectorId: string; nativeName: string; definitionHash: string; active: boolean; }>;

type DispatchDependencies = Readonly<{ // All methods below are trusted application services. loadLiveEvidence: (id: string, name: string) => Promise<LiveEvidence>; isAuthorized: ( actor: Actor, capabilityId: string, dataDomain: string, args: unknown, ) => Promise<boolean>; validateArgs: ( definitionHash: string, args: unknown, ) => Promise<boolean>; invokeBound: ( connectorId: string, nativeName: string, args: unknown, ) => Promise<unknown>; }>;

export async function dispatchBoundTool( snapshot: Snapshot, call: CallRequest, actor: Actor, deps: DispatchDependencies, ): Promise<unknown> { if (call.snapshotId !== snapshot.snapshotId) { throw new Error("STALE_TOOL_SNAPSHOT"); }

const binding = snapshot.byAlias.get(call.alias); if (!binding) throw new Error("UNKNOWN_TOOL_ALIAS");

if (binding.dataDomain !== actor.requestedDomain) { throw new Error("WRONG_DATA_DOMAIN"); }

const live = await deps.loadLiveEvidence( binding.connectorId, binding.nativeName, );

if (!live.active || live.connectorId !== binding.connectorId || live.nativeName !== binding.nativeName || live.definitionHash !== binding.definitionHash) { throw new Error("TOOL_BINDING_DRIFT"); }

if (!(await deps.isAuthorized( actor, binding.capabilityId, binding.dataDomain, call.arguments, ))) { throw new Error("TOOL_CALL_FORBIDDEN"); }

if (!(await deps.validateArgs( binding.definitionHash, call.arguments, ))) { throw new Error("INVALID_TOOL_ARGUMENTS"); }

return deps.invokeBound( binding.connectorId, binding.nativeName, call.arguments, ); } ~~~

The example assumes that the authenticated request has already populated Actor, and that the trusted service uses the authorized connector's credentials—not credentials supplied by the model or its arguments. In a real system, isAuthorized must check resource-level permission as well as the broad capability, especially for write operations.

There is also a race between verifying the current definition and making the call. A production connection broker must bind the operation to the same verified deployment generation, or re-check immediately before invocation. Otherwise an endpoint can change after the definition check while the client still thinks it is invoking the approved version.

The connector itself must enforce its own authorization. The host's checks are defense in depth, not a delegation of security to a model.

A unique alias is necessary, not sufficient

If the model chooses the wrong *unique* alias, perfect routing will faithfully execute the wrong tool. That is a selection failure rather than a resolver collision. Production systems need controls for both.

For low-risk information lookup, the application can expose the correct domain and make tool descriptions distinguishable. For consequential actions, the host should obtain the intended data domain from authenticated workflow state, not from the model's latest sentence.

For example, a maintenance flow might begin with a verified incident ID and an explicit goal to find the responsible team. The application can scope the model to incident tools only, rather than exposing every available find_record capability. Even if an infrastructure tool exists, it is not eligible in that stage.

This fits the approach in my tool retrieval and ranking article: candidate selection should happen *after* hard filtering by user rights and task scope. Ranking and aliases improve the model's choices; they do not replace the hard filters.

One practical improvement is to make every model-facing tool description mention its domain boundary and expected identifiers. A name-only disambiguation scheme may technically prevent collisions while still making the model's choice unnecessarily difficult.

Provenance belongs on the result, not only the call

A model may produce a convincing answer based on a tool result from the wrong system. If all the transcript stores is the tool's model-facing name and returned text, incident review becomes guesswork.

I would attach an application-owned result envelope with:

  • correlation ID and workflow/step identity;
  • model-facing alias and original MCP tool name;
  • trusted connector ID and verified deployment generation;
  • definition fingerprint and catalog snapshot ID;
  • authenticated tenant and scoped data-domain reference;
  • normalized outcome class, elapsed time, and explicit error state.

The envelope should be stored in restricted trace and audit systems. The model-visible result should be the validated business output and, when relevant, a user-readable source label. The model must not be able to overwrite the audit fields with content returned from a tool.

Tool results can themselves contain malicious instructions. Treat them as untrusted data even when the connector has been approved. The MCP tools specification allows structured and unstructured tool content; application-specific validation remains necessary.

A tool response saying "you are now the administrator" is text, not an authentication event. Keeping execution and provenance boundaries explicit also helps the tool-output security controls that inspect what ultimately leaves the agent.

Python: test the aliases as an invariant

Most teams will test that a tool call works. I would also test that registration order, collision attempts, and tenant scope cannot change the destination.

Here is a compact Python model of an admission check. It is deliberately not an MCP SDK implementation; it tests the critical uniqueness property in the approved catalog.

~~~python from dataclasses import dataclass from typing import Sequence

@dataclass(frozen=True) class Tool: alias: str connector_id: str native_name: str definition_hash: str

def compile_catalog(tools: Sequence[Tool]) -> dict[str, Tool]: by_alias: dict[str, Tool] = {} native_pairs: set[tuple[str, str]] = set()

for tool in tools: if not all(( tool.alias, tool.connector_id, tool.native_name, tool.definition_hash )): raise ValueError("incomplete binding")

pair = (tool.connector_id, tool.native_name)

if tool.alias in by_alias: raise ValueError("duplicate model alias") if pair in native_pairs: raise ValueError("duplicate native binding")

by_alias[tool.alias] = tool native_pairs.add(pair)

return by_alias

incident = Tool( "mcp_incident_find_record", "incident-system", "find_record", "hash-a" ) inventory = Tool( "mcp_inventory_find_record", "asset-inventory", "find_record", "hash-b" )

first = compile_catalog([incident, inventory]) reverse = compile_catalog([inventory, incident])

assert first == reverse assert first[incident.alias].connector_id == "incident-system"

try: compile_catalog([incident, Tool( incident.alias, "asset-inventory", "find_record", "hash-b" )]) except ValueError: pass else: raise AssertionError("collision should have been rejected") ~~~

In a larger test suite, I would generate randomized server orders, similar-looking names, case changes, Unicode confusables, names that collide after normalization, long names that might be truncated, and duplicate native pairs. The compiler should either preserve the exact intended mapping or reject the catalog. It should never silently choose "first wins."

This test is not an authorization test. A separate suite must verify that the runtime denies a wrong tenant, a changed definition, a stale snapshot, and a connector that lost approval after the model saw it.

Handle tool-list changes as a new generation

The 2026-07-28 MCP specification allows the available tool list to change, and defines ways to notify clients. It also recommends deterministic ordering when the underlying list has not changed.

For the host, that means a tools/list refresh is not merely a UI update. It may change which aliases are present and which tool definitions are eligible.

I would follow this lifecycle:

  1. Fetch the complete authorized tool list for an authenticated connector and validate it.
  2. Compare native names, schemas, and relevant descriptions against approved definitions.
  3. Construct a new, unique model-facing snapshot; reject any ambiguous catalog.
  4. Keep the snapshot immutable for the model invocation that used it.
  5. If an important binding changes, invalidate dependent planned calls and re-plan with the new generation.
  6. Execute only when the recorded snapshot and live approved binding still agree.

This also makes caching safer. A prompt cache should be based on the *actual stable tool definitions shown to the model*, not on a name string whose meaning changes silently. See my earlier article on progressive MCP discovery and cached definitions.

The host must preserve the original native name when making the MCP tools/call request. Prefixing for the model is an application adapter strategy, not an instruction to rename the server's own exported function.

Framework support is helpful, but verify the boundary

Some agent runtimes already provide useful mechanics. The OpenAI Agents SDK for JavaScript documents a local-MCP option named includeServerInToolNames that exposes deterministic, server-prefixed names to the model. Its documentation also says duplicate names can produce an error when the prefix option is not enabled.

That is a useful implementation safeguard. The same documentation distinguishes local MCP exposure from hosted MCP tool behavior, and exposes tool filtering and input/output guardrail hooks.

I would still verify the configured server labels, which tool sets are available to a given agent, how the SDK maps the alias back to the original connector, and whether the application enforces its own tenant and user permissions. A naming feature does not automatically grant the stronger guarantees described in the host binding gateway above.

The guiding separation is simple:

LayerWhat it should guarantee
MCP serverIts native tool name and protocol behavior
Host catalogA unique alias mapped to one approved connector and definition
ModelA requested operation selected from the eligible list
Dispatch gateCorrect binding, current approval, and caller authorization
MCP server authorizationResource and operation permissions on the actual backend
ObservabilityA durable record of what was shown, selected, and actually invoked

Do not make the model responsible for proving the identity of the connector it chose.

Monitor wrong-provider risk as an operational signal

A successful HTTP response is a weak success metric when the wrong service answered. The host should measure route integrity independently from model answer quality.

MetricUseful interpretation
Catalog collision rejectionsConfiguration cannot produce a unique model tool list
Unknown or stale alias callsModel used a name outside its bound snapshot
Definition drift rejectionsTool changed after review or discovery
Wrong-domain dispatch attemptsModel selected a capability outside current workflow scope
Authorization denialsUser or tenant lacks permission for selected operation
Binding mismatch during rolloutRunning connector generation differs from approved one
Correct-provider rate on eval tasksTool selection reached the intended data domain
Result provenance coverageHow often traces identify the exact responding connector

Track rates alongside counts and eligible traffic so an incident does not disappear into a large denominator. For an actual wrong-provider write or unauthorized data access, treat the event as a security incident rather than waiting for a dashboard threshold.

Use bounded connector classes and outcome categories in metrics. Full tenant IDs, endpoint URLs, query bodies, and authentication materials belong only in appropriately protected traces or audit records. This complements my article on OpenTelemetry-based agent observability.

Failure-inject the execution boundary

Before I would approve this design for production, I would run a test matrix that deliberately separates alias mistakes from model selection errors:

Injected conditionExpected behavior
Two connectors advertise one native nameUnique model aliases, or catalog rejection
Registration order is reversedSame trusted alias-to-connector mappings
Host aliases collide after sanitizationCatalog build fails rather than choosing a winner
Server advertises a new tool descriptionPrior approval no longer automatically applies
Tool list changes mid-runStale plan is rejected; new snapshot is required
Model invents a connector ID in argumentsIgnored for routing; trusted binding used
Model selects an out-of-domain but valid aliasIndependent workflow policy blocks execution
Original connector goes unavailableHonest failure or separately approved fallback, not another same-named tool
Input schema is valid but requested record is privateResource authorization denies access
A result claims to come from a different serverProtected host provenance remains authoritative

I would additionally test with two otherwise identical connectors that return different synthetic records. The acceptance criterion is not that the model's final prose sounds sensible; it is that the call reaches the approved destination and the trace records the same destination.

For state-changing tools, ambiguous retries need their own idempotency and outcome-reconciliation controls. A host that accidentally executes the wrong write should not compound the error by retrying against a second server with a matching name. See side-effect-safe agent execution.

The cost and the boundary I would keep

A host-owned binding registry adds operational responsibility: connector enrollment, stable aliases, schema approvals, snapshot versions, protected runtime handles, and audit records. It may also require adapters when a model provider imposes stricter tool-name limits than MCP recommends.

For a small, trusted, fixed set of tools, a framework's built-in collision handling plus ordinary authorization checks may be enough. For a multi-tenant agent with dynamically installed connectors, the additional control is easier to justify. One wrong server invocation can be a data leak or a business operation against the wrong system.

The most important property is not that every tool has a pretty, globally unique name. It is that the name the model saw resolves to exactly one approved tool identity at the moment of execution, and that the host can prove which one it actually called.

Once this is a tested invariant, tool naming becomes a usability concern rather than a hidden routing decision with security consequences.

Primary technical sources

KEEP READING

Related engineering notes