Home/Blog/Securely add remote tool endpoints: OAuth, API keys and stateless best practices
Securely add remote tool endpoints: OAuth, API keys and stateless best practices
September 2, 2026

Remote tool endpoints let AI agents move beyond generation and take action: querying enterprise systems, updating records, triggering workflows, or delegating work to specialist MCP-connected agents. That power also creates a security boundary. Every tool call can carry credentials, user context, business data, and authorization decisions across systems that may have different owners, retention policies, and operational controls.
Secure integration starts by choosing authentication according to whose authority the tool is using. OAuth is appropriate when a remote tool acts for a signed-in user, while API keys are generally preferred for server-to-server calls made under application or project authority. In both cases, secrets should stay off browsers and mobile clients, requests should pass through a trusted backend, permissions should be narrow, and credentials should be monitored, revocable, and replaceable.
Start with the authority behind each tool call
Authentication is not only a mechanism for proving identity. In an agent workflow, it determines whose permissions are exercised, which data can be reached, and how investigators can attribute an action later. Selecting OAuth or an API key without first defining that authority can produce integrations that work technically but grant more access than the workflow needs.
For every remote tool endpoint, ask a direct question: is the agent acting on behalf of an individual user, or is the platform performing an application-level operation? The answer should drive the primary authentication pattern.
User-delegated authority:
Use OAuth when the remote service must identify a user, obtain account-specific consent, or enforce that user’s permissions.
Application or workload authority:
Use an API key for server-to-server access where the backend, project, or service owns the operation.
Administrative authority:
Keep organization-management capabilities separate from ordinary application calls. OpenAI’s management documentation, for example, distinguishes Admin API keys from normal API keys for specific administrative endpoints.
Mixed authority:
Use a trusted backend to combine short-lived user authorization with separately protected service credentials. Do not send the service secret to the user’s device.
This classification should happen at the individual tool level, not only at the agent level. A single specialist agent may read a user’s private documents through OAuth, call an internal classification service with a project API key, and submit an administrative request to a separately controlled workflow. Treating all three calls as if they have the same identity would blur important security boundaries.
Separate authentication from authorization
Authentication answers who or what is calling. Authorization answers what that identity may do. A valid credential should not automatically unlock every route exposed by a remote tool server.
OpenAI supports API-key permission levels including All, Restricted, and Read Only, with endpoint-level controls available for restricted keys. This distinction is operationally important: a key can be valid while still being unable to invoke unrelated or destructive operations. Apply the same principle to internal tools by defining explicit capabilities for read, write, delete, export, administration, and other sensitive actions.
A remote tool should receive the narrowest authority needed for the current workflow, not the broadest authority its host agent might ever need.
Controlled authorization also reduces prompt and tool risk. An agent can be influenced by ambiguous instructions, untrusted retrieved content, or an incorrectly routed task. Strong authorization ensures that an unexpected tool selection does not automatically become an overbroad data-access event.
Document the trust boundary before implementation
A concise trust-boundary record makes reviews more reliable. Identify the calling agent, orchestration backend, remote endpoint, credential issuer, credential storage location, data categories, expected operations, and audit owner. Also record whether the integration crosses organizational or vendor boundaries.
This document does not need to become a large architecture package. Its purpose is to stop implicit assumptions, such as believing that a third-party MCP server follows the same retention rules as the orchestration workspace or that a user login automatically limits a downstream service credential.
Use OAuth for user-specific remote tool access
OAuth is the appropriate choice when a tool needs user sign-in or account-based access. OpenAI’s GPT action guidance identifies the required integration elements: a Client ID, Client Secret, Authorization URL, Token URL, scopes, and a callback URL. Together, these components let the user authorize access without giving the agent or client application the user’s password.
The main security advantage is delegation. The tool can receive access tied to the user and approved scopes rather than a shared credential that represents the entire organization. This gives the remote service a basis for applying its own account permissions and makes authorization more understandable to the user.
Design the OAuth flow around a trusted backend
Initiate authorization from an authenticated session.
The orchestration platform should know which user and workspace are requesting the connection before redirecting to the authorization service.
Request only necessary scopes.
If the tool only reads records, do not request write, delete, export, or administrative access for possible future use.
Validate the authorization response.
Bind the response to the initiating session and accept callbacks only at registered destinations.
Exchange the authorization grant on the server.
The Client Secret and token exchange belong in trusted backend infrastructure, not browser code or a mobile application.
Store resulting credentials securely.
Use a secret-management facility or another storage control designed for sensitive credentials, with access restricted to the runtime that needs them.
Attach user context at execution time.
The orchestration layer should select the correct user connection and confirm that the requested tool operation is permitted before calling the remote endpoint.
Handle expiration and revocation deliberately.
Failed refreshes, revoked consent, or disabled accounts should stop the workflow safely and prompt reauthorization where appropriate.
Short-lived user authorization is preferable to treating one token as a permanent integration credential. The exact lifetime and refresh behavior depend on the provider, but the architectural goal is consistent: limit the useful life of intercepted material and make continued access dependent on current authorization.
Do not let agent context become authorization
An agent may receive a user ID, email address, or workspace role in its context, but that text is not proof of identity. The backend must derive identity from a verified session and map it to the correct stored OAuth connection. Never let model-generated arguments choose an arbitrary credential record or claim another user’s identity.
Tool schemas should also distinguish user-controlled parameters from server-derived fields. For example, an agent may propose a document identifier and an operation, while the backend supplies the verified tenant, user connection, and permitted scope. This prevents a prompt from overriding core authorization attributes.
Make consent understandable and reversible
A user connection should have a clear purpose, visible account identity, and a practical disconnect path. Revocation should remove or disable stored authorization material and prevent subsequent tool execution. If the remote provider also offers a revocation mechanism, integrate it where feasible rather than only deleting the local reference.
For enterprise workflows, administrators may also need policies governing which OAuth providers, scopes, or remote endpoints users can connect. User consent is necessary for delegated access, but it does not replace organizational controls over approved tools and data destinations.
Use scoped API keys for server-to-server calls
OpenAI explicitly recommends API key authentication for server-to-server access and OAuth for user-account access. An API key is therefore a strong fit when an orchestration backend invokes a remote tool as a project, service, or controlled workload rather than as an individual user.
The simplicity of API keys is useful, but it can encourage unsafe handling. OpenAI’s current guidance is unambiguous: never share keys, never ship them in browsers or mobile applications, never commit them to repositories, and use environment variables or secret-management systems instead. Secret handling is a core security control, not a convenience feature.
Prefer project-based credentials over shared personal keys
For OpenAI workloads, Projects are the recommended collaboration model. Teams can assign project members and issue distinct project keys, while isolating rate limits, spend controls, and usage visibility by project. This is safer and easier to operate than passing around one personal credential.
The same model applies broadly to remote tools. A credential should represent a defined workload and environment. It should not depend on the continued employment, device, or account status of one developer, and it should not be reused across unrelated agents.
Create separate credentials for development, staging, and production.
Use different keys for unrelated products, tenants, or security boundaries where practical.
Assign each key to a named service owner and documented purpose.
Apply endpoint-level or capability-level restrictions whenever the provider supports them.
Give read-only workflows read-only credentials rather than relying only on agent instructions.
Keep administrative credentials out of normal runtime paths.
Separate projects and keys reduce blast radius. A development credential exposed in a test log should not grant production access, and a staging workload should not consume production spend or obscure production usage signals.
Inject keys at runtime
Application code should refer to a logical secret name, not contain the secret itself. The deployment environment can then inject the value through an environment variable or secrets manager. Access to retrieve that value should be limited to the runtime identity responsible for the tool call.
Avoid copying keys into configuration examples, support tickets, issue trackers, chat messages, model prompts, or test fixtures. Redacting output after logging is less reliable than preventing secrets from entering logs in the first place. Request tracing should preserve useful metadata such as tool name, endpoint, status, project, and correlation ID without storing raw authorization ers.
Plan for replacement before exposure occurs
Keys need a complete lifecycle: creation, secure distribution, use, monitoring, rotation, revocation, and deletion. OpenAI notes that full secret keys are only shown at creation, deleted keys stop working, and lost keys should be replaced with new ones. This means operators should not build recovery plans around retrieving an old secret.
A safe rotation process usually overlaps the old and new keys briefly at the backend level. Create the replacement, deploy it through secret management, verify traffic with the new credential, then revoke the old key. The application should read credentials dynamically enough that replacement does not require code changes or distribution to client devices.
If a key is suspected to be exposed, replace it immediately. Investigation and log review can continue after access has been contained. Waiting for proof of misuse extends the window in which an exposed credential remains useful.
Keep stateless integrations secret-free at the client
A stateless tool interface should not mean that every caller receives a permanent credential. It should mean that each request carries enough non-secret context for the trusted server to authenticate the session, authorize the operation, locate protected credentials, and execute without relying on unsafe client storage.
OpenAI’s API-key safety guidance recommends routing requests through your own backend server so the secret key remains protected. This backend proxy is the central pattern for secure remote tool endpoints because it separates untrusted or semi-trusted clients from service credentials.
A practical request path
The user interacts with an agent through an authenticated application session.
The orchestration control plane selects a specialist agent and proposes a tool call.
The backend validates the session, tenant, workflow policy, and requested operation.
The backend resolves either the user’s OAuth connection or the workload’s API key from protected storage.
The proxy constructs the outbound request using an allowlisted destination and server-controlled ers.
The remote endpoint processes the request under the constrained credential.
The proxy filters the response, records security-relevant metadata, and returns only the required result to the agent.
The browser never receives the remote service API key or OAuth Client Secret. It also does not get to choose an arbitrary outbound host, replace authorization ers, or access another user’s token. Those controls remain inside the trusted execution boundary.
Keep authorization decisions deterministic
The model can recommend a tool and generate structured arguments, but the backend should make final authorization decisions using deterministic policy. Confirm that the tool is enabled for the workspace, the caller may use it, the operation is allowed, required approval has been obtained, and the target resource is within scope.
This separation is especially important for high-impact operations. Sending a message, changing a financial record, exporting data, or deleting content may require stronger checks than reading public metadata. The policy layer should be able to reject a syntactically valid tool call that violates operational rules.
Control outbound requests
A generic proxy can become a server-side request forgery path if the model or client can supply arbitrary URLs. Register remote tool endpoints in advance, enforce HTTPS, allowlist destinations, and keep host selection outside model-controlled fields. Redirect behavior should be constrained so an approved endpoint cannot silently send credentials to an unapproved host.
Limit request size, response size, execution time, and concurrency according to the tool’s purpose. These controls protect availability and reduce the impact of accidental loops in multi-agent workflows. Idempotency controls are also valuable for retried write operations so a network failure does not create duplicate side effects.
Minimize stored state without losing accountability
Stateless request handling can coexist with strong auditability. The proxy does not need to persist full prompts, complete payloads, or raw credentials in order to record who initiated an operation, which agent and tool were used, what policy allowed it, and whether the remote call succeeded.
Use correlation identifiers to connect orchestration events, approval records, and remote requests. Keep logs free of bearer tokens, API keys, unnecessary personal data, and sensitive tool output. Logging should support incident response without creating a second repository of secrets and regulated information.
Treat MCP servers as external data-governance boundaries
MCP-connected tools make it practical to attach specialist capabilities to an agent workspace, but connectivity does not imply equivalent governance. OpenAI notes that MCP servers used with the remote MCP server tool are third-party services, and data sent to them is subject to their retention policies.
That fact should shape tool onboarding. Before enabling an MCP endpoint, determine what data the server receives, whether it stores requests or responses, where data is processed, who operates the service, and how deletion or retention requests are handled. Authentication protects access to the endpoint; it does not decide what the endpoint does with authorized data.
Minimize the payload sent to each specialist
Context handoff is useful in multi-agent systems, but forwarding the entire conversation to every tool creates unnecessary exposure. Construct a purpose-specific payload containing only the fields required for the operation. If the tool needs an order number and status transition, it may not need the customer’s full message history.
Remove unrelated conversation turns before the tool call.
Exclude hidden system instructions and credentials from tool arguments.
Use stable resource identifiers instead of copying complete records where possible.
Redact sensitive fields that the remote operation does not require.
Constrain tool responses before placing them back into shared agent context.
Response minimization matters too. A remote search tool may return broad records even when the workflow needs one field. The proxy can select or transform the result before other agents receive it, reducing lateral data spread across the orchestration workspace.
Apply a repeatable onboarding review
Review the server’s operator, endpoint ownership, authentication support, permission model, retention terms, incident process, and availability expectations. Verify that the published endpoint matches the configured destination and that changes require controlled approval.
Classify the data likely to cross the boundary. A tool handling public documentation has a different risk profile from one processing employee records, source code, customer communications, or financial data. The classification should affect allowed scopes, approval requirements, logging, and whether the endpoint is permitted at all.
Ownership must remain clear after launch. Assign an internal service owner who can disable the connection, rotate credentials, evaluate provider changes, and answer audit questions. A remote MCP server without an accountable owner is difficult to govern even if its initial configuration is sound.
Build layered controls around every credential
No authentication choice eliminates the need for defense in depth. OpenAI’s security materials describe layered architecture, network segmentation, workload isolation, encryption, and Zero Trust principles. For remote tool integrations, these concepts translate into multiple independent checks between the user, agent, orchestration layer, secret store, proxy, and endpoint.
Zero Trust does not mean distrusting every tool indiscriminately. It means avoiding implicit trust based only on network location or prior connection. Each request should be authenticated, authorized for its current context, and limited to the resources it needs.
Layer controls by failure mode
Identity controls:
Authenticate users and workloads through managed identities rather than model-provided claims.
Authorization controls:
Enforce tenant, role, tool, operation, and resource restrictions before execution.
Credential controls:
Store secrets centrally, restrict retrieval, rotate them, and separate ordinary, privileged, and administrative credentials.
Network controls:
Restrict outbound destinations and isolate workloads that handle sensitive tools.
Data controls:
Minimize payloads, encrypt transport, and avoid unnecessary retention.
Execution controls:
Apply timeouts, rate limits, concurrency limits, and approval gates for consequential actions.
Detection controls:
Monitor authentication failures, unusual usage, denied operations, unexpected destinations, and changes in spending or request volume.
Recovery controls:
Maintain a tested path to revoke keys, disconnect OAuth grants, disable tools, and restore service with replacement credentials.
These layers address different failures. A scoped key limits damage if a secret is exposed. Network allowlisting limits where the runtime can send it. Monitoring helps detect unusual use. Rapid revocation shortens the incident. None of these controls should be expected to carry the entire security model alone.
Monitor behavior, not secret values
Useful telemetry includes credential identifier, project, environment, tool name, operation category, response code, latency, caller, and correlation ID. Do not log the credential itself. Where supported, use usage visibility and spend controls to establish operational boundaries and identify activity that does not match the expected workload.
Project-based isolation makes monitoring more actionable because one environment or workflow cannot hide inside a large pool of shared traffic. Distinct development, staging, and production projects also help operators distinguish testing errors from production incidents.
Alerting should focus on conditions that warrant action: repeated authorization failures, calls from an unexpected workload, access to disabled endpoints, unusual administrative activity, sudden changes in tool volume, or use of a credential believed to be retired. The goal is not to collect maximum telemetry; it is to produce evidence that supports timely containment and investigation.
Operationalize secure endpoint onboarding and rotation
Security is most reliable when it is part of the normal integration workflow rather than a final review. A standard onboarding path gives platform engineers, agent builders, product owners, and operations teams a shared definition of ready.
Before connecting the endpoint
Define the business action.
Describe exactly what the tool reads or changes and which agent workflows may call it.
Identify the acting principal.
Decide whether each operation uses user-delegated OAuth, a server-to-server API key, or a separately controlled administrative identity.
Classify data.
Record the information sent to and returned by the remote service, including any regulated or confidential fields.
Review the provider boundary.
For third-party and MCP services, assess retention policies, endpoint ownership, and operational responsibilities.
Choose minimum permissions.
Select narrow OAuth scopes or restricted API-key permissions and avoid administrative access in ordinary workflows.
Register the endpoint.
Pin the approved destination and prevent model-generated URLs from bypassing the registry.
Set environment boundaries.
Create separate projects and distinct keys for development, staging, and production.
Assign owners.
Name the service owner, security contact, and team responsible for credential rotation.
During implementation and testing
Use synthetic or appropriately protected test data. Verify that secrets appear only in approved backend components, not in browser traffic, agent context, traces, error messages, or repository history. Test denied operations as carefully as successful ones.
Attempt calls with insufficient scopes, the wrong tenant, an expired or revoked OAuth connection, a deleted API key, and an unapproved endpoint. Confirm that failures are safe, understandable, and observable. A secure design should fail closed rather than silently falling back to a broader credential.
Test retries and partial failures for write operations. If an endpoint times out after accepting a request, the orchestration layer must avoid blindly repeating a consequential action. Use remote operation identifiers or idempotency mechanisms where the endpoint supports them, and route ambiguous outcomes for verification.
After deployment
Review project usage, rate limits, spend controls, and authorization failures.
Verify that disabled users and disconnected accounts can no longer call user-specific tools.
Rotate credentials according to organizational policy and immediately after suspected exposure.
Remove keys for retired agents, environments, and integrations.
Reassess scopes when tool capabilities or workflows change.
Review third-party retention and security terms when the provider changes its service.
Exercise the emergency disable path so operators know it works before an incident.
Credential inventory is essential to this process. Each record should identify the credential type, provider, project, environment, owner, intended endpoint, permissions, storage location, and current status. Do not store the secret value in the inventory; store enough metadata to manage it.
Respond to suspected credential exposure
Containment should be immediate and procedural. Disable or delete the affected key, revoke the OAuth grant where appropriate, block the related endpoint if needed, and issue a replacement through the approved secret-distribution path. OpenAI’s guidance that deleted keys stop working and lost keys should be replaced supports this replace-first approach.
Then determine where the credential appeared and what authority it carried. Review relevant usage, tool calls, projects, resources, and administrative actions. Remove the underlying exposure path, such as a client-side bundle, repository commit, verbose exception, or improperly protected deployment variable, before restoring normal access.
Finally, verify that the replacement credential is narrower if the incident revealed unnecessary privilege. Rotation restores secrecy; permission reduction improves the design.
A practical secure remote tool endpoint checklist
The following checklist can be used during architecture review or release approval. It is intentionally focused on controls that teams can verify rather than broad assurances.
The acting identity is explicitly classified as user, workload, project, or administrator.
OAuth is used for user-specific access and requests only the scopes needed by the workflow.
API keys are used for server-to-server access and are not shared as personal or team-wide secrets.
Administrative credentials are separated from ordinary runtime credentials.
No API key, Client Secret, access token, or refresh token is shipped to a browser or mobile client.
Secrets are not embedded in source code, committed to repositories, copied into prompts, or written to logs.
A trusted backend proxy resolves credentials and constructs outbound authorization ers.
Remote destinations are registered and allowlisted rather than supplied freely by the model.
Restricted or read-only permissions are used where available.
Development, staging, and production use separate projects and distinct credentials.
Project-level usage, rate, and spend controls are configured for the workload.
Tool calls are authorized deterministically against user, tenant, role, operation, and resource policy.
Sensitive or consequential actions have appropriate confirmation or approval controls.
Payloads contain only the context required by the remote tool.
MCP and other third-party retention policies have been reviewed by an accountable owner.
Logs preserve attribution and correlation without recording raw secrets or unnecessary sensitive data.
Keys and grants can be revoked without changing client code.
Replacement credentials can be deployed promptly through secret management.
Expired, deleted, or revoked credentials fail closed.
The team has tested endpoint disablement and credential-rotation procedures.
Several anti-patterns deserve special attention. One shared production key across many agents makes attribution and containment difficult. A browser calling a remote service directly with an embedded key turns every user into a potential secret recipient. Giving an agent unrestricted outbound URLs can turn a tool proxy into an exfiltration path. Treating a valid token as permission for every operation bypasses least privilege.
Another common mistake is to focus on authentication while ignoring data governance. A correctly authenticated call can still send too much information to a third-party MCP server or retain results longer than intended. Secure remote tool design must address identity, authorization, endpoint control, data minimization, retention, monitoring, and recovery as one operating model.
Securely adding remote tool endpoints is therefore less about choosing one universal authentication method and more about matching authority to purpose. Use OAuth when a tool acts for a user, scoped project API keys when a backend acts as a workload, and separately controlled admin credentials only for the management operations that require them. Keep every secret behind a trusted backend and make policy enforcement independent of model output.
The most resilient integrations combine short-lived user authorization, least-privilege scopes, restricted and replaceable service keys, environment isolation, approved endpoint routing, minimal context sharing, and observable revocation paths. This layered, stateless pattern lets an agent orchestration control plane connect specialist tools without turning convenience into uncontrolled access.