Complete "Authentication, Authorization, and Secrets Management" first to unlock this lesson.Go to previous lesson

Defensive Goals

MCP tools connect model-directed requests to systems that can read data, modify records, execute processes, or call external services. In production, treat every tool invocation as a request across a trust boundary. The model is not an authorization system, and a tool description is not a security control. Enforce policy in the server or the component that owns the protected resource, where decisions can be checked consistently.

This lesson applies layered controls to a tool that extracts text from a document. The request may be malformed, overbroad, or influenced by untrusted content. The integration may also be compromised or return data designed to mislead downstream components. No single validation step resolves all of these risks: input checks, authorization, execution isolation, output handling, and operational limits address different failure modes.

Validate Inputs and Outputs

Validate tool arguments against a strict schema before execution. Require expected fields and types, reject unexpected fields when practical, and enforce bounds such as maximum path length or document size. Schema validation establishes shape, not permission. A string can have the right type and still name a sensitive file or exploit a downstream parser, so apply semantic checks against the operation's actual policy.

For a file-reading tool, accept a document identifier or resolve paths beneath a configured root. Canonicalize the path, then verify that the resolved target remains inside that root; checking only whether the original string begins with a directory name is not sufficient. Consider symbolic links, platform-specific path separators, and time-of-check/time-of-use races. Prefer opening files through a restricted directory handle or using an application-level identifier mapped to an approved object.

Validate results before returning them to the MCP client. Enforce output size and expected structure, handle decoding failures explicitly, and avoid returning secrets, internal paths, or raw exception details. Treat extracted text as untrusted data: it may contain instructions or misleading claims. Validation can establish that a response is structurally acceptable; it cannot establish that its contents are truthful or safe to follow.

Allowlist Tools and Authorization

Expose only the tools needed for the deployment. An explicit allowlist should identify permitted tool names and, where relevant, permitted argument values or resource scopes. Do not rely on hiding a tool from a model-facing listing as the only restriction: requests can be malformed, clients can differ, and authorization must be checked at invocation time.

Separate tool availability from user authorization. A user who can call a document extraction tool should not automatically be able to read every document visible to the server process. Before execution, check the authenticated principal, requested resource, and action against policy. Pass a narrow, short-lived credential or scoped capability to the integration when supported; avoid giving a general service credential to every tool.

Keep the allowlist and authorization policy reviewable and versioned. When adding a third-party integration, record its owner, purpose, required permissions, data flows, and failure behavior. Remove unused tools and credentials. Log policy decisions with enough context for investigation, while excluding document contents, access tokens, and other sensitive values.

Show an MCP client request passing through argument validation, tool allowlisting and user authorization before an isolated document extractor; show validated, size-limited output returning through a separate output check, with denied paths blocked and audit events recorded.

Sandbox Execution and Limit Resources

Run integrations with the least privilege needed for their task. A document extractor should not inherit broad host filesystem access, unrestricted network access, or administrator privileges. Use an operating-system or container isolation boundary appropriate to the threat model, mount only required data, make unnecessary filesystems read-only, and restrict outbound connections. A container alone is not a complete sandbox; its configuration, host kernel, mounted secrets, and runtime permissions determine much of its protection.

Set resource limits for time, memory, CPU, process count, file size, and temporary storage where the platform supports them. Terminate work that exceeds its deadline and ensure temporary files are cleaned up. For a remote third-party service, isolation also includes limiting the data sent, authenticating the destination, verifying transport security, and defining how failures or timeouts are handled. Avoid sending an entire document when a smaller excerpt or an approved identifier is sufficient.

Design failure behavior deliberately. A timeout or invalid response should fail closed for sensitive actions: do not silently substitute an unverified result or continue with a broader fallback credential. Return a controlled error to the caller, preserve diagnostic detail in protected logs, and avoid exposing stack traces or secrets in the tool response.

Rate Limits and Operational Safeguards

Apply limits per principal and tool, not only as one global threshold. Bound concurrent work, requests per time window, input size, and expensive operations. Choose thresholds from expected workload and resource cost, then monitor rejection rates and latency. A burst allowance can support normal traffic, while a concurrency cap prevents a few slow calls from occupying every worker.

Rate limiting reduces abuse and accidental overload, but it does not replace authorization or sandboxing. Make limit behavior predictable: reject or defer excess work with a clear, non-sensitive error, and avoid retry loops that amplify load. If clients retry, use bounded retries with backoff and ensure operations that change state have suitable idempotency handling.

For untrusted or third-party integrations, maintain ownership and version information, pin or review dependency updates, and test changes before production rollout. Monitor tool invocation volume, timeouts, validation failures, denied resources, and unusual output sizes. Alert on meaningful deviations and have a way to disable an integration or revoke its credentials. Logs should support incident response without becoming a second copy of sensitive data.

Practical Review and Common Failures

Review one invocation from request to response. Confirm that malformed arguments are rejected before side effects; valid arguments are still checked against the caller's permissions; the process cannot reach unrelated files or networks; and returned data is bounded and checked. Test boundary cases such as traversal paths, symbolic links, oversized documents, invalid encodings, slow integrations, malformed responses, and repeated requests.

Common failures include treating schema validation as authorization, trusting a model-generated path, granting a tool broad credentials for convenience, assuming a container is automatically secure, and returning raw third-party output as trusted instructions. Another operational mistake is logging complete arguments and responses for debugging, which can expose sensitive information. Redact by default and retain only fields needed for security monitoring.

A production control set should have an owner and a verification method. For each control, state what it blocks, where it is enforced, and what evidence shows it is working. A test that confirms an unauthorized path is denied is more useful than a policy document that merely says paths are restricted. Re-run these checks when tool code, permissions, dependencies, or deployment boundaries change.

Lesson practice

Lesson Checkpoint

Review what you learned and get feedback on your work.

0/1
Answered · 0/1