Complete "Threat Modeling MCP Systems" first to unlock this lesson.Go to previous lesson

Introduction

Production MCP security depends on three separate decisions: who is calling, what that caller is allowed to do, and how credentials are stored and used. Authentication establishes an identity, authorization evaluates that identity against an action and resource, and secrets management protects the credentials required to reach dependent systems. Treating these as one problem usually creates broad permissions, unclear audit records, and credentials that are difficult to rotate.

An MCP server should make authorization decisions at the server boundary, immediately before a tool or resource operation is executed. Do not assume that a client interface, a model instruction, or a previous successful request is sufficient proof of permission. Every request should carry enough trusted context to evaluate the current identity, tenant, action, resource, and relevant constraints. When a required attribute is missing, the safe result is denial, not an inferred permission.

This lesson uses a small transport-neutral Python example to make the decision process concrete. The example is not an MCP SDK and does not replace the authentication or authorization features of a particular deployment. It demonstrates the policy logic that an MCP server can apply after its transport has validated the request and established trusted identity claims.

Flowchart showing an MCP request moving through identity verification, tenant-context validation, policy evaluation, secret retrieval, tool execution, and audit logging, with denied requests stopping before secret retrieval

Authentication And Identity Context

Authentication answers whether a presented identity can be trusted. In production, an MCP deployment may receive identity from a validated session, an enterprise identity provider, a workload identity mechanism, or a gateway that verifies a token before forwarding trusted claims. The exact mechanism depends on the deployment, but the server must define which component validates credentials, which claims are trusted, how expiration is checked, and how identity is represented internally.

A useful internal identity record contains a stable subject identifier, a tenant identifier, an actor type, and the permissions or roles relevant to the policy decision. Keep the original external token separate from this internal context whenever possible. Tool implementations normally need identity claims, not a bearer token. Passing raw tokens into model-visible arguments, tool results, logs, or unrelated downstream services increases exposure without improving authorization.

Authentication also needs lifecycle controls. Reject expired, malformed, or incorrectly scoped credentials. Distinguish an end user from a service account, because a service account should not automatically inherit a human user's permissions. Record the authentication method and identity identifier in audit events, while avoiding token values and other secret material. A successful authentication event must not be treated as a blanket authorization grant.

Least-Privilege Authorization

Authorization should evaluate a specific request, not merely a broad role name. A practical decision model includes subject, tenant, action, resource, environment, and constraints such as read-only mode or approval status. For example, reading a report for tenant alpha is different from exporting all reports, deleting a report, or reading a report belonging to tenant beta. The policy should name these operations separately so that a permission granted for one does not silently imply the others.

The default policy should be deny. Allow only when the request has a known action, a known resource scope, a valid tenant match, and an explicit permission. Avoid wildcard permissions for production service accounts unless the operational requirement is documented, narrowly bounded, and monitored. Separate high-risk operations such as deletion, credential rotation, bulk export, and configuration changes from ordinary read operations.

The following runnable example evaluates a small policy. Its input is a JSON request containing identity and request attributes. Its output is a JSON decision and reason. The example intentionally denies missing tenant context, cross-tenant access, unknown actions, and permissions that are not explicitly present.

python
import json
import sys
def authorize(request):
identity = request.get("identity") or {}
subject = identity.get("subject")
tenant = identity.get("tenant")
permissions = set(identity.get("permissions") or [])
action = request.get("action")
resource_tenant = request.get("resource_tenant")
if not subject or not tenant:
return {"allow": False, "reason": "missing_identity_context"}
if not action or not resource_tenant:
return {"allow": False, "reason": "missing_request_scope"}
if tenant != resource_tenant:
return {"allow": False, "reason": "cross_tenant_access"}
if action not in {"report:read", "report:export"}:
return {"allow": False, "reason": "unknown_action"}
if action not in permissions:
return {"allow": False, "reason": "permission_not_granted"}
return {"allow": True, "reason": "explicit_permission"}
if __name__ == "__main__":
request = json.load(sys.stdin)
print(json.dumps(authorize(request), sort_keys=True))

For example, provide the program with a request whose identity tenant is alpha, whose resource tenant is alpha, and whose permissions contain report:read. The result is an allow decision. Changing the resource tenant to beta produces a cross-tenant denial even when the identity has report:read. A malformed JSON document causes the standard JSON parser to exit with an error; missing fields produce a structured denial instead of an exception or an accidental allow.

Tenant Isolation And Scoped Access

Tenant isolation is stronger than adding a tenant field to a log message. The tenant boundary must be enforced in the authorization decision and in the data access layer. A tool should derive the effective tenant from trusted identity context, compare it with the requested resource scope, and pass the approved scope to the repository or downstream service. Do not let a model-generated argument replace the trusted tenant identifier.

Resource scope should be as narrow as the task allows. A request to read one report should produce a query constrained to that report and tenant. A request to export a dataset should require a separate permission, an explicit export scope, and appropriate limits on volume and frequency. For administrative operations, require an independently verified administrative identity and, where appropriate, an approval or step-up authentication signal.

Be careful with indirect access paths. Search tools, analytics tools, file tools, and error messages can disclose data even when the primary read operation is protected. Apply tenant filtering to search results, aggregates, filenames, metadata, exception text, caches, and asynchronous jobs. Test both direct and indirect paths, including an authorized identity attempting to access a neighboring tenant and an unauthenticated request attempting to infer whether a resource exists.

Comparison diagram with two tenants and isolated resource stores, showing an allowed same-tenant read path and a blocked cross-tenant path at both the MCP authorization layer and the data repository layer

Secrets Management And Tool Execution

A secret is any value whose disclosure or unauthorized use can grant access, including API keys, client secrets, database passwords, signing keys, and short-lived access tokens. Store production secrets in an approved secret manager or equivalent platform facility, with access controlled by workload identity. Do not put them in source code, configuration committed to version control, prompts, tool arguments, model context, exception messages, or ordinary application logs.

Secret retrieval must occur after authorization and as close as practical to the downstream operation. The MCP server should request only the specific secret needed for the approved action, use it for the shortest practical time, and avoid returning it to the caller. Prefer short-lived credentials and automatic rotation where the dependency supports them. Rotation must be tested as an operational workflow, because a policy that works only until the first rotation is not production-ready.

The authorization example can be extended with a secret provider, but the provider itself must enforce workload identity and secret-level policy. A tool should not accept an arbitrary secret name from a model-generated argument and then retrieve it. Map an approved operation to an allowed dependency internally, and reject unexpected mappings. Redact sensitive values before logging request details, tool results, headers, or stack traces.

A common failure is authorizing a request first and then logging the complete request object, including an access token or credential supplied by a client. Another is using one powerful service credential for every tenant and every tool. These designs make compromise harder to contain. Use separate identities or secret paths for different services and environments, restrict access by tenant or operation when supported, and monitor secret reads as security events.

Operations And Common Failures

Authorization is an operational control, so monitor its decisions. An audit event should identify the subject, tenant, action, resource classification, decision, reason, policy version, and correlation identifier. It should not contain secret values or unrestricted sensitive payloads. Alert on repeated denials, cross-tenant attempts, unusual export volume, unexpected secret reads, and service accounts performing interactive or administrative actions.

Common implementation errors include trusting a tenant identifier supplied by the client, checking roles without checking the requested resource, treating authentication as authorization, allowing unknown actions by default, and returning detailed downstream errors to model-facing clients. Another error is testing only the happy path. Tests should cover expired identity, missing claims, wrong tenant, unknown action, insufficient permission, secret-store failure, rotation, and audit redaction.

A secret-store outage should fail closed for operations that require the unavailable credential. Do not silently use a fallback credential with broader access. A policy configuration error should also produce a denial and an operator-visible alert. Distinguish a user denial from an internal dependency failure in logs and metrics, while returning only the minimum safe information to the caller.

Before production release, review each MCP tool with four questions: what identity does it trust, what exact actions does it allow, what tenant and resource scope does it enforce, and which secrets can it access? Document the answers, test them automatically, and review them when a tool, dependency, tenant model, or credential lifecycle changes.

Summary

Authentication provides a verified identity, but it does not decide what that identity may do. Authorization must evaluate every sensitive operation using explicit action and resource permissions, trusted tenant context, and a deny-by-default policy. Tenant isolation must be enforced both at the MCP boundary and in downstream data access so that search, metadata, exports, and errors cannot bypass the boundary.

Secrets should be retrieved only after authorization, through an approved secret-management system, using the narrowest available identity and the shortest practical lifetime. Keep secrets out of model context, tool responses, logs, and source code. Production readiness also requires auditability, rotation, failure-safe behavior, and tests for negative paths, because the most damaging authorization bugs occur when assumptions remain implicit.

The central implementation rule is simple: authenticate the caller, authorize the exact action against the exact scope, retrieve only the required secret, execute within that scope, and record a redacted decision that can be investigated later.

Lesson practice

Lesson Checkpoint

Review what you learned and get feedback on your work.

0/1
Answered · 0/1