MCP: Model Context ProtocolMCP Security and Trust BoundariesLangChain MCP Tool Access and Credentials

How do you secure MCP tool access and credentials?

Question 4 of 43 · Updated

On this page

Direct answer#

Secure MCP tool access by treating the LangChain agent as an untrusted proposer of actions, not as an authenticated or authorized principal. The host authenticates the user, connects only to approved MCP servers, obtains narrowly scoped credentials outside the model context, and exposes only tools relevant to the user's permissions. For every invocation, the server validates the credential, checks the operation and resource against the user's identity and tenant, validates the arguments, and requires additional confirmation where necessary. The host must never allow a model to choose credentials, arbitrary server URLs, or authorization claims.

For remote MCP services, use TLS and a supported authorization mechanism such as the OAuth-based framework defined in the applicable MCP specification. For local stdio servers, constrain the executable, process identity, environment and filesystem/network permissions. Both transports need application-level authorization; neither a successful connection nor a discovered tool is evidence that a user may execute it.

Research and testing scope: This article uses the historical MCP 2025-06-18 specification as a baseline, not a claim about the current revision. Official links and exact SDK API versions were not live-verified under the authorized offline research exception. The dependency-free Python policy example was executed on Python 3.13.5 and syntax-compiled successfully. MCP, LangChain and LangChain MCP adapter packages were unavailable locally, so real OAuth exchanges, SDK behavior and end-to-end integrations were not executed. The Mermaid diagrams are authored in standard flowchart and sequence diagram syntax; no Mermaid parser or live site renderer was available to verify rendering.

1. Authentication is not authorization#

Authentication establishes who is making a request. Authorization determines whether that identity may perform a particular operation on a particular resource under the current conditions. For example, Alice is an authenticated support employee belonging to tenant A. She may read orders belonging to tenant A, but that does not imply she can read tenant B's orders or cancel orders.

A valid token may still have an insufficient scope, a different audience, or a subject that is not entitled to the requested record. A valid JSON Schema tool argument may still identify another tenant's record. An agent can propose a syntactically valid operation that is unauthorized.

ControlQuestion answeredExample
AuthenticationWho is requesting access?Alice's verified identity
Audience validationWas the access token intended for this server?Orders MCP endpoint
Scope validationWhat class of operation is permitted?orders:read
Resource authorizationWhich specific record may this identity access?Order A12 in tenant A
ApprovalHas the authorized user explicitly confirmed this sensitive action?Cancel order A12
Execution validationAre arguments and business state valid?Order is still cancellable
AuditWhat actually happened?Request, decision, outcome

Authentication and authorization must be enforced even if the model never sees a forbidden tool. Hiding a tool in the host is useful for reducing exposure, but the server is the final policy enforcement boundary for its own operations.

2. Understand the trust boundaries#

Loading diagram…

The credential manager and the model context are separate boundaries. A credential manager may issue or retrieve a token for the client, but does not put that token into the LLM prompt. The agent's proposal passes through policy before the MCP client transmits it. The server validates the request again before accessing business data. Returned content is checked before being passed to the model.

The main trust boundaries are:

  • User to host: authentication, identity, tenant membership and consent.
  • Model to host: treat model-selected tool names and arguments as untrusted inputs.
  • Host to MCP client: trusted routing, scoped credentials and server allowlists.
  • Client to MCP server: authenticate the intended resource server and validate the transport and protocol.
  • MCP server to downstream services: independent identity, least-privilege permissions and resource access controls.
  • Tool result to model: untrusted content, output constraints, privacy and prompt injection defenses.

An MCP server can be trusted to perform one narrow service without being trusted to instruct the host to disclose credentials or invoke another service. Trust is capability-specific rather than a blanket property.

3. Secure remote MCP authorization#

The historical 2025-06-18 MCP authorization framework for HTTP deployments is based on OAuth standards. When using it, treat the MCP server as an OAuth protected resource, the MCP client as the OAuth client, and the authorization server as the component responsible for issuing access tokens. This architecture does not require the MCP server itself to implement a complete identity provider.

For interactive user-delegated access, a typical authorization-code flow with PKCE proceeds as follows. This is a conceptual sequence rather than a complete wire-level protocol transcript; metadata discovery, registration, resource indicators and required headers depend on the supported specification and deployment.

Loading diagram…

In practice:

  1. Configure the client with approved MCP server identities and endpoints. Do not let a model supply a new endpoint.
  2. Discover authorization metadata through the revision-appropriate mechanisms. Validate the returned issuer and metadata URLs against trust and network policy.
  3. Use an appropriate supported OAuth client flow. Interactive applications should use the authorization-code flow with PKCE where required. Protect redirects and authorization state. Never send credentials through the model.
  4. Request an access token for the intended MCP resource, with only the required scopes.
  5. Send that token over TLS using the supported authorization mechanism, normally the Authorization bearer header for OAuth-protected HTTP resources.
  6. Validate the token on the server before handling sensitive MCP operations. Check issuer, intended audience or resource binding, expiry, and required permissions. For JWT access tokens, verify signature using trusted issuer keys and a permitted algorithm; for opaque tokens, use an appropriate trusted validation or introspection mechanism.
  7. Bind the verified subject to the application identity and tenant. Perform per-resource authorization in addition to token-level scope checks.
  8. Renew or reauthorize using documented credential flows as needed, and fail closed if authorization cannot be established.

OAuth is primarily an authorization framework. An application requiring authentication may use a separate trusted identity mechanism such as OpenID Connect. An ID token intended for a client is not automatically a valid MCP API access token.

Access tokens, refresh tokens and scopes#

An access token authorizes limited access to a resource. A refresh token, where issued, belongs in the trusted client credential store and should be sent only to the authorization server's token endpoint as appropriate. It is not a tool input and should not be forwarded to the MCP resource server.

Use short-lived access tokens, secure refresh token storage, and revocation or rotation mechanisms supported by the issuer. Avoid logging authorization headers, authorization codes, refresh tokens or complete environment dumps. Scope names are deployment-defined; orders:read and orders:cancel in this lesson are examples, not standardized MCP permissions.

A resource server should reject access tokens intended for another service. Do not pass a received token through to an unrelated downstream API. Use a separate downstream credential or an explicitly supported, properly scoped token exchange. Identity delegation must preserve accountability without widening access.

4. Local stdio credential isolation#

For stdio, the client typically launches a local server process using an approved executable and explicit argument array. The subprocess can access resources allowed by its operating-system identity and sandbox, so local does not mean safe.

Use a dedicated process identity or sandbox where feasible, read-only filesystem mounts for read-only tools, explicit workspace access, and restricted network egress. Keep the executable and scripts in protected locations and pin reviewed dependency versions.

Build a minimal subprocess environment; inspect the installed SDK's inheritance and default environment behavior rather than assuming an env override removes inherited secrets. Avoid forwarding a model-provider key to an inventory tool server. Do not put secrets in command-line arguments, which may be exposed in process listings. Prefer platform secret mechanisms or protected environment injection when supported. Keep arbitrary logs off stdout so the stdio protocol remains valid.

MCP roots, where supported, communicate workspace context. They are not an operating-system filesystem sandbox. Enforce filesystem boundaries independently, including symlink handling and path resolution. Never grant a subprocess access to an entire home directory just because the user has selected a single workspace.

5. Integrate the security boundary with LangChain#

The LangChain MCP adapter converts discovered server tools into framework-compatible tools. This is useful for interoperability, but the conversion does not establish that every advertised tool is safe. The host should construct its server configuration from trusted application settings, manage credentials separately from prompts, and filter discovered tools before constructing the agent.

A practical integration should perform these steps:

  • Authenticate the application user and load their permitted actions from a trusted policy source.
  • Resolve the intended MCP server from a protected configuration registry. Bind server identity and tool identity together; avoid collisions between two servers exposing the same tool name.
  • Create the MCP client using the selected transport and a credential intended only for that server. For remote OAuth integration, use the installed SDK's supported authentication flow or a documented authenticated gateway. If an adapter release supports injected HTTP headers, provide them from a trusted credential provider, not from model output. A fixed bearer header is not an implementation of OAuth acquisition or refresh.
  • Discover tools, review schemas and expose a minimal policy-approved subset. Use known server identity, tool name, schema and required permission to construct the mapping.
  • Bind those tools to the LangChain agent. Use supported middleware or wrapped tool implementations for invocation-time policy checks, rather than trusting the model's decisions. The exact wrapper and middleware APIs vary by LangChain release.
  • Derive the authenticated identity from trusted runtime context. Never let an agent argument such as tenant_id, user_id, role, scope or approved replace that context.
  • Invoke the server; independently enforce authorization again at the server and downstream data boundary.
  • Return only the approved result content, with controlled size and sensitive-field redaction. Preserve the tool error state so the model cannot confuse denial with success.

For a real multi-user application, construct user-specific credentials and authorization decisions within the correct request/session context. Never share a global mutable token or a discovered tool catalog containing sensitive user-specific metadata among tenants.

No version-specific executable LangChain integration is claimed here: the framework and adapter packages were unavailable. The example below is a tested policy implementation independent of those APIs, intended for use inside a trusted server handler or host wrapper.

6. Design permissions around business operations#

Expose narrowly scoped business operations rather than unrestricted shell commands, raw file access or arbitrary SQL. An orders service might implement:

ToolRequired permissionResource conditionAdditional confirmation
orders.statusorders:readOrder belongs to authorized tenantUsually no
orders.cancelorders:cancelOrder belongs to tenant and is cancellableExplicit user approval
orders.refundorders:refundTenant, amount and payment policy checksApproval according to risk

These names illustrate internal host routing aliases and permissions, not prescribed MCP wire-level names. The service must use provider-compatible model-facing aliases if a model API imposes naming restrictions.

Read operations can still disclose sensitive data. The read-only annotation is only descriptive; it cannot substitute for authorization. Apply least privilege, resource ownership, redaction and rate limits even to supposedly read-only tools. For actions with side effects, require a policy-appropriate confirmation bound to the authenticated principal, exact operation, normalized arguments, expiry and a unique operation identifier.

Loading diagram…

A model saying the user has approved an action is not proof of approval. Obtain confirmation through a trusted host interaction or approval service. For a cancellation or refund, atomically consume the applicable approval and record an idempotency key at the execution boundary. This avoids treating a replayed approval or network retry as authorization to repeat a financial or business action.

7. Tested Python example: per-tool and per-resource authorization#

This dependency-free example demonstrates the policy decision boundary for a hypothetical orders MCP server. It assumes the Principal comes from a trusted authentication layer that has already validated the token, that order_tenant comes from an authoritative repository, and that Approval comes from a trusted confirmation service. It does not parse or verify JWT signatures, implement OAuth, communicate with an MCP server, or execute cancellations.

PYTHON
from dataclasses import dataclass, replace @dataclass(frozen=True) class Principal: subject: str tenant: str audience: str scopes: frozenset[str] expires_at: int @dataclass(frozen=True) class Approval: subject: str tenant: str action: str order_id: str expires_at: int REQUIRED = {'orders.status': 'orders:read', 'orders.cancel': 'orders:cancel'} AUDIENCE = 'https://orders.example.com/mcp' def authorize(p, action, args, order_tenant, now, approval=None): if p is None or not p.subject or not p.tenant: raise PermissionError('Unauthenticated') if p.audience != AUDIENCE or p.expires_at <= now: raise PermissionError('Invalid token context') if action not in REQUIRED or REQUIRED[action] not in p.scopes: raise PermissionError('Operation not permitted') if (not isinstance(args, dict) or set(args) != {'order_id'} or type(args['order_id']) is not str or not 1 <= len(args['order_id']) <= 64): raise PermissionError('Invalid arguments') if order_tenant != p.tenant: raise PermissionError('Resource not permitted') if action == 'orders.cancel': if (approval is None or approval.subject != p.subject or approval.tenant != p.tenant or approval.action != action or approval.order_id != args['order_id'] or approval.expires_at <= now): raise PermissionError('Approval required') return True if __name__ == '__main__': now = 100 user = Principal('alice', 'tenant-a', AUDIENCE, frozenset({'orders:read', 'orders:cancel'}), 200) args = {'order_id': 'A12'} ok = Approval('alice', 'tenant-a', 'orders.cancel', 'A12', 150) assert authorize(user, 'orders.status', args, 'tenant-a', now) assert authorize(user, 'orders.cancel', args, 'tenant-a', now, ok) bad = [ (None, 'orders.status', args, 'tenant-a', None), (replace(user, audience='https://other.example.com'), 'orders.status', args, 'tenant-a', None), (replace(user, expires_at=now), 'orders.status', args, 'tenant-a', None), (replace(user, scopes=frozenset()), 'orders.status', args, 'tenant-a', None), (user, 'orders.delete', args, 'tenant-a', None), (user, 'orders.status', dict(args, tenant='tenant-b'), 'tenant-a', None), (user, 'orders.status', args, 'tenant-b', None), (user, 'orders.cancel', args, 'tenant-a', None), (user, 'orders.cancel', args, 'tenant-a', replace(ok, order_id='B34')), (user, 'orders.cancel', args, 'tenant-a', replace(ok, expires_at=now)), ] for p, action, payload, tenant, approval in bad: try: authorize(p, action, payload, tenant, now, approval) except PermissionError: pass else: raise AssertionError('Unauthorized request accepted') print('12 policy cases passed (2 allowed, 10 denied)')

Save as mcp_q4_policy.py and run python mcp_q4_policy.py with Python 3.10 or later. Actual local execution on Python 3.13.5 produced:

12 policy cases passed (2 allowed, 10 denied)

The positive cases prove the example allows an authorized read and an approved cancellation. The ten negative cases verify that unauthenticated access, the wrong audience, expired credentials, missing scopes, unknown tools, injected tenant fields, cross-tenant access, missing approval, wrong-order approval and expired approval are rejected.

The test uses fixed timestamps for reproducibility. In production use a trusted clock and appropriate token validation semantics. Do not instantiate Principal or Approval from raw model inputs. The repository lookup and subsequent mutation must enforce tenant ownership in the same execution boundary, avoiding time-of-check/time-of-use races. The example deliberately does not demonstrate approval consumption, replay prevention, signature verification, server-side identity mapping, rate limiting or actual business writes. Those are mandatory additional design considerations, not properties proven by the twelve tests.

8. Prevent credential leakage and prompt injection#

Treat MCP tool metadata, prompts, resources and tool results as untrusted data. A server can return text claiming that a token is required in the next prompt; the host should not comply with such an instruction. A model may be influenced by adversarial text, so policy must live outside the model.

Keep credentials out of model prompts, tool descriptions, tool arguments, returned resource content, traces and exception messages. Keep access and refresh tokens in a protected store with restricted read access; use separate credentials for each server and environment. Rotate compromised credentials and revoke or invalidate access according to issuer capabilities.

Review server and tool descriptors before enabling them, maintain approved versions of sensitive tool schemas, and treat unexpected changes as requiring revalidation. A server-provided description or annotation should never grant itself additional privileges. Apply tool allowlists with trusted server identity, constrain external destinations, and control which data may be sent to which tool. A malicious tool result should not trigger automatic invocation of a different server merely because it includes instructions.

Do not assume prompt filtering is a comprehensive defense. Enforce data flow policy, authorization, result size limits, output validation and network egress controls. For remote connectors, validate server destinations and redirects, protect authorization metadata fetching against server-side request forgery, and avoid blindly accepting discovery-provided hosts. Local HTTP servers should follow revision-appropriate Origin validation and DNS rebinding protections. Deep implementations of these individual controls belong in later security lessons.

9. Production scenario: a support agent#

Suppose the support department uses a LangChain assistant connected to an orders MCP server. Alice belongs to tenant A and has orders:read, but not orders:cancel. When she asks about order A12, the host can expose the status tool, the MCP server verifies her token and scopes, and the repository queries the order with tenant A as a trusted filter.

If she asks about a tenant B order, the request must not return that record, even if the model generates a plausible order identifier. Avoid exposing resource existence to unauthorized callers when the application policy requires indistinguishable denial responses.

If Alice later receives the cancellation permission, that change does not imply she has confirmed every possible cancellation. The host obtains explicit confirmation for a specific authorized order; the server or execution service verifies the approval and atomically applies its single-use or idempotency policy. A timeout after submission is an ambiguous business outcome: check the durable operation status before retrying.

For auditability, record the request correlation ID, authenticated actor or a controlled pseudonymous identifier, trusted server/tool identity, authorization decision, policy version, approval/operation ID and result category. Redact secrets and sensitive payloads. Store audit records under restricted access with appropriate retention. Never record an access token to prove identity.

10. Security checklist before deployment#

AreaRequired check
IdentityTrusted issuer, signature or introspection validation, expiry and intended audience
AuthorizationTool-level permission, tenant/resource ownership and business-state checks
Credential isolationSeparate server credentials, minimal scopes, protected secret store and safe rotation
TransportTLS and approved endpoints for remote services; trusted subprocess and sandbox for stdio
Tool exposureApproved server/tool mapping, schema review and invocation-time enforcement
Sensitive actionsTrusted confirmation, bounded approval, replay protection and idempotency
OutputsUntrusted content handling, schema/size checks and redaction
ObservabilityCorrelation, denied and successful decisions, sanitized logs
TestingCross-tenant and invalid-token tests, forbidden calls, expired approvals, malicious tool outputs
RecoveryRevocation, disabling compromised connectors and reconciling uncertain business actions

Test the actual deployed OAuth and MCP integration, not only a standalone permission function. Include issuer/key rotation, invalid signatures, wrong audience, expired tokens, lost sessions, token refresh, user changes, direct invocation bypass attempts, approval replay, concurrent writes, result injection and logging checks. Measure authorization failures and latency while preserving privacy.

Interview-ready answer#

I secure MCP access at both the LangChain host and the MCP server. The host authenticates the user, selects trusted servers, obtains resource-specific least-privilege credentials outside the model, and exposes only approved tools. Every request is validated again at the server for token validity, scope, resource ownership and business rules. For remote servers I use TLS and the applicable OAuth authorization framework; for stdio I isolate subprocess permissions, files and environment. Sensitive writes require verified action-specific approval and replay protection. Tool schemas and results are untrusted inputs, so I apply deterministic policy, redaction and audit logging independently of model reasoning. Successful tool discovery is not authorization, and a valid token does not permit every operation.

References

  1. 1.
    MCP specification (2025-06-18)modelcontextprotocol.io
  2. 2.
    MCP authorizationmodelcontextprotocol.io
  3. 3.
    MCP security best practicesmodelcontextprotocol.io
  4. 4.
    MCP transportsmodelcontextprotocol.io
  5. 5.
    MCP toolsmodelcontextprotocol.io
  6. 6.
    LangChain MCP integrationdocs.langchain.com
  7. 7.
  8. 8.
  9. 9.
    PKCE (RFC 7636)rfc-editor.org
  10. 10.
  11. 11.

Related questions

Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation