跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

构建 Code Mode MCP 服务器

最后更新 查看 MarkdownAgent 设置

Code Mode MCP 服务器让任意模型上下文协议 (MCP) 客户端都能使用模型编写的代码,而无需自行提供沙箱。服务器不再为每项操作公布一个工具,而是将代码执行作为工具接口,并在隔离的 Worker 中运行生成的 JavaScript。生成的代码可以组合多项操作并只返回最终结果,因此工具定义和中间数据不会进入模型上下文。有关设计理由,请参阅 Code Mode:用 1,000 个 token 为智能体提供完整 API ↗。

选择模式

模式 MCP 工具 面向模型的 API 适用场景
单代码工具 code 每个上游工具的带类型方法 已有 MCP 服务器且工具数量可控。
搜索并执行 search, execute OpenAPI 文档与请求函数 拥有大型 API,完整 schema 应保持在上下文之外。

当现有 MCP 服务器已定义模型所需的操作与 schema 时,使用 codeMcpServer()。当大型 OpenAPI 目录需要渐进发现且模型上下文占用固定时,使用 openApiMcpServer()。

这两个函数目前都会返回 SDK v1 服务器。请按封装现有 MCP 服务器和使用搜索并执行发布大型 API中的示例,通过 createLegacyMcpHandler 提供服务。

封装现有 MCP 服务器

单工具模式使用 codeMcpServer() 包装现有 MCP 服务器。服务器不再分别通告每个上游工具,而是通告一个 code 工具。

code 工具描述包含为每个上游工具生成的 TypeScript 定义。模型针对 codemode 命名空间编写 JavaScript:

async () => {
    const projects = await codemode.list_projects({ status: "active" });
    const tasks = [];

    for (const project of projects) {
        tasks.push(...(await codemode.list_tasks({ projectId: project.id })));
    }

    return tasks.filter((task) => task.status === "blocked");
};

MCP 客户端发起一次外层工具调用。在沙箱内,代码可进行依赖的上游调用、过滤中间数据,并仅返回最终结果。

当生成的类型声明能舒适地放入 code 工具描述时,此模式效果良好。模型在加载 MCP 工具时会收到这些声明。

需要 Cloudflare Workers 项目与现有 McpServer。

  1. 安装 Code Mode 与 MCP 依赖:

    npm i @cloudflare/codemode agents @modelcontextprotocol/sdk zod
  2. 添加 Worker Loader 绑定与 nodejs_compat 兼容性标志:

    {
      "$schema": "./node_modules/wrangler/config-schema.json",
      "name": "codemode-mcp-server",
      "main": "src/server.ts",
      "upload_source_maps": true,
      // Set this to today's date
      "compatibility_date": "2026-11-20",
      "compatibility_flags": [
        "nodejs_compat"
      ],
      "worker_loaders": [
        {
          "binding": "LOADER"
        }
      ]
    }
    name = "codemode-mcp-server"
    main = "src/server.ts"
    upload_source_maps = true
    # Set this to today's date
    compatibility_date = "2026-11-20"
    compatibility_flags = ["nodejs_compat"]
    
    [[worker_loaders]]
    binding = "LOADER"
  3. 创建 upstream server 并传给 codeMcpServer():

    src/server.jsjs
    import { DynamicWorkerExecutor } from "@cloudflare/codemode";
    import { codeMcpServer } from "@cloudflare/codemode/mcp";
    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
    import { createLegacyMcpHandler } from "agents/mcp";
    import { z } from "zod";
    
    function createOrderServer() {
    	const server = new McpServer({
    		name: "orders",
    		version: "1.0.0",
    	});
    
    	server.registerTool(
    		"get_order",
    		{
    			description: "Get an order by ID",
    			inputSchema: {
    				orderId: z.string().describe("Order ID"),
    			},
    		},
    		async ({ orderId }) => ({
    			structuredContent: {
    				id: orderId,
    				status: "processing",
    			},
    			content: [
    				{
    					type: "text",
    					text: JSON.stringify({ id: orderId, status: "processing" }),
    				},
    			],
    		}),
    	);
    
    	return server;
    }
    
    export default {
    	async fetch(request, env, ctx) {
    		const upstream = createOrderServer();
    		const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
    		const server = await codeMcpServer({
    			server: upstream,
    			executor,
    		});
    
    		return createLegacyMcpHandler(server, { route: "/mcp" })(request, env, ctx);
    	},
    };
    src/server.tsts
    import { DynamicWorkerExecutor } from "@cloudflare/codemode";
    import { codeMcpServer } from "@cloudflare/codemode/mcp";
    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
    import { createLegacyMcpHandler } from "agents/mcp";
    import { z } from "zod";
    
    function createOrderServer() {
        const server = new McpServer({
            name: "orders",
            version: "1.0.0",
        });
    
        server.registerTool(
            "get_order",
            {
                description: "Get an order by ID",
                inputSchema: {
                    orderId: z.string().describe("Order ID"),
                },
            },
            async ({ orderId }) => ({
                structuredContent: {
                    id: orderId,
                    status: "processing",
                },
                content: [
                    {
                        type: "text",
                        text: JSON.stringify({ id: orderId, status: "processing" }),
                    },
                ],
            }),
        );
    
        return server;
    }
    
    export default {
        async fetch(request, env, ctx): Promise<Response> {
            const upstream = createOrderServer();
            const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
            const server = await codeMcpServer({
                server: upstream,
                executor,
            });
    
            return createLegacyMcpHandler(server, { route: "/mcp" })(
                request,
                env,
                ctx,
            );
        },
    } satisfies ExportedHandler<Env>;
  4. 部署 Worker:

    npx wrangler deploy
  5. 在 MCP client 中连接到 https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev/mcp。确认 server 暴露名为 code 的单个 tool。

模型可在 code tool 内使用生成的 codemode 命名空间:

async () => {
    const order = await codemode.get_order({ orderId: "order-123" });
    return { id: order.id, status: order.status };
};

上游工具返回 structuredContent 时,Code Mode 直接暴露该值。仅文本的内容会拼接,并在可能时解析为 JSON。上游 MCP 错误变为模型代码可捕获的异常。混合文本与二进制内容保留 MCP 结果结构。

若提供自定义 description,在生成 TypeScript 声明应出现处使用 {{types}}。在 SDK 应插入基于第一个上游 MCP 工具的示例调用处使用 {{example}}。两个占位符均为可选。

保护上游操作

codeMcpServer() 不为每个上游工具调用提供持久审批。它在外层 code 工具内从内部调用上游处理程序。

在产生副作用前于每个上游处理程序强制执行授权与任何每操作审批。不要在工具结果中包含凭证。

使用搜索并执行发布大型 API

大型 API 可能包含数千个操作。将所有操作放入一个工具描述仍会消耗大量上下文。搜索并执行模式将能力发现与已认证的 API 调用分离。

服务器暴露两个 MCP 工具:

  • search 针对 OpenAPI 文档运行生成的代码。仅返回任务所需的操作、参数或 schema。
  • execute 使用已认证的 request 函数运行生成的代码。可调用所选操作、组合响应并返回聚焦的结果。

完整的 OpenAPI 文档保留在沙箱内。只有搜索代码返回的内容才会进入模型上下文。

认证保留在宿主请求回调中。生成的代码接收 request 函数,而非凭证。

Cloudflare API MCP 服务器 使用此模式,通过 search 与 execute 暴露 Cloudflare API。有关设计理由与上下文节省,请参阅 Code Mode: give agents an entire API in 1,000 tokens ↗。

需要 Cloudflare Workers 项目、OpenAPI 3.x 文档,以及宿主侧认证 API 请求的方法。

  1. 安装 Code Mode 与 MCP 依赖:

    npm i @cloudflare/codemode agents @modelcontextprotocol/sdk zod
  2. 添加 Worker Loader 绑定与 nodejs_compat 兼容性标志:

    {
      "$schema": "./node_modules/wrangler/config-schema.json",
      "name": "openapi-codemode-mcp",
      "main": "src/server.ts",
      "upload_source_maps": true,
      // Set this to today's date
      "compatibility_date": "2026-11-20",
      "compatibility_flags": [
        "nodejs_compat"
      ],
      "worker_loaders": [
        {
          "binding": "LOADER"
        }
      ]
    }
    name = "openapi-codemode-mcp"
    main = "src/server.ts"
    upload_source_maps = true
    # Set this to today's date
    compatibility_date = "2026-11-20"
    compatibility_flags = ["nodejs_compat"]
    
    [[worker_loaders]]
    binding = "LOADER"
  3. 在 host 加载 OpenAPI 文档。用已认证的 request 函数创建 MCP 服务器:

    src/server.jsjs
    import { DynamicWorkerExecutor } from "@cloudflare/codemode";
    import { openApiMcpServer } from "@cloudflare/codemode/mcp";
    import { createLegacyMcpHandler } from "agents/mcp";
    
    const SPEC_URL = "https://api.example.com/openapi.json";
    const API_ORIGIN = "https://api.example.com";
    
    let specCache;
    
    async function loadSpec() {
    	if (specCache) return specCache;
    
    	const response = await fetch(SPEC_URL);
    	if (!response.ok) {
    		throw new Error(`OpenAPI request failed: ${response.status}`);
    	}
    
    	specCache = await response.json();
    	return specCache;
    }
    
    export default {
    	async fetch(request, env, ctx) {
    		const authorization = request.headers.get("Authorization");
    		if (!authorization?.startsWith("Bearer ")) {
    			return new Response("Bearer token required", { status: 401 });
    		}
    
    		const server = openApiMcpServer({
    			spec: await loadSpec(),
    			executor: new DynamicWorkerExecutor({ loader: env.LOADER }),
    			name: "example-api",
    			version: "1.0.0",
    			request: async (options) => {
    				if (!options.path.startsWith("/")) {
    					throw new Error("API path must start with a slash");
    				}
    
    				const url = new URL(`${API_ORIGIN}${options.path}`);
    				for (const [key, value] of Object.entries(options.query ?? {})) {
    					if (value !== undefined) {
    						url.searchParams.set(key, String(value));
    					}
    				}
    
    				const headers = { Authorization: authorization };
    				if (options.contentType) {
    					headers["Content-Type"] = options.contentType;
    				} else if (options.body !== undefined) {
    					headers["Content-Type"] = "application/json";
    				}
    
    				const response = await fetch(url, {
    					method: options.method,
    					headers,
    					body:
    						options.body === undefined
    							? undefined
    							: options.rawBody
    								? options.body
    								: JSON.stringify(options.body),
    				});
    
    				if (!response.ok) {
    					throw new Error(`API request failed: ${response.status}`);
    				}
    				if (response.status === 204) return null;
    
    				const responseType = response.headers.get("Content-Type") ?? "";
    				return responseType.includes("application/json")
    					? await response.json()
    					: await response.text();
    			},
    		});
    
    		return createLegacyMcpHandler(server, { route: "/mcp" })(request, env, ctx);
    	},
    };
    src/server.tsts
    import { DynamicWorkerExecutor } from "@cloudflare/codemode";
    import { openApiMcpServer } from "@cloudflare/codemode/mcp";
    import { createLegacyMcpHandler } from "agents/mcp";
    
    const SPEC_URL = "https://api.example.com/openapi.json";
    const API_ORIGIN = "https://api.example.com";
    
    let specCache: Record<string, unknown> | undefined;
    
    async function loadSpec(): Promise<Record<string, unknown>> {
        if (specCache) return specCache;
    
        const response = await fetch(SPEC_URL);
        if (!response.ok) {
            throw new Error(`OpenAPI request failed: ${response.status}`);
        }
    
        specCache = (await response.json()) as Record<string, unknown>;
        return specCache;
    }
    
    export default {
        async fetch(request, env, ctx): Promise<Response> {
            const authorization = request.headers.get("Authorization");
            if (!authorization?.startsWith("Bearer ")) {
                return new Response("Bearer token required", { status: 401 });
            }
    
            const server = openApiMcpServer({
                spec: await loadSpec(),
                executor: new DynamicWorkerExecutor({ loader: env.LOADER }),
                name: "example-api",
                version: "1.0.0",
                request: async (options) => {
                    if (!options.path.startsWith("/")) {
                        throw new Error("API path must start with a slash");
                    }
    
                    const url = new URL(`${API_ORIGIN}${options.path}`);
                    for (const [key, value] of Object.entries(options.query ?? {})) {
                        if (value !== undefined) {
                            url.searchParams.set(key, String(value));
                        }
                    }
    
                    const headers: Record<string, string> = { Authorization: authorization };
                    if (options.contentType) {
                        headers["Content-Type"] = options.contentType;
                    } else if (options.body !== undefined) {
                        headers["Content-Type"] = "application/json";
                    }
    
                    const response = await fetch(url, {
                        method: options.method,
                        headers,
                        body:
                            options.body === undefined
                                ? undefined
                                : options.rawBody
                                    ? (options.body as string)
                                    : JSON.stringify(options.body),
                    });
    
                    if (!response.ok) {
                        throw new Error(`API request failed: ${response.status}`);
                    }
                    if (response.status === 204) return null;
    
                    const responseType = response.headers.get("Content-Type") ?? "";
                    return responseType.includes("application/json")
                        ? await response.json()
                        : await response.text();
                },
            });
    
            return createLegacyMcpHandler(server, { route: "/mcp" })(
                request,
                env,
                ctx,
            );
        },
    } satisfies ExportedHandler<Env>;
  4. 部署 Worker:

    npx wrangler deploy
  5. 在 MCP client 中连接到 https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev/mcp。包含 Worker 所需的 bearer token。

  6. 列出 MCP tool。验证服务器暴露 search 与 execute。

搜索 OpenAPI 文档

在 execute 之前调用 search。Search 代码可检查文档而不发起 API 请求:

async () => {
    const spec = await codemode.spec();
    return Object.entries(spec.paths)
        .filter(([path]) => path.includes("/orders"))
        .map(([path, operations]) => ({
            path,
            methods: Object.keys(operations),
        }));
};

代码调用 codemode.spec() 时,本地 OpenAPI $ref 在沙箱内解析。外部引用保持未解析。

调用 API

execute tool 包含相同的 codemode.spec() 方法与 host 提供的 codemode.request() 方法:

async () => {
    const response = await codemode.request({
        method: "GET",
        path: "/orders",
        query: { status: "processing", limit: 20 },
    });

    return response.items.map(({ id, status }) => ({ id, status }));
};

Host 回调接收 method、path、可选 query、可选 body、可选 contentType 与可选 rawBody 字段。精确类型请参阅 openApiMcpServer() API。

search 和 execute 工具使用固定的示例代码片段。可选的 description 会追加到 execute 工具说明中。此函数不使用 codeMcpServer() 支持的 {{types}} 或 {{example}} 占位符。

保护 API

示例在创建 MCP 服务器前读取 bearer token。其 request 回调将该 token 加入出站请求。Token 永不进入沙箱。

openApiMcpServer() 不为 execute 内每次请求提供持久审批。在应用副作用前于宿主回调强制执行授权及任何所需的按操作审批。验证路径而非接受任意来源。

不要在 OpenAPI 文档或 API 结果中包含 secret。两者对模型编写的代码可用。

沙箱与授权边界

模型编写的代码会在隔离的 Worker 中运行。DynamicWorkerExecutor 默认会阻止直接调用 fetch() 和 connect(),因此生成的代码只能通过上游 MCP 工具或主机提供的请求回调访问外部系统。

代码执行不能替代授权。在应用副作用前,于上游工具处理程序或宿主 request 回调内强制执行权限及任何所需审批。不要通过工具结果或 OpenAPI 文档暴露凭证。

限制结果

让模型编写的代码在返回前 select、map、aggregate 或 paginate 数据。发布者将最终 MCP 响应限制在约 6,000 估计 token,截断响应标记 --- TRUNCATED ---。

截断不减少已执行的 API 工作。返回支持模型下一决策的聚焦标识符、状态字段、计数与错误。

这篇文档对您有帮助吗?