---
title: "MCP Security Best Practices: Auth, Tool Access, and Egress - API7.ai"
description: "Secure MCP with resource-bound authentication, least-privilege tools, separate credentials, correctly timed guardrails, and egress controls."
url: "https://api7.ai/blog/mcp-security-best-practices"
---

[Blog](https://api7.ai/blog)

[Products](https://api7.ai/category/products)[Technology](https://api7.ai/category/technology)[Ecosystem](https://api7.ai/category/ecosystem)[Case Study](https://api7.ai/category/usercase)[Team & Community](https://api7.ai/category/community)

Search

⌘ + K

[Blog](https://api7.ai/blog)

Technology

# MCP Security Best Practices: Auth, Tool Access, and Egress

[![Yilia Lin](https://github.com/Yilialinn.png)](https://github.com/Yilialinn)

[Yilia Lin](https://github.com/Yilialinn)

October 8, 2026

[Technology](https://api7.ai/category/technology)

MCP security is not one OAuth flow or one tool allowlist. A production Model Context Protocol deployment has several trust boundaries: the client authenticates to the gateway, the gateway authorizes a tool, the gateway authenticates to an upstream MCP server, and the tool may access another protected resource or network destination.

The safer design treats each boundary explicitly. It uses resource-bound tokens, deny-by-default tool access, reviewed server publication, gateway-held upstream credentials, content controls with understood timing, restricted egress, and negative-path tests.

This article follows the **MCP specification revision 2025-11-25** and uses **AISIX AI Gateway 1.5.0** as a concrete implementation. AISIX provides runtime controls, but it is not a universal sandbox, an SSRF firewall, or a replacement for human approval of destructive actions.

## Key Takeaways

- Authenticate the client for the MCP resource; a sign-in for another audience is insufficient.
- Authorize individual tools and recheck permission at `tools/call`, not only during discovery.
- Keep client and gateway-to-server credentials separate; avoid generic token passthrough.
- Run input guardrails before dispatch; an output block cannot reverse an upstream side effect.
- Constrain OAuth discovery and tool egress at the network layer.
- Test denied, expired, unavailable, anonymous, and fail-open/fail-closed paths.

## Start with the Trust Boundaries

A useful [MCP Gateway architecture](https://api7.ai/blog/mcp-gateway-architecture) puts a runtime boundary between agents and upstream tool servers. That boundary helps only when identities and credentials on each side remain distinct.

```
flowchart LR
    C[MCP client or agent]
    C -->|client credential| G[AISIX MCP Gateway]
    G -->|tool authorization| T[Permitted tool]
    G -->|gateway-held credential| S[Upstream MCP server]
    S -->|resource identity| R[Database, SaaS, or API]
    E[Egress policy] -. restricts .-> S
    E -. restricts .-> R
```

The diagram contains four decisions: who may call the gateway, which tools that principal may use, how the gateway authenticates to the server, and what the server may do downstream. Collapsing them into one bearer token creates excessive privilege and weakens auditability.

The official [MCP Security Best Practices](https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices) warns against token passthrough. A token not issued for the MCP server can bypass audience boundaries when blindly relayed to another resource.

## Authenticate for the MCP Resource

AISIX exposes aggregated `/mcp` and per-server `/mcp/{server}` entries. Its [client authentication](https://docs.api7.ai/ai-gateway/mcp-gateway/client-authentication) supports gateway keys, OAuth, and a bounded anonymous mode.

A gateway key works for an agent, job, or service profile. Give operational identities separate keys where attribution and revocation matter. The key identifies the caller to AISIX; it is not the upstream server credential.

For OAuth clients, the access token must identify the MCP resource in its audience. This follows the resource-indicator pattern in [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707). A user can authenticate successfully and still present a token intended for another resource. The gateway must validate the audience rather than treating any signed token as sufficient.

Anonymous access belongs only inside a real network boundary. In AISIX 1.5.0 it maps eligible unauthenticated requests from configured source CIDRs to a caller-key principal with tool permissions and applicable controls. An invalid credential is rejected rather than downgraded to anonymous. Callers mapped to the same principal also share its attribution and quota, so anonymous mode should not be described as per-user identity.

## Authorize Tools, Not Just Servers

A single MCP server may expose search, issue creation, repository deletion, and administration. Those tools should not inherit one permission simply because they share a server.

AISIX names aggregated tools as `<server>__<tool>` and documents exact grants, server wildcards, broader patterns, and denies in [tool access control](https://docs.api7.ai/ai-gateway/mcp-gateway/tool-access-control). In AISIX Cloud, applicable environment, team, and key allow rules intersect, while a deny at any layer wins. Only configured layers participate; if no access layer grants a tool, it is unavailable.

The open-source resources-file path has caller-key `mcp_access` but not the Cloud environment/team policy collection. Preserve that product boundary.

Authorization happens at two points. `tools/list` filters discovery to improve the client experience, while `tools/call` rechecks permission before upstream dispatch. The second check is the enforcement boundary. Prefer exact grants for high-risk tools because a server wildcard also covers tools added later.

## Review Servers Before Publication

Registry metadata is not proof that a server is safe. Review the URL, transport, timeout, upstream credential provenance, tool schemas, downstream privileges, data classification, egress destinations, owner, and revocation path.

[AISIX Cloud server review](https://docs.api7.ai/ai-gateway/mcp-gateway/server-review) separates submission from publication. Pending or rejected servers do not appear on gateways, even when a caller key names their tools. This is a Cloud control-plane capability. Open-source deployments need equivalent change control around `resources.yaml`: protected branches, secret provenance outside Git, validation, staged rollout, and emergency removal.

Re-review a server when its URL, credential mode, tool surface, environment exposure, or operator changes. Approval should not be permanent.

## Separate Caller and Upstream Credentials

The client credential proves identity to the gateway. The upstream credential proves the gateway's identity to the MCP server. These should differ by default.

AISIX [upstream authentication](https://docs.api7.ai/ai-gateway/mcp-gateway/upstream-authentication) can hold a bearer token, API key, or OAuth client credential for a registered server. The caller's gateway key is not forwarded by default. Use HTTPS for credentialed upstreams and token endpoints.

Some internal servers need the end user's identity. AISIX supports an explicit `forward_client_headers` exception, but it changes the trust model. The list is empty by default, broad patterns may relay more than intended, and a downstream server can reject a caller token minted for the gateway audience. Do not forward `authorization` as a shortcut. Document the issuer, audience, precedence, and reason, and consider token exchange where appropriate.

## Time Guardrails Correctly

MCP tools carry structured arguments and can return text, resource links, embedded resources, or structured content. Content controls may help with secrets, personal data, prompt-injection indicators, and organization-specific policy.

AISIX [MCP guardrails](https://docs.api7.ai/ai-gateway/mcp-gateway/guardrails) run on `tools/call`:

- input guardrails inspect arguments before upstream dispatch;
- output guardrails inspect results after the upstream responds but before AISIX returns them.

If an input guardrail blocks, the upstream is not contacted. If an output guardrail blocks, the result is withheld, but the operation may already have changed state. Blocking the result of `delete_repository` does not restore the repository.

Use authorization and input controls to prevent dangerous calls. Use output controls to reduce sensitive-data delivery to the agent. Add client-side confirmation, downstream authorization, transactions, or compensating actions for state changes.

Guardrails also require attachment and failure policy. An unattached guardrail inspects no traffic. Model-scoped rules do not cover MCP tool calls because no model is resolved. Choose environment, server, caller-key, or team scope as supported, and test fail-open versus fail-closed behavior when a remote guardrail is unavailable.

## Constrain Network Egress and Runtime

Authentication and tool ACLs do not prevent a permitted server or OAuth discovery flow from reaching an unsafe destination. MCP security guidance identifies SSRF risks in protected-resource metadata, authorization-server metadata, token endpoints, redirects, private ranges, loopback services, and cloud metadata addresses. Tool arguments may create a similar risk when a server accepts caller-controlled URLs.

Use defense in depth:

- require HTTPS for production OAuth and credentialed upstream URLs;
- block private, reserved, loopback, link-local, and metadata destinations unless explicitly needed;
- validate every redirect hop and account for DNS rebinding;
- restrict Kubernetes NetworkPolicy, security groups, or firewall egress;
- isolate local or third-party servers with minimal filesystem, process, and network privileges;
- scope downstream credentials to the resources and operations each tool needs.

The [OWASP SSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html) provides broader validation guidance. AISIX should not be described as a complete SSRF sandbox; network destination control and server isolation remain separate infrastructure responsibilities unless a specific versioned feature says otherwise.

## Test Negative Paths

The happy path proves little about security. Test at least:

| Test                                           | Expected result                                     |
| ---------------------------------------------- | --------------------------------------------------- |
| Expired, malformed, or wrong-audience token    | Rejected at client authentication                   |
| No effective tool grant                        | Tool is neither listed nor callable                 |
| Allow at one layer, deny at another            | Deny wins                                           |
| Guessed unauthorized tool name                 | Rejected before upstream routing                    |
| Invalid credential with anonymous mode enabled | Rejected, not downgraded                            |
| Pending or rejected server                     | Absent from the gateway surface                     |
| Revoked upstream credential                    | That server fails without exposing the credential   |
| Input guardrail block                          | Upstream tool is not invoked                        |
| Output block on a mutating tool                | Result is withheld; side effect may remain          |
| Guardrail dependency unavailable               | Configured fail-open or fail-closed behavior occurs |
| Metadata redirects to a private address        | Network policy blocks the destination               |

Collect enough telemetry to identify the principal, tool, server, authorization outcome, request ID, latency, and upstream result without assuming full arguments or results must be stored. Prepare independent revocation paths for caller keys, OIDC trust, server approval, upstream credentials, tool grants, and environment exposure.

This article pins [AISIX 1.5.0](https://github.com/api7/aisix/releases/tag/v1.5.0). Older gateways may differ, especially around authentication and policy scopes.

## Build MCP Security as a System

MCP security depends on several controls agreeing: resource-bound authentication, least-privilege tool authorization, reviewed servers, separate upstream credentials, correctly timed guardrails, restricted egress, downstream permissions, observability, and rapid revocation.

[AISIX MCP Gateway](https://docs.api7.ai/ai-gateway/mcp-gateway/overview) provides a central runtime boundary for many of them. Start with one read-only server, one scoped caller, and no wildcard access. Expand only when identity, tool, credential, network, and audit boundaries remain clear.

Tags:

[MCP](https://api7.ai/tags/mcp)

[AI Gateway](https://api7.ai/tags/ai-gateway)

[AISIX](https://api7.ai/tags/aisix)

[Security](https://api7.ai/tags/security)

[AI Agents](https://api7.ai/tags/ai-agents)

Share article link

Share

Related Posts

[![Rotate LLM Provider Keys in AISIX Without Breaking Model Aliases](https://static.api7.ai/uploads/2026/08/25/61viB4d5_ai-gateway-provider-key-management.webp)](https://api7.ai/blog/ai-gateway-provider-key-management)

## [Rotate LLM Provider Keys in AISIX Without Breaking Model Aliases](https://api7.ai/blog/ai-gateway-provider-key-management)

[![MCP Access Control: Least Privilege for AI Agents](https://static.api7.ai/uploads/2026/08/14/yhTEMszT_mcp-access-control-least-privilege-cover.svg)](https://api7.ai/blog/mcp-access-control-least-privilege-ai-agents)

## [MCP Access Control: Least Privilege for AI Agents](https://api7.ai/blog/mcp-access-control-least-privilege-ai-agents)

Table of Contents

- [Key Takeaways](#key-takeaways)
- [Start with the Trust Boundaries](#start-with-the-trust-boundaries)
- [Authenticate for the MCP Resource](#authenticate-for-the-mcp-resource)
- [Authorize Tools, Not Just Servers](#authorize-tools-not-just-servers)
- [Review Servers Before Publication](#review-servers-before-publication)
- [Separate Caller and Upstream Credentials](#separate-caller-and-upstream-credentials)
- [Time Guardrails Correctly](#time-guardrails-correctly)
- [Constrain Network Egress and Runtime](#constrain-network-egress-and-runtime)
- [Test Negative Paths](#test-negative-paths)
- [Build MCP Security as a System](#build-mcp-security-as-a-system)

## Related Posts

[![What Is an MCP Registry? Discovery and Gateway Control](https://static.api7.ai/uploads/2026/09/15/PL8CU1Q1_what-is-mcp-registry.webp)](https://api7.ai/blog/what-is-mcp-registry)

Technology

September 15, 2026

#### [What Is an MCP Registry? Discovery and Gateway Control](https://api7.ai/blog/what-is-mcp-registry)

Learn how an MCP Registry catalogs servers, differs from a marketplace and gateway, and supports governed MCP discovery and tool execution.

[MCP](https://api7.ai/tags/mcp)

[AI Gateway](https://api7.ai/tags/ai-gateway)

[AI Agents](https://api7.ai/tags/ai-agents)

[![PII Redaction in an AI Gateway: Protect Sensitive Data Before It Reaches an LLM](https://static.api7.ai/uploads/2026/09/01/2G8m9g09_ai-gateway-pii-redaction.webp)](https://api7.ai/blog/ai-gateway-pii-redaction)

Technology

September 1, 2026

#### [PII Redaction in an AI Gateway: Protect Sensitive Data Before It Reaches an LLM](https://api7.ai/blog/ai-gateway-pii-redaction)

Learn how AI Gateway PII redaction detects, masks, or blocks sensitive data in LLM requests and responses before it crosses a trust boundary.

[AI Gateway](https://api7.ai/tags/ai-gateway)

[AISIX](https://api7.ai/tags/aisix)

[Security](https://api7.ai/tags/security)

[![Rolling Out AI Gateway Guardrails: Monitor, Block, and Handle Streaming Safely](https://static.api7.ai/uploads/2026/08/25/gJlmAdvv_ai-gateway-guardrails.webp)](https://api7.ai/blog/ai-gateway-guardrails)

Technology

August 25, 2026

#### [Rolling Out AI Gateway Guardrails: Monitor, Block, and Handle Streaming Safely](https://api7.ai/blog/ai-gateway-guardrails)

Use AISIX AI Gateway guardrails safely with monitor and block modes, input and output hooks, scoped policies, streaming controls, and failure handling.

[AI Gateway](https://api7.ai/tags/ai-gateway)

[AISIX](https://api7.ai/tags/aisix)

[Security](https://api7.ai/tags/security)
