AI Personal Learning
and practical guidance
讯飞绘镜

Cloudflare Embraces Remote MCP: Pushing AI Agent Capabilities to the Wider Internet

Cloudflare 拥抱远程 MCP:将 AI Agent 能力推向更广阔的互联网-1

under construction AI Applications and Agent The circle of model context protocols (Model Context ProtocolMCP) is becoming a hot topic. Much of the discussion centers around installing and running on a local computer the MCP Server Unfolding. Recently.Cloudflare announced support for building and deploying on its platformremotely MCP server, which marks the MCP An important turning point in the application.

Cloudflare To simplify remote MCP The server is built to introduce four key capabilities:

  1. workers-oauth-provider: a OAuth Provider library, which greatly simplifies the authorization process necessary for remote services.
  2. McpAgent: integrated in Cloudflare Agents SDK A class in the MCP The teleportation details of the
  3. mcp-remote: an adapter utility that lets local connection-only supported MCP The client can also communicate with the remote MCP Server Interaction.
  4. AI playground from a distance MCP client (computing): an online chat interface to directly connect and test remote MCP server with built-in authentication checks.

Developers can use the Cloudflare The sample code and deploy button provided, in no time at all, puts a MCP The server is deployed to the production environment.


https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-server

 

In contrast to the previously prevalent use of local MCP servers are different, the remote MCP The server is publicly accessible. Users simply log in and grant permissions through a familiar authorization process, theMCP Clients (e.g. AI Agent) will be able to access the required tools. This is considered a huge step forward. Over the past few months, it has been a challenge to bring coding Agent Connect to local MCP servers have given developers an initial taste of their potential, and remote MCP In turn, it is expected to extend a similar working model to a wider group of users, including more everyday consumer-grade application scenarios. This is not just a difference in technical implementation, but could herald AI Agent A fundamental shift in the application paradigm.

 

From Local to Remote: A Critical Step for MCP to Reach the Masses

MCP is rapidly becoming a generalized protocol that allows large language models (LLMThe ability to go beyond simple reasoning (inference) and retrieval enhancement generation (RAG) that can perform operations that require access to external resources (e.g., sending emails, deploying code, posting blogs, etc.). It makes it possible to AI Agent (MCP Client) can be accessed through an external service (MCP server) to interact with the tools and resources provided by the server.

However, to date, theMCP applications are mostly limited to running locally. If you want the AI Agent pass (a bill or inspection etc) MCP To access a tool on the web, developers usually need to set up a local server on their own machine. This means that it is not possible to use a web interface or mobile application from the MCP, also lacks mechanisms to allow ordinary users to authenticate and authorize themselves.MCP The server is not really "online".

Cloudflare 拥抱远程 MCP:将 AI Agent 能力推向更广阔的互联网-3

off-site MCP Connected support changes this. It creates opportunities to reach a wider range of Internet users who are less likely to go to a local installation and run desktop apps just to use the MCP Server. Remote MCP support, as if moving from desktop software to Web Transition of software. Users expect to work continuously across devices and have everything work when they log in. Local MCP It's convenient for developers, but it's the remote connection that makes the MCP The critical missing link for services to reach all Internet users. Of course, remote connections also need to take into account the possible impact of network latency, which is different from local stdio Communication is different.

Cloudflare 拥抱远程 MCP:将 AI Agent 能力推向更广阔的互联网-4

 

Making authentication and authorization work "out of the box" in MCP

commander-in-chief (military) MCP Pushing from local to remote is more than just changing the transport layer (from the stdio to flowable HTTP). When building a remote that requires access to user account information MCP server, the authentication (authentication) and authorizations (e.g.authorization) became critical. There needs to be a way for users to log in and prove their identity, and there needs to be a way for users to control AI Agent What can be accessed when using the service.

MCP The specification uses the OAuth 2.0 to solve this problem.OAuth is a standard protocol that allows users to authorize applications to access their information or services without sharing passwords. In the MCP Scenario.MCP The server itself plays OAuth Provider The role of the However, complete self-realization conforms to the MCP formal OAuth The process is quite complex and error prone.Cloudflare The programs offered are designed to address this pain point.

workers-oauth-provider: Customized OAuth 2.1 Provider Library for Cloudflare Workers

When the developer is in the Cloudflare deploy on top of MCP server when its Worker It is possible to utilize workers-oauth-provider This new TypeScript The library to act as a OAuth Provider. The library encapsulates the Worker code for the API Endpoints (including but not limited to) MCP server endpoints) adds an authorization layer.

MCP The server receives the authenticated user's information directly as a parameter and does not need to perform token validation or management on its own. At the same time, the developer still has full control over how the user is authenticated: from the login screen (UI) to what identity provider to choose (e.g. GoogleGitHub (or build your own system).

complete MCP OAuth The process is as follows:

Cloudflare 拥抱远程 MCP:将 AI Agent 能力推向更广阔的互联网-5

In this process, theMCP The server is both an upstream service (e.g. GitHubGoogle(used for emphasis) OAuth Clients, in turn, are oriented to MCP Clients (e.g. AI Agent(used for emphasis) OAuth Server (Provider). Developers can use any upstream authentication process, and the workers-oauth-provider assure MCP Server Compliance MCP Specification of authorization requirements to work with a variety of client applications and websites. This includes support for dynamic client registration (RFC 7591) and authorization server metadata (RFC 8414). Using this library significantly reduces development complexity and improves security and compliance compared to self-implementation.

Simple, pluggable OAuth interface

utilization Cloudflare Workers construct (sth abstract) MCP When the server is used, the developer only needs to provide the OAuth Provider Examples of related paths (authorizations, tokens, client registration endpoints), as well as the MCP Processor for server and authentication logic (handler):

import OAuthProvider from "@cloudflare/workers-oauth-provider";
import MyMCPServer from "./my-mcp-server";
import MyAuthHandler from "./auth-handler";
export default new OAuthProvider({
apiRoute: "/sse", // MCP 客户端连接服务器的路由
apiHandler: MyMCPServer.mount('/sse'), // MCP 服务器实现
defaultHandler: MyAuthHandler, // 认证实现
authorizeEndpoint: "/authorize",
tokenEndpoint: "/token",
clientRegistrationEndpoint: "/register",
});

This abstraction makes it easy to insert custom authentication logic. For example, a program that uses the GitHub as an identity provider MCP servers, which can be used by implementing the /callback cap (a poem) /authorize routing and integration in less than 100 lines of code.

Why do MCP servers issue their own Token?

In the authorization diagram above and MCP The authorization portion of the specification, notably MCP The server will send a message to the MCP The client issues its own Tokeninstead of directly passing the upstream service from which the TokenThe

Specifically.Worker The access token obtained from upstream (access token) Encrypted storage (e.g., using Workers KV), and then generate and issue a new, stand-alone Token for the benefit of MCP Client.workers-oauth-provider The library handles this process automatically, and the developer's code does not need to directly touch the upstream token in plaintext or manage the storage itself, thus avoiding potential security risks.

// 调用 completeAuthorization 时传入的 accessToken 会被加密存储,绝不会暴露给 MCP 客户端
// 一个新的、独立的 token 会在 /token 端点生成并提供给客户端
const { redirectTo } = await c.env.OAUTH_PROVIDER.completeAuthorization({
request: oauthReqInfo,
userId: login,
metadata: { label: name },
scope: oauthReqInfo.scope,
props: {
accessToken,  // 加密存储,不发送给 MCP 客户端
},
})
return Response.redirect(redirectTo)

On the surface, this indirect approach seems more complex. Why is it so designed?

By issuing its own Token(math.) genusMCP Servers can enforce finer-grained access control than upstream providers. Even when issued to MCP client-side Token compromised, and the attacker gains access to just that MCP Limited privileges explicitly granted by the server (via its provided tools), rather than full access to the upstream service.

For example, suppose a MCP Server requests user authorization to read Gmail Mail permissions (using gmail.readonly scope). However, the server exposes the tool The functionality is narrower, allowing only the reading of a specific sender's travel booking notification to answer questions such as "What time is my hotel checkout tomorrow?" and so on. Developers can add the MCP This constraint is enforced in the server. If issued to the MCP client-side Token Stolen, as the Token Corresponds to MCP server instead of the original upstream provider (Google), the attacker can't use it to read arbitrary emails, but can only call the MCP specific tools provided by the server.OWASP To replace the term "over-agent" (Excessive Agency) is listed as a constructed AI One of the main risks of applying By issuing its own Token and enforcing restraints.MCP The server can restrict access to the tool to provide only the functionality required by the client, following the principle of least privilege.

Another example, based on the aforementioned GitHub authentication, you can force only certain users to access a tool. In the following example, only whitelisted users (geelen) in order to see and call the generateImage tool, which uses the Workers AI Follow the prompts to generate an image:

import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const USER_ALLOWLIST = new Set(["geelen"]); // 使用 Set 提高查找效率
export class MyMCP extends McpAgent<Props, Env> {
server = new McpServer({
name: "Github OAuth Proxy Demo",
version: "1.0.0",
});
async init() {
// 根据用户身份动态添加工具
if (USER_ALLOWLIST.has(this.props.login)) {
this.server.tool(
'generateImage',
'使用 flux-1-schnell 模型生成图像。',
{
prompt: z.string().describe('你想要生成的图像的文本描述。')
},
async ({ prompt }) => {
const response = await this.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {
prompt,
steps: 8
});
// 检查 response.image 是否存在
if (!response.image) {
throw new Error("图像生成失败,未返回图像数据。");
}
return {
content: [{ type: 'image', data: response.image, mimeType: 'image/jpeg' }],
}
}
)
}
}
}

 

Introduction of McpAgent: Compatible with current and future teleportation

commander-in-chief (military) MCP The next step in bringing out the local machine is to open up the remote transport layer. The locally running MCP Servers are usually configured with standard inputs and outputs (stdio) to communicate, but let the MCP servers can be invoked over the Internet, it is necessary to implement a teleportation protocol, which is currently in the draft specification based on the HTTP (used form a nominal expression) Server-Sent Events (SSE)The

Cloudflare in its Agents SDK void void McpAgent class handles the complexity of remote transfers. It does this in the background using the Durable Objects to maintain a persistent connection, making the MCP The client can pass the SSE toward MCP The server sends the message. The developer does not need to write the underlying code that handles transmission or serialization. A minimalist MCP The server can be implemented with just a dozen lines of code:

import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
export class MyMCP extends McpAgent {
server = new McpServer({
name: "Demo",
version: "1.0.0",
});
async init() {
this.server.tool("add", "计算两个数字的和", { a: z.number(), b: z.number() }, async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
}));
}
}

It is worth noting that after community discussionsMCP The teleportation in the specification is being revised with plans to use streamable HTTP (Streamable HTTP) replaces the current HTTP+SSE Program. This will allow for the integration with the MCP The server establishes stateless, pure HTTP connection and optionally upgrade to SSEThe client can send messages to different endpoints, while eliminating the complexity of having to send messages to different endpoints.Cloudflare indicate McpAgent Classes will evolve with specification updates to support new Streamable HTTP standards, ensuring that developers don't have to rewrite code to adapt to changes in transmission methods.

This consideration of future transmission protocol evolution is equally important. Currently, the vast majority of MCP Server Main Exposure toolsThey are essentially simple remote procedure calls (RPC), which can be provided by stateless transmission. But the more complex "man-in-the-loop" (human-in-the-loop) and Agent Interaction scenarios that will require prompts cap (a poem) sampling et al. (and other authors) MCP Conceptual support. These scenarios requiring bidirectional, real-time communication are difficult to realize efficiently without a bidirectional transport layer. By then, theCloudflare Platform,Agents SDK cap (a poem) Durable Objects All natively supported WebSocketsThe ability to provide full-duplex, bi-directional, real-time communication capabilities provides the opportunity for future, more advanced MCP The application lays the foundation.

 

Stateful MCP server with Agent features

exist Cloudflare superstructure MCP When the server, each MCP Client sessions are all controlled by a Durable Object Support (via Agents SDK). This means that each session can manage and persist its own state, and can even have its own SQL Database.

This sets the stage for building stateful MCP The server opens the door.MCP Servers are no longer just a place for client applications and external API stateless transition layers between them, which can themselves be stateful applications - such as games, checkout processes with shopping carts, persistent knowledge graphs, and so on. In the Cloudflare Up.MCP The potential of servers goes far beyond serving as REST API of the front end.

A simple counter example is used to understand the basic principles of its operation:

import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
type State = { counter: number }
export class MyMCP extends McpAgent<Env, State, {}> {
server = new McpServer({
name: "Demo",
version: "1.0.0",
});
// 定义初始状态
initialState: State = {
counter: 1,
}
async init() {
// 定义一个资源,用于读取计数器当前值
this.server.resource(`counter`, `mcp://resource/counter`, (uri) => {
return {
contents: [{ uri: uri.href, text: String(this.state.counter) }],
}
})
// 定义一个工具,用于增加计数器的值
this.server.tool('add', '增加存储在 MCP 服务器中的计数器的值', { a: z.number() }, async ({ a }) => {
// 更新状态
this.setState({ ...this.state, counter: this.state.counter + a });
return {
content: [{ type: 'text', text: `增加了 ${a}, 当前总数是 ${this.state.counter}` }],
}
})
}
// 状态更新时的回调(可选)
onStateUpdate(state: State) {
console.log({ stateUpdate: state });
}
}

For a given session, the above MCP The server will take a number of tool Remember the state of the counter between calls.

exist MCP Inside the server, developers can utilize the Cloudflare Complete developer platform capabilities, such as enabling MCP The server launches the browser for web browsing, triggering WorkflowCall AI models, etc. This presupposes that the MCP The ecosystem will evolve to more advanced and intelligent use cases.

 

Connecting an Existing MCP Client to a Remote Server

Cloudflare Early support for remote MCPEven in the mainstream MCP Client applications generally support remote, authenticated MCP Before. This provides developers with the opportunity to be one step ahead.

But this also poses a real challenge: if there is not yet support for remote MCP clients, how developers can test and get users to use the remotes they've built MCP Servers?

Cloudflare Two new tools are provided to respond:

  1. Workers AI Playground update: This online chat interface is now a fully functional remote MCP Client that supports connecting to any remote MCP server with a built-in authentication process. The developer simply enters the remote server's URL(e.g. https://remote-server.example.com/sse) and click connect to test it immediately without any local software installation.

    Cloudflare 拥抱远程 MCP:将 AI Agent 能力推向更广阔的互联网-6

    After clicking Connect, the user will go through the authentication process (if set up), after which they will be able to chat directly with the MCP Server tool interactions.

  2. mcp-remote adapter (device): For those who already support MCP Clients that have not yet handled remote connections and authentication (such as the Claude Desktop maybe Cursor), you can use the mcp-remote. It's a npm package that acts as a bridge between local clients and remote servers. It allows developers and users to preview the interface with the remote server in their familiar tools. MCP server interaction experience without waiting for the client itself to update its support.

    Cloudflare Provides information on how to incorporate mcp-remote together with Claude DesktopCursorWindsurf epidemic MCP Guidelines for using the client in conjunction with the client. For example Claude Desktop in the configuration file, simply add a configuration similar to the following:

    {
    "mcpServers": {
    "remote-example": {
    "command": "npx",
    "args": [
    "mcp-remote",
    "https://remote-server.example.com/sse" // 替换为你的远程服务器 URL
    ]
    }
    }
    }
    

 

Remote MCP's are coming of age

Remote Model Context Protocol (Remote MCP) is undoubtedly AI Agent field is an important development direction. When client applications widely support remote MCP server when its user base will expand from developers to a much wider group of people - who may never even have heard of the MCP The term.

For service providers, building remote MCP A server is a server that integrates its own services to the millions of users using the AI The critical path in assistants and tools. Many large Internet companies are reported to have been actively building MCP servers, and at the same time, it makes you look forward to those who are known for their Agent-first,MCP-native way to the birth of an emerging business.

on the basis of Cloudflare provides tools and platforms that developers can use now to start building future-proof remote MCP Applications. This is not only an upgrade of the tech stack, it is an upgrade of the AI Agent An important exploration of how to integrate Internet services. As the ecosystem matures, remote MCP promises to spawn smarter and more personalized user experiences. Developers can check out the Cloudflare Developer Documentation Get more information and start practicing.

May not be reproduced without permission:Chief AI Sharing Circle " Cloudflare Embraces Remote MCP: Pushing AI Agent Capabilities to the Wider Internet
en_USEnglish