Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

MCP Agent OAuth Authorization and Remote Server Deployment

Connect Agents to MCP servers with OAuth, deploy protected remote MCP servers on Workers, and verify client and server authorization flows.

This page summarizes Cloudflare Agents documentation on the Model Context Protocol (MCP): how an Agent acts as an MCP client, how you publish a remote MCP server with OAuth authorization, and where Perplexity Agent API fits when you call MCP from a hosted model instead of your own Worker.

Model Context Protocol (MCP) ↗︎ is an open standard that connects AI systems with external applications. Think of MCP like a USB-C port for AI applications.

— Cloudflare, Model Context Protocol (MCP)

MCP terminology: agent client, remote server, and OAuth

Section titled “MCP terminology: agent client, remote server, and OAuth”

MCP gives agents a standard way to discover and call tools on external systems. In Cloudflare’s vocabulary, an Agent embeds an MCP client; the program you deploy that exposes tools is an MCP server.

Role What it does Typical transport
Agent / MCP client Connects to servers, runs OAuth, passes tools to the model Streamable HTTP (or RPC to a bound server)
Remote MCP server Exposes tools at an HTTPS /mcp endpoint Streamable HTTP
Authorization server Signs users in and issues access tokens OAuth 2.1 subset used by MCP

The MCP standard supports two modes of operation: Remote MCP connections: MCP clients connect to MCP servers over the Internet, establishing a connection using Streamable HTTP, and authorizing the MCP client access to resources on the user’s account using OAuth.

— Cloudflare, Model Context Protocol (MCP)

Remote connections are what most production setups target; local stdio MCP is out of scope here unless you already run tools on the same machine.

Agent MCP client: addMcpServer and tool discovery

Section titled “Agent MCP client: addMcpServer and tool discovery”

If you build on Cloudflare Agents, the Agent class includes a multi-server MCP client. You connect in onStart() or from an HTTP handler, then pass discovered tools into model calls (for example via this.mcp.getAITools()).

Agent includes a multi-server MCP client. This enables your Agent to interact with external services that expose MCP interfaces.

— Cloudflare, Agent class internals

How to connect an Agent to an MCP server URL

Section titled “How to connect an Agent to an MCP server URL”

Call addMcpServer() with a display name and the server’s MCP endpoint URL. For servers that do not use OAuth, the connection can reach ready immediately; tools are persisted in the agent’s SQL storage across requests.

Connections persist in the agent’s SQL storage, and when an agent connects to an MCP server, all tools from that server become available automatically.

— Cloudflare, MCP Client

Use getMcpServers() to inspect connection state, listed tools, and errors; use this.mcp.getAITools() when integrating with the AI SDK, and this.mcp.listTools() for raw catalog inspection.

addMcpServer return state Meaning Your next step
ready Connected; tools discovered Call the model with getAITools()
authenticating OAuth required Send the user to authUrl

For internal servers you can skip public HTTP and bind a Durable Object MCP implementation via RPC (see Agent class internals). For bearer tokens or Cloudflare Access, pass transport.headers as described in MCP Client and MCP.

OAuth for MCP clients: authUrl, callbacks, and custom providers

Section titled “OAuth for MCP clients: authUrl, callbacks, and custom providers”

Many remote servers (for example Cloudflare API MCP server) require OAuth before tools run. The client flow is: connect → receive authenticating and authUrl → user approves → callback → token stored → ready.

When connecting to OAuth-protected MCP servers (like Slack or Notion), your users need to authenticate before your Agent can access their data.

— Cloudflare, Handle OAuth with MCP servers

MCP client OAuth flow: redirect, popup, or status polling

Section titled “MCP client OAuth flow: redirect, popup, or status polling”

The high-level sequence matches what operators describe as “connect MCP then sign in”:

  1. Call addMcpServer(name, url) (optionally set callbackHost for custom domains).
  2. If the result includes authUrl, present it (redirect, popup, or link).
  3. The provider redirects to the Agent callback; the built-in DurableObjectOAuthClientProvider validates state and stores tokens.
  4. Connection state moves through authenticating → connecting → ready (or failed with server.error).

Configure completion behavior with this.mcp.configureOAuthCallback() in onStart()—for example successRedirect, errorRedirect, or a customHandler that closes a popup (Handle OAuth with MCP servers). Browser apps can use useAgent with onMcpUpdate instead of polling (Client SDK).

Agents SDK v0.4.0 adds createMcpOAuthProvider() so you can override default dynamic client registration—for example pre-registered client credentials or mTLS (changelog).

Remote MCP server: deploy without auth, then add OAuth

Section titled “Remote MCP server: deploy without auth, then add OAuth”

To host an MCP server, Cloudflare’s path starts with a public Streamable HTTP server, then layers OAuth when you need per-user access.

This guide shows how to deploy a remote MCP server on Cloudflare using Streamable HTTP transport. You have two options: Without authentication — anyone can connect and use the server (no login required). With authentication and authorization — users sign in before accessing tools, and you can control which tools an agent can call based on the user’s permissions.

— Cloudflare, Build a Remote MCP server

Create a template with npm create cloudflare@latest, run npm start, and test with MCP Inspector (npx @modelcontextprotocol/inspector)—the /mcp URL is for MCP protocol messages, not ordinary browser navigation (Build a Remote MCP server). Deploy with npx wrangler deploy, then register the HTTPS /mcp URL in clients such as Claude Code (claude mcp add --transport http …).

Implement tools with createMcpHandler and McpServer.registerTool (MCP Server, Tool results).

MCP server OAuth: authorization server and resource server split

Section titled “MCP server OAuth: authorization server and resource server split”

MCP authorization separates authentication (who signed in) from authorization (what the client may do). Cloudflare documents this with @cloudflare/workers-oauth-provider v1: one Worker as authorization server, another as resource server (your MCP handler).

When building a Model Context Protocol (MCP) server, you need both a way to allow users to login (authentication) and allow them to grant the MCP client access to resources on their account (authorization). The Model Context Protocol uses a subset of OAuth 2.1 for authorization.

— Cloudflare, Authorization

One Worker acts as the authorization server: it signs users in and issues tokens. Your MCP server acts as the resource server, and can run in another Worker. It validates each token with the authorization server over a Service Binding, without crossing the public Internet.

— Cloudflare, Workers OAuth Provider v1 changelog

Section titled “Authorization server Worker: consent and completeAuthorization”

Install @cloudflare/workers-oauth-provider, bind OAUTH_KV, set global_fetch_strictly_public when using Client ID Metadata Documents, and implement /authorize with parseAuthRequest and completeAuthorization. Props passed to completeAuthorization() are encrypted and delivered to the MCP server on each request (Authorization).

Resource server Worker: OAuthResourceServer and createMcpHandler

Section titled “Resource server Worker: OAuthResourceServer and createMcpHandler”

Wrap your MCP handler in OAuthResourceServer. It publishes protected resource metadata, returns 401 without a token so clients discover the authorization server, and rejects tokens minted for a different resource URL.

MCP_SERVER_URL must be exactly the URL clients connect to, because every token is bound to it.

— Cloudflare, Authorization

Deploy the authorization server first, then the MCP server with a Service Binding to AUTH_SERVER.validateToken—the MCP Worker does not need its own KV for token checks (Authorization).

Clients without a token follow the 401 challenge, complete /authorize and /oauth/token, then retry with an access token (Authorization).

Third-party identity (Stytch, Auth0, Descope)

Section titled “Third-party identity (Stytch, Auth0, Descope)”

Cloudflare links example flows that delegate login to Stytch, Auth0, or Descope while still using Workers OAuth Provider for MCP-facing tokens (Authorization). For Descope, if you enable Dynamic Client Registration on an MCP Server resource, configure a human approval step—otherwise any client can self-register (Authorization).

Scopes, tool permissions, and securing the MCP endpoint

Section titled “Scopes, tool permissions, and securing the MCP endpoint”

requiredScopes on OAuthResourceServer is advertised, not enforced. Check ctx.auth.scope in the handler and return insufficientScope() so the client can prompt for step-up scopes (Authorization, Securing MCP servers).

Inside tools, read identity via getMcpAuthContext()?.props (from completeAuthorization()). You can deny inside a tool handler (model sees the error) or register tools only for allowed users (model never sees forbidden tools) (Authorization).

Props often hold upstream access tokens. Do not log or return them.

— Cloudflare, Authorization

On the authorization server, render a real consent page: describeConsent, beginConsent, and approveConsent so users see client name, scopes, and redirect host before tokens issue (Securing MCP servers). When upstream login uses GitHub or Google, call beginUpstream / finishUpstream so one provider session cannot authorize arbitrary MCP clients (Securing MCP servers).

For Code Mode servers, enforce authorization in host callbacks before side effects; do not put secrets in OpenAPI documents exposed to model-written code (Build a Code Mode MCP server).

Perplexity Agent API: mcp tool vs Project connectors

Section titled “Perplexity Agent API: mcp tool vs Project connectors”

If the model runs on Perplexity Agent API rather than your Agent Worker, you attach remote MCP with type: "mcp" and server_url (Streamable HTTP only; legacy SSE is not supported).

Connect a remote MCP server to an Agent API request and optionally approve tool calls before they run.

— Perplexity, MCP

Approach Setup Credentials
Connector (type: "connector") Register once in the Project; reference id Stored per Project; your app sends connector ID
MCP (type: "mcp") server_url on each request Your app passes authorization or headers per request

Both connectors and MCP servers let the Agent API call external tools. Use a managed or custom connector to reuse a connection configured for your Project. Use MCP to provide a remote server’s URL and authentication in each request.

— Perplexity, Connectors

Agent API discovers tools at request start (mcp_list_tools in the response). Connector OAuth flows are not supported on the raw mcp tool—bring your own server and pass tokens (MCP). For a custom data server, Perplexity’s cookbook uses API key auth on /mcp and Streamable HTTP (Build a Data Analytics Agent).

  • MCP_SERVER_URL mismatch — Tokens bind to the exact URL clients use; loopback http://localhost is only for local dev (Authorization).
  • Assuming requiredScopes enforces access — Always check scopes in the resource server handler (Securing MCP servers).
  • Opening /mcp in a browser — Use MCP Inspector or an MCP client (Build a Remote MCP server).
  • Ignoring failed OAuth state — failed connections stay until removeMcpServer(); surface server.error and allow retry (Handle OAuth with MCP servers).
  • Leaking tokens through tools — Treat props as sensitive (Authorization).
  1. Start or deploy your MCP server and note the full /mcp URL. For a quick public server, follow Build a Remote MCP server; for OAuth, deploy the auth Worker before the resource Worker (Authorization).
  2. Run npx @modelcontextprotocol/inspector and connect to your endpoint. If auth is required, use Quick OAuth Flow in Auth settings, then List tools (Test a Remote MCP Server).
  3. For an Agent client, POST to your add-mcp route or call addMcpServer locally; confirm authenticating returns authUrl when needed and GET mcp-state shows ready with tools (Connect to an MCP server).
  4. Send an unauthenticated request to a protected /mcp and confirm 401 with metadata pointing at your authorization server; retry with a valid token and confirm tools execute (Authorization).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match your deployment or the linked provider docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you think is wrong so it can be corrected.