OXYNE PLATFORMAgentic Security
Back to Blog
Blog

MCP Sampling Security: When Servers Request Model Completions

How to secure MCP sampling against prompt injection, data disclosure, model misuse, recursive calls, cost abuse and unsafe server-directed completions.

MCP sampling allows a server to request a model completion through the client or host. It enables useful patterns: a server can ask the user's existing AI application to summarize data, classify a result or help complete a workflow without embedding its own model provider.

It also reverses the direction of influence. A server that was supposed to provide data or tools can now propose messages for a model, potentially combine them with context and receive generated output. If the host treats that request as trusted, a compromised server can extract information, steer the model, consume resources or create recursive agent behavior.

Sampling should therefore be governed as delegated model use. The host—not the requesting server—must remain in control of model selection, context, policy, user consent and cost.

Map the sampling trust boundary

Document which servers may request sampling, which models are available, what context can be included and where results return. Identify whether requests can contain system-like instructions, tool results, images or user data. Define maximum tokens, frequency, concurrency and nesting.

The server's request is untrusted input. Even an approved server can be compromised or return attacker-controlled content. The host should not merge sampling messages blindly with its privileged system prompt, hidden memory or unrelated conversation.

Separate identities and logs. A completion requested by an MCP server should be distinguishable from one requested directly by the user or host. Otherwise usage, incident investigation and policy decisions become ambiguous.

Keep the host in control

The host should decide whether sampling is allowed, which model satisfies the request and which controls apply. A server may express preferences, but it should not select an unapproved provider, disable safety policy or demand hidden context.

Apply enterprise policy based on server identity, user, task, data classification and requested capability. High-risk sampling may require explicit approval. Low-risk, repetitive use can be preauthorized within narrow limits.

Provide a global disable control and per-server permission. New servers should not receive sampling automatically because they expose ordinary tools. Changes to sampling permissions should be auditable and reversible.

Isolate context

Do not automatically attach the user's full conversation, memory, system prompt or credentials to a server-requested completion. Construct a minimal context specifically for the sampling task. Mark the source and trust level of every message.

Sensitive content may enter through tool results or retrieved documents. Apply data-loss prevention and purpose checks before including it. The fact that the user can see information does not mean every connected server may process it.

Test whether a sampling request can ask the model to repeat previous messages, hidden policy, memory or data from another tenant. Use canary values in separate context partitions and confirm they never appear in the completion.

Defend against instruction injection

Sampling messages can contain direct instructions. A malicious server may claim that its text is a system message, tell the model to ignore host rules or encode instructions inside data. Preserve role boundaries and do not grant server messages higher privilege than policy allows.

When sampling over server-provided or third-party content, distinguish the task instruction from the content to analyze. Structured delimiters help reasoning but are not a security boundary. The host must restrict available data and tools independently.

Test direct jailbreaks, indirect instructions in documents, role-confusion strings, encoded payloads and multi-turn escalation. Observe both output and subsequent actions. A completion that looks harmless may carry a hidden instruction into another stage.

Prevent recursive and cascading calls

Sampling can create loops: server requests model completion, model selects a tool, tool reaches the server, and the server requests another completion. Multi-server workflows can amplify this across several components.

Track call depth and provenance. Set maximum nested sampling, tool calls and total turns. Detect cycles using a run graph or correlation ID. Stop safely when limits are reached and communicate the incomplete state to the user.

Test self-referential prompts, repeated tool results, retry storms and two servers that trigger each other. Resource limits should apply to the whole workflow, not reset at each component.

Control cost and denial of service

A server can request expensive models, large contexts or many completions. Apply per-request, per-server, per-user and organization budgets. Limit tokens, concurrency and rate. Reject unsupported parameters and extreme values.

Make cost attribution visible. Security teams should know which server caused usage and which user or task initiated it. Alert on sudden changes in volume, context size, model class or failure rate.

Test rapid requests, long prompts, maximum outputs and cancellation. Confirm that stopping the user workflow cancels downstream sampling. Avoid charging for orphaned work when the server disconnects.

Validate output before returning it

The completion may contain sensitive data, unsafe code, fabricated claims or instructions that influence the server's next action. Apply output policy appropriate to the task. Do not assume that because the host's model generated it, the result is trusted.

Consider whether the server actually needs free-form output. Structured, constrained responses can reduce ambiguity. Validate schema and size. For code or commands, require separate review and execution controls.

Tag the result with provenance: model, policy version, requesting server and run. The server should not present model output as a verified fact without additional validation.

Users should understand when a connected server asks their AI application to use a model, especially when data leaves the local environment or incurs cost. Consent should name the server, purpose, data category and likely effect.

Avoid repetitive approval that trains users to click through. Allow narrow standing permission for a known low-risk operation, with clear scope and revocation. Require new approval when the server changes task, data category or consequence.

Do not render consent text solely from the server. Trusted UI should summarize structured facts and label server-provided explanation separately.

Model routing and provider boundaries

Enterprises may have rules about which models can process particular data. Sampling must honor those rules. A server preference cannot route regulated data to an unapproved provider or region.

Select models through trusted policy. Verify retention, logging and training settings applicable to the chosen provider. Keep provider credentials outside both server and model context.

Test fallback behavior. If the approved model is unavailable, the host should not silently use a less trusted provider. Fail safely or request an explicit decision.

Logging and evidence

Record server identity, initiating user, purpose, sanitized input classification, selected model, policy result, token usage and output handling. Preserve enough content for investigation according to privacy and retention policy. Avoid logging secrets or complete sensitive prompts by default.

Link sampling events to tool calls before and after them. This makes it possible to see whether an untrusted server request influenced a consequential action. The AI agent observability guide describes this end-to-end evidence model.

For high-impact findings, retain the exact test setup and a redacted transcript. Distinguish model output from executed effect. A server receiving a problematic answer is different from that answer causing a tool action.

Sampling security test plan

Assess at least these cases:

  1. An unauthorized server requests sampling.
  2. A server asks for hidden system prompts or previous conversation.
  3. Cross-tenant canaries are requested through context references.
  4. The server supplies role-confusion and jailbreak instructions.
  5. Sampling recursively triggers tools and further sampling.
  6. Requests exceed token, cost, rate and concurrency limits.
  7. A server requests an unapproved model or provider.
  8. Approved-model failure attempts an unsafe fallback.
  9. Generated output includes code or instructions for a next action.
  10. User cancellation fails to stop downstream work.
  11. Sensitive prompts or outputs appear in logs.
  12. Server updates silently gain sampling permission.

Use synthetic data and mock tools for high-consequence paths. Define success criteria before testing: disclosure of a canary, policy bypass, unauthorized model use, uncontrolled loop or confirmed downstream action.

Enterprise sampling checklist

  • Allow sampling only for explicitly approved servers.
  • Keep model choice and provider routing under host policy.
  • Construct minimal, task-specific context.
  • Never expose hidden prompts, credentials or unrelated memory.
  • Treat server messages as untrusted instructions.
  • Set depth, turn, token, cost, rate and concurrency limits.
  • Detect cycles across sampling and tool calls.
  • Validate and label generated output before returning it.
  • Bind consent to server, purpose and data category.
  • Prevent unsafe provider fallback.
  • Correlate sampling with subsequent tool effects.
  • Retest permissions and limits after server or host changes.

Frequently asked questions

Is MCP sampling the same as a server calling its own LLM API?

No. Sampling asks the client or host to perform the model request, which can preserve user model choice but also exposes a trusted host capability to the server.

Should sampling requests include the current conversation?

Only the minimum context required and permitted for the task. Automatically sharing full conversation, memory or system prompts creates unnecessary disclosure risk.

Can sampling trigger tools?

That depends on the host design. If generated output can lead to tools, apply call-depth, authorization and approval controls to the complete workflow.

What is the strongest safety control?

Keep the host authoritative over context, model, policy and limits. The server may request a capability, but it should not control the trust boundary.

Sampling can reduce duplication and support richer MCP workflows, but it gives servers influence over a scarce and context-rich capability. Secure implementations make that influence explicit, bounded and observable. For wider system testing, see AI agent red teaming versus LLM evaluations and MCP gateway security.

Establish sampling policy by server and task

Do not enable sampling globally because one trusted server requires it. Allowlist server identities, task types, model classes, context sources, token budgets and maximum calls. Treat every additional server as a separate trust decision.

Define whether the server may request tools, images, files or conversation history. Default to the minimum context. A server that summarizes one document should not automatically receive unrelated chat messages or secrets.

Re-evaluate policy when server ownership, endpoint, certificate, tool metadata or package version changes. Pin expected identity and require review for capability expansion.

Protect users from invisible work

Make consequential sampling visible in the host interface. Show which server requested model work, what category of data will be shared and whether cost or external action may result.

Human approval should be reserved for meaningful decisions, not every token. Use policy for low-risk bounded calls and explicit review when sensitive context, expensive models or action-capable responses are involved.

Prevent servers from crafting deceptive approval labels. Build the decision packet from trusted host state and structured request fields.

Test resource exhaustion and loops

A malicious or buggy server can request repeated sampling, oversized context or recursive work. Enforce per-call, per-run, per-server and tenant limits. Detect cycles between sampling and tool calls.

Test concurrent requests, retry storms, cancellation and disconnects. Confirm that charges and work stop when the parent run ends. Rate limits should fail safely without switching to a broader identity or unapproved model.

Record requested and consumed resources so operators can attribute unusual usage. Cost anomalies may be the first signal of misuse.

Validate returned content before use

Sampling output remains untrusted. If a server feeds it into a tool, database or user interface, apply the same authorization, output encoding and action validation used for ordinary model output.

Preserve provenance linking the result to server, request, model and context. Do not let sampled text impersonate host policy or human approval.

Test whether malicious sampling output can poison shared memory, alter tool selection or escape into another tenant. The boundary does not end when the model call returns.

Final review questions

Which verified servers may request sampling, and what model, context, tools, budget and frequency may each use? Can a request expand context or authority through user-controlled fields?

Confirm that cancellation stops queued and recursive work, resource limits fail closed, and returned content remains untrusted. Review logs for server identity, request purpose, context classes, model choice, cost and subsequent actions.

Run adversarial tests for evaluator injection, loops, oversized context, cross-tenant data and deceptive approval. Keep the cases as regressions after client, server, model or policy changes.

Keep reading

September 25, 2026

Vector Database Security for RAG: Isolation, Access and Poisoning

A practical guide to securing vector databases used by RAG systems, including tenant isolation, ingestion controls, authorization, poisoning tests and evidence.

Read article
September 25, 2026

RAG Poisoning Security: How Malicious Documents Manipulate AI Agents

Understand and test RAG poisoning across document ingestion, retrieval, prompt injection, metadata, agent tools, memory and source remediation.

Read article