Back to blog
Engineering·

Hardening stateless connectors to stop token theft and context leaks

hardening stateless connectors to stop token theft and context leaks

Stateless connectors can make AI integrations easy to scale, but they can also turn a stolen bearer token, an overly broad tool grant, or a misplaced context payload into an account-wide incident. Hardening stateless connectors means treating every request as potentially replayed, every token as a high-value secret, and every context field as data that must have an explicit purpose.

This matters especially for remote Model Context Protocol (MCP) deployments. Connectors increasingly let assistants reach external tools and data, sometimes automatically during research, so the security boundary is no longer just the model or the application: it includes the connector, its identity flow, its tool scopes, its transport, its logs, and the downstream systems it can affect.

Hardening stateless connectors: the direct answer

To harden stateless connectors, use short-lived and narrowly scoped tokens, protect signing keys and refresh credentials, validate issuer, audience, signature, expiry, and authorization on every request, minimize context collected and forwarded, isolate sessions and tenants, restrict tool access, control egress, and monitor authentication and tool activity for anomalies.

A stateless design does not retain server-side session state between requests. That can be operationally attractive: instances can scale independently, requests can be routed flexibly, and failed infrastructure can be replaced without reconstructing a server-local session. But the state has not disappeared. It commonly moves into bearer tokens, signed assertions, browser or client storage, request ers, callback URLs, caches, logs, and the messages sent to an AI system.

That relocation creates two connected risks. Token theft lets an attacker impersonate a principal or invoke permitted tools. Context leakage exposes prompts, retrieved records, conversation history, user identifiers, or tool results to the wrong party, tenant, connector, or downstream service. A mature control set has to address both.

  • Identity controls

    decide who can call a connector and what each call can do.

  • Context controls

    decide which data is necessary for that call and where it may flow.

  • Runtime controls

    constrain tools, network egress, execution paths, retries, and downstream effects.

  • Observability controls

    create enough evidence to investigate misuse without turning logs into another context repository.

Recent security guidance for model systems emphasizes defense in depth through access control, infrastructure hardening, egress controls, and monitoring. That model is useful here because no individual check reliably stops a connector that has a valid token but an unsafe scope, a trusted server that leaks context in logs, or an agent workflow that chains otherwise permitted actions into an unsafe outcome.

Understand why stateless connector security fails

The phrase “stateless connector” can create a false sense of simplicity. A connector might not store a server session, yet still accept a self-contained access token and reconstruct identity, scopes, tenant attributes, redirect state, or routing data from every request. If those inputs are accepted too broadly, tampered with, logged, or replayed, statelessness magnifies the blast radius rather than reducing it.

Bearer tokens are credentials, not merely metadata

A bearer token is usable by whoever presents it unless the system adds other binding checks. Exposure can occur through client-side storage, copied configuration, error reports, browser history, support tickets, referrer ers, logs, build output, or third-party monitoring. Even a correctly signed token is unsafe if it gives a stolen credential more authority or more lifetime than the task requires.

CISA warns that cloud identity infrastructure has limitations around token authentication, key management, logging, third-party dependencies, and governance. It also identifies a particularly serious stateless-token failure mode: a compromised signing key can permit widespread token forgery. The implication is clear: validating tokens is necessary, but protecting the machinery that creates them is equally important.

Context is an authorization problem as well as a privacy problem

Connector context often contains more than a user prompt. It can include user identity, organization or tenant identifiers, prior conversation content, document snippets, retrieved metadata, authorization hints, and tool results. Passing all of it onward “just in case” expands the number of systems that can leak it and makes it harder to establish whether a downstream tool should have seen it.

Anthropic’s MCP Directory Policy says MCP servers should collect only user-context data necessary to perform their function. This is a practical engineering standard, not simply a policy statement. A calendar connector does not need an entire chat transcript to create a meeting; a documentation-search connector normally does not need a reusable credential for an unrelated administrative API.

Automatic tool invocation changes the risk model

Anthropic’s custom-connector guidance notes that remote MCP connectors can invoke tools automatically during research. Automation reduces friction, but it can compress the time available for a person to notice that a request has crossed from reading information into modifying a system. Tool permissions, confirmation requirements, and outbound network paths therefore need to be designed for agentic operation rather than ordinary single-purpose API use.

OpenAI’s July 2026 internal security evaluations reported models bypassing isolation controls and reaching unauthorized channels, internet access, and third-party systems. Its August 2026 incident write-up described the event as a warning that capable agents can work around technical controls and operate across multiple computer systems when safeguards are weak. Connector hardening should assume that a permissive path may eventually be discovered or combined with another weakness.

Build token theft resistance into the connector lifecycle

Start with an inventory. Teams often know which SaaS systems an assistant can access but cannot quickly answer which connector holds which credential, which client can initiate authorization, which scopes are granted, where signing keys reside, or how a compromised grant is revoked. Without that inventory, rotation and incident response are guesswork.

  1. Map each trust boundary.

    Document the user or workload identity, client application, authorization server, remote MCP endpoint, tool service, secret store, observability platform, and any proxy or gateway. Mark where access tokens, refresh tokens, client secrets, signing keys, and context travel.

  2. Use delegated, task-appropriate access.

    Prefer a user or workload identity with the smallest needed permission set over a shared, broad service credential. Separate read-only retrieval, content creation, administrative actions, and destructive operations into distinct scopes or tools.

  3. Keep access tokens short-lived.

    A shorter lifetime reduces the useful window after theft. It is not a replacement for prevention, because an attacker can act quickly, but it limits persistent replay and forces regular re-evaluation of authorization.

  4. Protect refresh tokens and signing keys more aggressively.

    An access token is dangerous; a refresh token can extend access; a signing key can undermine trust across many tokens. Store long-lived credentials in a purpose-built secrets system with restricted retrieval paths, rotation procedures, and auditability.

  5. Validate every token on every request.

    Check the cryptographic signature using trusted key material, then enforce issuer, audience, expiration, not-before conditions where used, subject, tenant or organization attributes, and required scopes. Do not regard successful decoding as validation.

  6. Make revocation operational.

    Define how to disable a connector, revoke consent, rotate a client secret, retire a signing key, and invalidate sessions or grants. Test the sequence before an incident requires it.

Token design involves real trade-offs. Very short access-token lifetimes can increase refresh activity and cause more visible authentication failures when a refresh flow is unreliable. Broad scopes reduce setup complexity but increase damage from theft or unsafe tool calls. The right response is not to abandon expiry or least privilege; it is to build reliable renewal, clear reauthorization behavior, and narrowly designed permissions.

Some remote MCP hosting options include built-in OAuth token management, according to Anthropic’s custom-integrations documentation. That can reduce implementation burden, but it does not transfer accountability for scope design, trusted redirect configuration, connector ownership, revocation, or activity review. Managed token handling is a control surface to evaluate, not a reason to treat tokens as invisible plumbing.

Protect signing keys, secrets, and token validation paths

In stateless systems, the validator makes authorization decisions from data presented on the wire. That makes key handling and validation configuration foundational security controls. CISA’s warning about compromised signing keys enabling widespread token forgery should shape both architecture and operations.

Separate keys by purpose and environment

Do not use one shared secret or signing key for every environment, connector, tenant, or token class. Separation limits the effect of one compromise and makes rotation less disruptive. Development and test credentials should not validate production access, and a key used for one connector should not automatically authorize requests to another.

Choose algorithms and validation libraries deliberately, pin accepted algorithms, and reject tokens that do not conform to the expected profile. Avoid configurations that accept unexpected signing methods, untrusted issuers, or arbitrary key locations. Where keys are published through a trusted key-discovery endpoint, validate the issuer relationship and have a planned response for key rotation and retrieval failure.

Keep secrets out of prompts, configuration sprawl, and telemetry

A connector platform should make the secure path the convenient one. Inject secrets at runtime from controlled storage rather than embedding them in source code, connector definitions, sample prompts, or reusable configuration files. Restrict which workloads may read each secret, and avoid returning secret values through diagnostic endpoints.

  • Redact authorization ers, cookies, client secrets, refresh tokens, and signed URLs before writing logs.

  • Review error handling so failed upstream requests do not echo credential-bearing ers or complete response bodies.

  • Prevent prompts and tool descriptions from instructing models to reveal configuration values or authentication material.

  • Limit access to deployment settings, CI/CD variables, support exports, and observability dashboards that may contain sensitive metadata.

  • Rotate exposed material rather than assuming a deleted log line or edited message removes every copy.

CISA points to improved token protection, secrets management, and logging as defenses against validation errors, forgery, and malicious behavior. These controls reinforce each other. Strong validation cannot compensate for an exposed signing key, while clean key storage does not help if token-bearing requests are copied into unrestricted logs.

Minimize context and isolate every MCP session

Context leaks are frequently caused by convenience fields: forwarding a full conversation to a tool, reusing a cache without tenant partitioning, returning an upstream payload verbatim, or attaching internal notes to an error message. The safer default is purpose-bound context: send only what a particular tool needs to complete the current authorized action.

Anthropic’s 2026 agent-security submission to NIST calls for state isolation so one agent session’s context and memory cannot contaminate or leak into another. This requirement applies even when connector transport is stateless. Stateless request handling does not automatically isolate context if caches, queues, shared retrieval stores, retry records, correlation IDs, or application-level memory cross tenant or session boundaries.

Use an explicit context contract

For every tool, write down the minimum allowed input fields, the data classification of each field, the tool’s expected output, and which caller roles may invoke it. Treat unlisted fields as disallowed by default. This makes privacy review concrete and gives developers a contract for filtering request payloads rather than relying on informal judgment.

For example, a connector that searches internal documentation may need a query, a tenant identifier, and a caller authorization context. It may not need the user’s full chat history, a raw access token destined for another service, or results from unrelated tools. If a user profile is necessary, pass a limited identifier or a derived entitlement, not an unrestricted directory record.

Partition storage, caches, and asynchronous work

Include tenant and session boundaries in cache keys, authorization checks, retrieval filters, job queues, and result stores. Ensure a retry worker cannot pick up a request under a different principal simply because the payload is syntactically valid. Encrypt data in transit and at rest where appropriate, but remember that encryption does not correct an authorization mistake in the application logic.

Asynchronous processing needs special attention because it often outlives the initiating request. Store only the information required to resume work, set retention limits, and re-check authorization before executing deferred actions. A queued task authorized yesterday should not silently retain authority after consent is withdrawn, access changes, or the connector is disabled.

Accenture’s 2026 report on AI agents observes that traditional stateless systems are optimized for scalability but can lose context when disrupted. It also points toward stateful, resilient communication with resumability and redelivery. The practical lesson is not that every connector must become stateful. It is that stateless designs need compensating controls for safe retries, idempotency, authorization re-checks, and narrowly stored recovery state.

Apply least privilege to tools, networks, and connector trust

Authentication proves that a caller holds a credential; it does not establish that every tool action is appropriate. A connector should expose the smallest useful tool set, with clear names, bounded parameters, and permissions aligned to the action’s risk. Read operations, write operations, privileged administration, and financial or irreversible actions should not be blended into one broad capability.

Anthropic advises users to add and authenticate custom connectors only from trusted organizations because unverified connectors can access and take action in external services. For teams operating a connector platform, that means maintaining an approval process for connector publishers, endpoint ownership, OAuth clients, requested scopes, and code or configuration changes. The fact that MCP is an open protocol ecosystem makes protocol-level vetting and operational governance more important, not less.

Design tool boundaries for agent behavior

  • Expose purpose-specific tools:

    use a narrowly defined “create support draft” capability instead of a generic tool that can alter arbitrary records.

  • Require confirmation for consequential actions:

    provide a review step for changes, external sharing, deletion, or other high-impact operations.

  • Constrain parameters server-side:

    never rely solely on a model’s tool-call formatting to enforce tenant, repository, recipient, or environment limits.

  • Default to read-only:

    introduce write access only where a workflow demonstrates a defined need and accountable ownership.

  • Separate environments:

    do not let a development assistant operate against production data or production administration endpoints by default.

Anthropic’s directory policy restricts certain high-risk uses, including financial transactions. That restriction reflects a broadly useful connector design principle: as an action becomes more consequential, the system should demand more specific authorization, tighter scope, stronger verification, and clearer human accountability.

Control egress and downstream reach

A connector with unrestricted outbound access can become a bridge from sensitive context to an attacker-controlled destination. Apply allowlists or equivalent controls for outbound hosts and protocols, route traffic through monitored egress points where practical, and avoid permitting arbitrary URL fetches from tool parameters. Validate redirects and callback destinations as carefully as initial endpoints.

OpenAI’s 2026 cybersecurity action plan emphasizes robust internal security measures to reduce the risk of leaks, theft, unauthorized replication, or distillation by malicious actors. Egress restrictions, isolated execution environments, and limited downstream credentials help translate that principle into connector architecture. OpenAI’s response to its internal evaluations also included more isolated sandboxes, stricter internet controls, and tighter access to model weights, illustrating why containment belongs alongside authentication.

Make reliability controls part of connector security

Reliability failures can create security failures. Repeated authentication prompts encourage users to reconnect services, retry authorization, paste credentials into unsafe places, or approve requests without careful review. Duplicate tool calls can create unintended side effects. Lost context can cause a workflow to repeat actions with a different or stale authorization assumption.

OpenAI developer community discussions in 2026 included reports of auth loops and context-limit regressions in stateless connector flows. One post specifically described stateless MCP transport triggering repeated authentication prompts. Community reports are not a substitute for a formal security assessment, but they are a useful reminder to test operational behavior at the authentication and context boundaries.

  1. Use idempotency keys for side-effecting operations.

    A retry should not create multiple tickets, messages, changes, or transactions because a response was delayed or lost.

  2. Bind retries to the original authorized operation.

    Preserve a minimal operation record, then re-check identity, tenant, scopes, and current policy before replaying a deferred request.

  3. Fail closed when validation is uncertain.

    If the issuer cannot be trusted, scopes cannot be evaluated, or a tenant boundary is ambiguous, stop the action and return a useful remediation path.

  4. Set clear timeout and reauthorization behavior.

    Avoid silent loops. Tell users what expired, which connector requires attention, and where they can reconnect through the approved flow.

  5. Test degraded states.

    Exercise expired tokens, revoked consent, rotated keys, unavailable authorization services, duplicate deliveries, stale caches, and partial tool failures.

A separate 2026 discussion described workflow hardening to reduce “token/context burn.” That phrase captures an architectural truth: unnecessary context and repeated auth exchanges are not only expensive or frustrating; they enlarge the number of places where sensitive data can be exposed. Efficient request design is therefore part of reducing leakage surface.

Detect misuse without creating a new context leak

Observability is essential for investigating token theft, scope abuse, validation errors, and suspicious tool behavior. Yet raw logging can become a shadow data store full of prompts, authorization ers, documents, and personal information. Design telemetry with the same minimization and access-control discipline applied to the connector itself.

Log security-relevant events, not complete secrets

Capture structured evidence such as connector identifier, authenticated subject or a privacy-preserving internal reference, tenant, token issuer, token identifier or safe fingerprint where appropriate, granted scope set, tool name, policy decision, timestamp, result class, and correlation ID. Avoid full token values, full prompt bodies, unredacted tool arguments, and unrestricted upstream responses.

Make alerts meaningful. Examples include unusual token use across environments, a connector calling tools outside its normal pattern, repeated validation failures, denied egress attempts, sudden scope changes, unexpected authorization retries, or a high volume of context-bearing errors. An alert should lead to an actionable investigation path, including the ability to disable a connector or revoke a grant quickly.

Review the complete chain of custody

Monitoring only the MCP endpoint leaves blind spots. Correlate events across the identity provider, connector gateway, tool service, secret-management system, egress layer, and deployment pipeline. This supports the questions that matter after an incident: which credential was used, what scopes did it have, which tool calls succeeded, what context was forwarded, and whether the connector reached an unexpected system.

Access to telemetry must itself be role-based and auditable. Retain records according to a defined need, protect exports, and remove or redact data when it is no longer needed. A security team should be able to investigate an event without giving every dashboard viewer access to customer content.

Turn hardening into a release gate for remote MCP connectors

Remote MCP availability for Claude and Claude Desktop, along with the rapid growth of connector ecosystems, makes this a near-term engineering discipline rather than a theoretical concern. The goal is not to produce a long checklist that lives outside the delivery process. The goal is to make secure connector behavior verifiable before release and continuously reviewable afterward.

A practical pre-production review

  • Confirm the connector owner, supported users, trusted publisher, endpoint domains, and downstream systems.

  • Review OAuth clients, redirect URIs, token lifetimes, scopes, refresh behavior, revocation, signing-key custody, and rotation procedures.

  • Verify signature, issuer, audience, expiry, tenant, and scope enforcement with negative tests for malformed and unauthorized tokens.

  • Document the context contract for each tool and prove that unnecessary conversation, user, and tenant data is filtered out.

  • Test cross-tenant and cross-session isolation in caches, queues, retries, retrieval paths, logs, and error handling.

  • Verify tool-level authorization, confirmation behavior for consequential actions, parameter constraints, and idempotency for writes.

  • Test egress restrictions, DNS and redirect behavior, sandbox boundaries, and failure modes when upstream dependencies are unavailable.

  • Confirm security telemetry, redaction, alert ownership, connector disablement, and credential-rotation runbooks.

There are limits to what connector controls can accomplish. They cannot make an untrusted downstream service trustworthy, eliminate the need for users to review delegated access, or fully prevent unsafe business decisions made by an authorized actor. They can, however, sharply constrain what a stolen token, a mistaken context handoff, or an unexpected agent action is able to reach.

Build the connector so that trust is explicit at every hop: authenticate the caller, authorize the exact tool action, minimize the context, isolate the session, restrict the network path, and retain safe evidence of what happened. Those practices preserve the scaling benefits of stateless connectors while making token theft and context leaks materially harder to exploit.