### Install and Run Development Server Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Install project dependencies and start the local development server. ```bash npm install npm run dev # Start dev server ``` -------------------------------- ### Find Information on D1 Databases Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Example of how to query the Docs Tool to find setup and configuration details for D1 databases. ```json { "query": "D1 database setup and configuration" } ``` -------------------------------- ### Install Dependencies Source: https://github.com/cloudflare/mcp/blob/main/AGENTS.md Run this command to install all project dependencies. Node.js version 22 or higher is required. ```bash npm install # Install dependencies ``` -------------------------------- ### Example: Tool Call (Success) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Example of an AnalyticsEngineDataPoint for a successful tool call. ```json { "indexes": ["tool_call"], "blobs": ["cloudflare-api", "0.1.0", "user123", "search"], "doubles": [] } ``` -------------------------------- ### Example: Auth User (Success) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Example of an AnalyticsEngineDataPoint for a successful user authentication event. ```json { "indexes": ["auth_user"], "blobs": ["cloudflare-api", "0.1.0", "user456", null], "doubles": [] } ``` -------------------------------- ### Example Output after Reference Resolution Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md The expected output after resolving the `$ref` in the input example, showing the fully resolved schema. ```json { "type": "object", "properties": { "name": { type: "string" }, "main": { type: "string" }, ... } } ``` -------------------------------- ### Development Commands Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Common commands for local development, including starting the server, type checking, linting, and running tests. ```bash npm run dev # Start local development server npm run typecheck # Type checking npm run lint # Linting npm run test # Run tests ``` -------------------------------- ### Search Cloudflare Workers Documentation Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Example of how to query the Docs Tool to find information about deploying Cloudflare Workers. ```json { "query": "How do I deploy a Cloudflare Worker?" } ``` -------------------------------- ### Example Input for Reference Resolution Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md An example of a JSON object containing a reference that needs to be resolved within an OpenAPI specification. ```json { "$ref": "#/components/schemas/CreateWorkerRequest" } ``` -------------------------------- ### Example: Tool Call (Error) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Example of an AnalyticsEngineDataPoint for a failed tool call, indicated by a negative double value. ```json { "indexes": ["tool_call"], "blobs": ["cloudflare-api", "0.1.0", "user123", "execute"], "doubles": [-1] } ``` -------------------------------- ### MCP URL Examples Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Use the `codemode` query parameter to switch between 3-tool code mode and ~2,500-tool non-code-mode. The default is code mode enabled. ```url https://mcp.cloudflare.com/mcp ``` ```url https://mcp.cloudflare.com/mcp?codemode=false ``` -------------------------------- ### Example JSON Input Schema Output Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md Illustrates the structure of a JSON schema generated by `buildJsonInputSchema`, including path parameters, query parameters, headers, and request body. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "account_id": { "type": "string", "description": "Path parameter: account_id" }, "limit": { "type": "string", "description": "Max records to return" }, "header_x_auth_token": { "type": "string", "description": "Header: X-Auth-Token — Custom auth" }, "body": { "type": "string", "description": "Request body as string" } }, "required": ["account_id"] } ``` -------------------------------- ### Example: Auth User (Failure) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Example of an AnalyticsEngineDataPoint for a failed user authentication event, showing an error reason in the blobs. ```json { "indexes": ["auth_user"], "blobs": ["cloudflare-api", "0.1.0", null, "invalid_grant: expired token"], "doubles": [] } ``` -------------------------------- ### Look Up Cloudflare Access Policies Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Example of how to query the Docs Tool to find information regarding Cloudflare Access policy rules. ```json { "query": "Cloudflare Access policy rules" } ``` -------------------------------- ### Example Zod Schema Output Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md Shows an example of the Zod schema object returned by `buildInputSchema`, detailing how parameters and request bodies are represented with Zod types. ```typescript { account_id: z.string().describe("..."), limit: z.string().optional().describe("..."), body: z.string().optional().describe("..."), ... } ``` -------------------------------- ### Instantiate and Log Tool Call Event Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Example of creating a MetricsTracker instance and logging a ToolCall event. Ensure AnalyticsEngineDataset and ServerInfo are correctly provided. ```typescript const metrics = new MetricsTracker(env.MCP_METRICS, SERVER_INFO); metrics.logEvent(new ToolCall({ toolName: 'search', userId: user?.id, errorCode: undefined // Success })); ``` -------------------------------- ### Direct Tool Call Example Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Illustrates how to directly call a non-codemode tool with its arguments, bypassing explicit code writing. This is used for composition scenarios. ```javascript // Direct tool call instead of writing code { "name": "get_accounts_workers_scripts", "arguments": { "account_id": "abc123", "limit": "10" } } ``` -------------------------------- ### Example JSON Configuration for OAuth Source: https://github.com/cloudflare/mcp/blob/main/README.md This JSON configuration is used when setting up the MCP server with OAuth authentication. It specifies the MCP server URL. ```json { "mcpServers": { "cloudflare-api": { "type": "http", "url": "https://mcp.cloudflare.com/mcp" } } } ``` -------------------------------- ### Example Cloudflare API Error Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/errors.md An example of a Cloudflare API error, specifically for invalid DNS record parameters. ```text Error: Cloudflare API error: 1000: Invalid request body ``` -------------------------------- ### getProducts Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Gets the product list from cache or R2. It has a 1-hour in-isolate TTL and falls back to R2, returning an empty array if unseeded. ```APIDOC ## getProducts ### Description Gets the product list from cache or R2. It has a 1-hour in-isolate TTL and falls back to R2, returning an empty array if unseeded. ### Method async ### Endpoint (Not specified, likely a utility function) ### Parameters None ### Returns Array of product names ``` -------------------------------- ### Account Discovery Guidance Constants Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Provides constant strings for guiding users on how to discover accounts when resolution fails. These are used in error messages and tool descriptions for multi-account scenarios. ```typescript const ACCOUNT_DISCOVERY_GUIDANCE = 'Call GET /accounts to discover available accounts.'; ``` ```typescript const ACCOUNT_DISCOVERY_DESCRIPTION = 'Call GET /accounts to discover available accounts. Paginate as needed, or filter by exact name with GET /accounts?name=.'; ``` ```typescript const NON_CODEMODE_ACCOUNT_DISCOVERY_GUIDANCE = 'Call the get_accounts tool to discover available accounts.'; ``` -------------------------------- ### Example OpenAPI Spec Entry Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md Illustrates a typical entry within the resolved OpenAPI specification file (spec.json), detailing an API endpoint with its HTTP method, summary, description, parameters, and responses. ```json { "/accounts/{account_id}/workers/scripts": { "get": { "summary": "List Worker scripts", "description": "Fetch all Cloudflare Worker scripts for an account", "tags": ["workers"], "parameters": [ { "name": "account_id", "in": "path", "required": true, "description": "The Cloudflare account ID" }, { "name": "limit", "in": "query", "required": false, "description": "Number of results per page" } ], "responses": { ... } }, "post": { ... } } } ``` -------------------------------- ### Example Non-Codemode Tool Structure Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md Shows the structure of a tool definition within the non-codemode-tools.json file, including its name, description, input schema, HTTP method, path, and execution details. ```typescript { name: "get_accounts_workers_scripts", description: "GET /accounts/{account_id}/workers/scripts\n\nList Worker scripts", inputSchema: JsonObjectSchema, method: "get", path: "/accounts/{account_id}/workers/scripts", queryParams: ["limit", "page"], headerParams: [], execution: { taskSupport: 'forbidden' } } ``` -------------------------------- ### Retrieve Product List Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Gets the list of products from the isolate cache or R2. It has a 1-hour TTL in the isolate cache and returns an empty array if the list is not found or unseeded. ```typescript async function getProducts(): Promise ``` -------------------------------- ### Example JSON Configuration with Code Mode Disabled Source: https://github.com/cloudflare/mcp/blob/main/README.md This JSON configuration is used when the MCP server is set up with code mode disabled. It includes the `?codemode=false` query parameter in the URL. ```json { "mcpServers": { "cloudflare-api": { "type": "http", "url": "https://mcp.cloudflare.com/mcp?codemode=false" } } } ``` -------------------------------- ### Upload a Worker script (multipart) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Use this example to upload a Worker script, including its code and metadata, to Cloudflare. It constructs a multipart/form-data request body for the PUT operation. ```javascript async () => { const code = "export default { fetch: () => new Response('hi') }"; const metadata = { body_part: "script", bindings: [{ type: "kv_namespace", name: "MY_KV", namespace_id: "..." }] }; const boundary = `--F${Date.now()}`; const body = [ `--${boundary}`, 'Content-Disposition: form-data; name="metadata"', 'Content-Type: application/json', '', JSON.stringify(metadata), `--${boundary}`, 'Content-Disposition: form-data; name="script"', 'Content-Type: application/javascript', '', code, `--${boundary}--` ].join("\r\n"); return cloudflare.request({ method: "PUT", path: `/accounts/${accountId}/workers/scripts/my-worker`, body, contentType: `multipart/form-data; boundary=${boundary}`, rawBody: true }); } ``` -------------------------------- ### Access LOADER Worker Binding in TypeScript Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Example of how to access the configured LOADER Worker binding in TypeScript. It demonstrates fetching a worker entrypoint with specific compatibility settings. ```typescript const worker = env.LOADER.get(workerId, { compatibilityDate: "2026-01-12", globalOutbound: exports.GlobalOutbound({ props }), mainModule: "worker.js", modules: { "worker.js": "..." } }); const entrypoint = worker.getEntrypoint(); ``` -------------------------------- ### Use AI Search Binding in TypeScript Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Example of how to use the configured AI binding in TypeScript for performing semantic searches. If the binding is not configured, the docs tool will return an error. ```typescript env.AI.autorag('docs-mcp-rag').search({ query }) ``` -------------------------------- ### Deploy to Production Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Execute the production deployment script. This process includes linting, type checking, building, minification, and deploying the worker to production. ```bash npm run deploy:prod ``` -------------------------------- ### Local Development Bindings Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Lists the required bindings for local development, including LOADER, SPEC_BUCKET, and OAUTH_KV. ```markdown - LOADER binding (Worker Loader) - SPEC_BUCKET binding (R2) - OAUTH_KV binding (KV) - OAuth credentials (for testing OAuth flow) ``` -------------------------------- ### getNonCodemodeTools Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Gets pre-computed non-code-mode tools from cache or R2. If `non-codemode-tools.json` is missing, it derives the tools from `spec.json`. ```APIDOC ## getNonCodemodeTools ### Description Gets pre-computed non-code-mode tools from cache or R2. If `non-codemode-tools.json` is missing, it derives the tools from `spec.json`. ### Method async ### Endpoint (Not specified, likely a utility function) ### Parameters None ### Returns Array of tool definitions ``` -------------------------------- ### Create MCP Server Instance Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Initializes an MCP server for a single session. Use `codemode = true` for development and debugging with search/execute/docs tools, or `false` for production with a larger set of individual tools. ```typescript async function createServer(props: AuthProps, codemode = true): Promise ``` -------------------------------- ### createServer Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Creates and configures an MCP server instance for a single session. It supports both code mode and a non-code mode with a large number of tools. ```APIDOC ## createServer ### Description Creates and configures an MCP server instance for a single session. It supports both code mode and a non-code mode with a large number of tools. ### Method `async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | props | AuthProps | Yes | — | Authentication context (user/account, token) | | codemode | boolean | No | true | Enable code mode (search/execute/docs) vs non-code-mode (~2500 tools) | ### Returns Configured McpServer instance ready for tool calls ``` -------------------------------- ### MCP Server Initialization Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Initializes the MCP server with a specified name and version. ```typescript const server = new McpServer({ name: 'cloudflare-api', version: '0.1.0' }); ``` -------------------------------- ### getNonCodemodeToolMap Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Gets a lookup map (tool name → definition) for fast dispatch. It tracks both the map and its source, regenerating if the source changes. ```APIDOC ## getNonCodemodeToolMap ### Description Gets a lookup map (tool name → definition) for fast dispatch. It tracks both the map and its source, regenerating if the source changes. ### Method async ### Endpoint (Not specified, likely a utility function) ### Parameters None ### Returns Map for O(1) tool lookup ``` -------------------------------- ### Execute Tool Execution Flow Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Outlines the steps for the execute tool, including resolving account IDs, creating an isolated Worker, injecting API tokens, and proxying fetch calls. ```text 1. User provides JavaScript code, optional account_id 2. Resolve account ID (pinned/auto/throw if unresolved) 3. Create isolated Worker 4. Inject API token via GlobalOutbound props 5. Expose cloudflare.request() helper 6. Execute user code: const result = await ({code}()) 7. All fetch() calls proxied through GlobalOutbound ├─ Verify hostname == CLOUDFLARE_API_BASE ├─ Inject Authorization header ├─ Auto-retry on 429 and network errors └─ Return response 8. Handle GraphQL/REST response differences 9. Catch/return result or error 10. Truncate to 24k chars 11. Return to agent ``` -------------------------------- ### Deploy to Staging Command Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Command to deploy the application to the staging environment. ```bash npm run deploy ``` -------------------------------- ### Run Tests Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Execute all defined tests, including unit, mock, and integration tests. ```bash npm run test # Run tests ``` -------------------------------- ### Spec Processing Pipeline Steps Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/overview.md Details the steps involved in the spec processing pipeline, including fetching raw OpenAPI specs, resolving references, extracting product information, and writing artifacts to R2. ```text 1. **Scheduled Task** (daily): Fetch raw OpenAPI spec from `OPENAPI_SPEC_URL` 2. **Ref Resolution**: Walk spec tree, resolve all `$ref` pointers inline 3. **Product Extraction**: Parse product names from path patterns 4. **Three Artifacts Written to R2**: - `spec.json` — Full resolved spec for `search` tool - `products.json` — Product list for tool descriptions - `non-codemode-tools.json` — Pre-computed tool roster for non-code-mode mode ``` -------------------------------- ### getSpec Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Gets the processed spec (as text and parsed paths) from cache or R2. It utilizes an in-isolate cache with a 1-hour TTL and falls back to R2 if the cache is expired or not found. ```APIDOC ## getSpec ### Description Gets the processed spec (as text and parsed paths) from cache or R2. It utilizes an in-isolate cache with a 1-hour TTL and falls back to R2 if the cache is expired or not found. ### Method async ### Endpoint (Not specified, likely a utility function) ### Parameters None ### Returns Object with `text` (raw JSON) and `paths` (parsed) ``` -------------------------------- ### Run Vitest Tests Source: https://github.com/cloudflare/mcp/blob/main/AGENTS.md Commands to run vitest tests for the project. Use 'npm run test' for a single run or 'npm run test:watch' to continuously run tests as files change. ```bash npm run test ``` ```bash npm run test:watch ``` -------------------------------- ### List all Workers in an account Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Use this snippet to retrieve a list of all Workers scripts within a specified Cloudflare account. It utilizes the `cloudflare.request` function to make a GET request to the Workers scripts endpoint. ```javascript async () => { const response = await cloudflare.request({ method: "GET", path: `/accounts/${accountId}/workers/scripts` }); return response.result; } ``` -------------------------------- ### Spec Processing Steps Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/spec-processing.md TypeScript code demonstrating the steps to fetch, process, and extract data from an OpenAPI specification. ```typescript const rawSpec = await fetch(env.OPENAPI_SPEC_URL).json() const processed = processSpec(rawSpec) const products = extractProducts(rawSpec) const paths = processed.paths const nonCodemodeTools = buildNonCodemodeTools(paths) ``` -------------------------------- ### Retrieve Non-Code-Mode Tool Lookup Map Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Gets a map for fast O(1) dispatch of non-code-mode tools, mapping tool names to their definitions. The cache tracks both the map and its source, regenerating if the source changes. ```typescript async function getNonCodemodeToolMap(): Promise> ``` -------------------------------- ### Inlineable Accounts Helper Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Returns the list of accounts if it's safe to display them directly in tool descriptions. Returns null for account tokens or incomplete lists, and the full array for multi-account users with a complete list. ```typescript function inlineableAccounts(props?: AuthProps): Account[] | null ``` -------------------------------- ### Get Specific Endpoint with Request Schema Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Retrieves details for a specific POST endpoint, including its summary, request body schema, and parameters. Accesses the 'post' operation for the path '/accounts/{account_id}/d1/database'. ```javascript async () => { const op = spec.paths['/accounts/{account_id}/d1/database']?.post; return { summary: op?.summary, requestBody: op?.requestBody, parameters: op?.parameters }; } ``` -------------------------------- ### Agent Documentation Search Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/overview.md The `docs` function allows searching documentation via AI Search. ```text Agent │ └─ docs({query: "..."}) └─ Search documentation via AI Search ``` -------------------------------- ### Get User and Accounts Function Signature Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md This function signature defines the expected input and output for retrieving user and account details during a token exchange. It's used to populate authentication properties with relevant user and account information. ```typescript async function getUserAndAccounts(token: string, caller: string): Promise<{ user: UserSchema | null; accounts: AccountSchema[]; accountCount?: number; }> ``` -------------------------------- ### Get Cached API Token Identity Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Retrieves cached user identity and account list per token. Uses KV namespace 'OAUTH_KV' with a TTL of 30 days and a cache key format of 'api-token-identity:v2:{token_hash}'. ```typescript async function getCachedApiTokenIdentity(token: string): Promise ``` -------------------------------- ### ServerInfo Interface Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/types.md Defines basic server information, including its name and version. Used for MCP server initialization and metrics tagging. ```typescript interface ServerInfo { name: string; // 'cloudflare-api' version: string; // '0.1.0' } ``` -------------------------------- ### Register Search Tool Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Registers the search tool with the MCP server. This function is asynchronous and returns a Promise. ```typescript async function registerSearchTool(server: McpServer): Promise ``` -------------------------------- ### Unresolved Account ID Error Response Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/errors.md This error occurs when a multi-account user attempts to read an account ID without selecting a specific account. Call GET /accounts to list available accounts and then specify the desired account_id. ```json { "content": [{ "type": "text", "text": "Error: No account selected: this token has access to multiple accounts. Call GET /accounts to discover available accounts." }], "isError": true } ``` -------------------------------- ### Agent-MCP Server Interaction Flow Source: https://github.com/cloudflare/mcp/blob/main/README.md Illustrates the communication flow between an agent and the MCP server for spec searching and API execution. ```mermaid Agent MCP Server │ │ ├──search({code: "..."})───────►│ Execute code against spec.json │◄──[matching endpoints]────────│ │ │ ├──execute({code: "..."})────── ►│ Execute code against Cloudflare API │◄──[API response]──────────────│ ``` -------------------------------- ### Run Type Checking and Linting Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Perform type checking and linting to ensure code quality. ```bash npm run typecheck # Type checking npm run lint # Linting ``` -------------------------------- ### Tool Not Found Error Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/errors.md This error is returned when a requested tool does not exist within the non-code-mode tools available in the environment. ```json { "content": [ { "type": "text", "text": "Error: Tool {tool_name} not found" } ], "isError": true } ``` -------------------------------- ### Core Tools (Code Mode) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/overview.md Provides core tools for interacting with the OpenAPI spec and Cloudflare API using sandboxed JavaScript. ```APIDOC ## `search` Tool ### Description Queries the OpenAPI spec using sandboxed JavaScript. ### Usage Call this tool with a JavaScript query to search the spec. ``` ```APIDOC ## `execute` Tool ### Description Executes sandboxed JavaScript against the Cloudflare API. ### Usage Call this tool with JavaScript code to interact with the Cloudflare API. ``` ```APIDOC ## `docs` Tool ### Description Searches Cloudflare developer documentation via AI Search. ### Usage Call this tool with a search query to find relevant documentation. ``` -------------------------------- ### Extract Product from API Path Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Extracts a product or feature name from a single API path string. Handles account and zone path patterns. ```typescript function extractProduct(path: string): string | undefined ``` -------------------------------- ### MCP Server File Structure Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md This snippet displays the directory structure of the Cloudflare MCP Server project. It outlines the purpose of each key file and directory within the project. ```text output/ ├── README.md (this file) ├── overview.md Project identity and architecture ├── tools.md Tool reference (search, execute, docs, non-codemode) ├── authentication.md Auth flows and account management ├── types.md Type definitions and interfaces ├── errors.md Error handling and recovery ├── configuration.md Environment and deployment config ├── spec-processing.md OpenAPI spec handling pipeline ├── api-reference.md Core function signatures └── metrics.md Analytics and observability ``` -------------------------------- ### Environment Configuration in wrangler.jsonc Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Specifies environment configurations for staging and production deployments within the wrangler.jsonc file. ```json { "env": { "staging": { ... }, "production": { ... } } } ``` -------------------------------- ### Create a KV namespace Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md This snippet demonstrates how to create a new Key-Value (KV) namespace within a Cloudflare account. It uses `cloudflare.request` to send a POST request with the desired namespace title. ```javascript async () => { const response = await cloudflare.request({ method: "POST", path: `/accounts/${accountId}/storage/kv/namespaces`, body: { title: "my-cache" } }); return response.result; } ``` -------------------------------- ### Enable Detailed Logging for Debugging Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Enable detailed logging for debugging purposes using Wrangler. ```bash wrangler tail --env development ``` -------------------------------- ### Configure OAUTH_KV Namespace Binding Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md JSON configuration for binding a KV namespace named OAUTH_KV. Provide the namespace ID and preview ID for storing OAuth grants and API token cache. ```json { "name": "OAUTH_KV", "type": "kv_namespace", "id": "abc123def456", "preview_id": "xyz789uvw012" } ``` -------------------------------- ### SQL Query to Count Tool Calls by Tool Name Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Counts the occurrences of each tool name for 'tool_call' events originating from 'cloudflare-api', ordered by count. ```sql SELECT blob4 as tool_name, COUNT(*) as count FROM mcp-metrics-* WHERE index1 = 'tool_call' AND blob1 = 'cloudflare-api' GROUP BY blob4 ORDER BY count DESC ``` -------------------------------- ### Execute Tool Input Types (Account Token) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/types.md Defines the input for the execute tool when using an account token, requiring a code string to execute. ```typescript // Account token variant interface ExecuteInputAccountToken { code: string; } ``` -------------------------------- ### Find Endpoints by Product (Workers) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Searches the OpenAPI specification for endpoints tagged with 'workers'. It iterates through all paths and methods, collecting matching endpoints with their summary. ```javascript async () => { const results = []; for (const [path, methods] of Object.entries(spec.paths)) { for (const [method, op] of Object.entries(methods)) { if (op.tags?.some(t => t.toLowerCase() === 'workers')) { results.push({ method: method.toUpperCase(), path, summary: op.summary }); } } } return results; } ``` -------------------------------- ### Handle Multi-Account User Without Account Selected Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/errors.md When interacting with account-specific resources without a selected account, first discover available accounts and then retry the request with a selected account ID. This pattern is useful for ensuring the correct account context is established before making resource-dependent API calls. ```typescript await cloudflare.request({ method: "GET", path: `/accounts/${accountId}/workers/scripts` // accountId is undefined, throws }) ``` ```typescript const accounts = await cloudflare.request({ method: "GET", path: `/accounts`, // Account-independent call }) ``` ```typescript const scripts = await cloudflare.request({ method: "GET", path: `/accounts/${accounts.result[0].id}/workers/scripts` }) ``` -------------------------------- ### Request Handler Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Validates the token, fetches user/account info, and creates the MCP response. Returns null if the request is not an API token request. ```APIDOC ## handleApiTokenRequest ### Description Validates the token and fetches user/account info, then creates the MCP response. Returns `null` if the request is not an API token request (letting OAuth provider handle it). ### Function Signature ```typescript async function handleApiTokenRequest( request: Request, createMcpResponse: (props: AuthProps) => Promise ): Promise ``` ``` -------------------------------- ### Map Blobs to Positional Array Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Demonstrates mapping named blob properties to a positional array, automatically including server name and version. Missing blobs are padded with null. ```typescript mapBlobs({ blob3: "user123", blob4: "search" }) → ["cloudflare-api", "0.1.0", "user123", "search"] ``` -------------------------------- ### Handle API Token Request Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Validates the token, fetches user/account info, and creates the MCP response. Returns null if the request is not an API token request. ```typescript async function handleApiTokenRequest( request: Request, createMcpResponse: (props: AuthProps) => Promise ): Promise ``` -------------------------------- ### Search Tool Execution Flow Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Describes the process for the search tool, which involves executing user-provided JavaScript code within an isolated Worker after fetching its specification. ```text 1. User provides JavaScript code 2. Fetch spec.json from isolate cache (or R2) 3. Create isolated Worker 4. Embed spec.json as module constant 5. Execute user code: const result = await ({code}()) 6. Catch/return result or error 7. Truncate to 24k chars 8. Return to agent ``` -------------------------------- ### User and Account Schemas Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/types.md Defines the basic schemas for user and account information, including constraints on the number of accounts stored inline and pre-versioning grants. ```typescript interface UserSchema { id: string; // User ID from Cloudflare API email: string; // User email } interface AccountSchema { id: string; // Account ID from Cloudflare API name: string; // Human-readable account name } type AccountsSchema = AccountSchema[]; ``` -------------------------------- ### PKCE Code Generation Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Generates the necessary codes for Proof Key for Code Exchange (PKCE) to enhance OAuth 2.0 security. ```APIDOC ## PKCE Code Generation ### Description Generates the necessary codes for Proof Key for Code Exchange (PKCE) to enhance OAuth 2.0 security. ### Function Signature ```typescript async function generatePKCECodes(): Promise ``` ### Returns ```typescript interface PKCECodes { codeChallenge: string; // SHA-256 hash of verifier (base64url) codeVerifier: string; // 96-char random string } ``` ``` -------------------------------- ### Configure SPEC_BUCKET R2 Binding Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md JSON configuration for binding an R2 bucket named SPEC_BUCKET to store OpenAPI spec artifacts. Specify the bucket name and jurisdiction. ```json { "name": "SPEC_BUCKET", "type": "r2_bucket", "bucket_name": "mcp-specs", "jurisdiction": "eu" } ``` -------------------------------- ### Configure MCP Transport Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md Set up the WebStandardStreamableHTTPServerTransport with options for JSON response and retry intervals. Session ID generation is left undefined for default behavior. ```typescript const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, // No custom session IDs enableJsonResponse: true, // Return JSON (not JSONL streaming) retryInterval: 1000 // Milliseconds between retries }); ``` -------------------------------- ### Search Tool Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md The `search` tool allows agents to query the Cloudflare OpenAPI specification using sandboxed JavaScript. It enables searching for endpoints based on tags, path patterns, parameters, and request body schemas. ```APIDOC ## Search Tool ### Description Query the Cloudflare OpenAPI specification using sandboxed JavaScript. The entire resolved specification is embedded in the isolate, allowing agents to search for endpoints by tags, path patterns, parameters, and request body schemas. ### Signature ```typescript async function registerSearchTool(server: McpServer): Promise ``` ### Input Schema ```typescript interface SearchInput { code: string; // JavaScript async arrow function to search the OpenAPI spec } ``` ### Input Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | code | string | Yes | — | JavaScript async arrow function that searches `spec.paths` and returns matching endpoints | ### Return Type ```typescript interface ToolResponse { content: Array<{ type: 'text'; text: string }>; } ``` The function executes user code against the spec and returns the result (truncated if > 24,000 characters). Errors include the error message and stack trace. ### Available in User Code ```typescript declare const spec: { paths: Record; }; interface OperationInfo { summary?: string; description?: string; tags?: string[]; parameters?: Array<{ name: string; in: string; // 'path', 'query', 'header' required?: boolean; schema?: unknown; description?: string; }>; requestBody?: { required?: boolean; content?: Record; }; responses?: Record; }>; } interface PathItem { get?: OperationInfo; post?: OperationInfo; put?: OperationInfo; patch?: OperationInfo; delete?: OperationInfo; } ``` ### Usage Examples **Find endpoints by product (e.g., Workers)** ```javascript async () => { const results = []; for (const [path, methods] of Object.entries(spec.paths)) { for (const [method, op] of Object.entries(methods)) { if (op.tags?.some(t => t.toLowerCase() === 'workers')) { results.push({ method: method.toUpperCase(), path, summary: op.summary }); } } } return results; } ``` **Get specific endpoint with request schema** ```javascript async () => { const op = spec.paths['/accounts/{account_id}/d1/database']?.post; return { summary: op?.summary, requestBody: op?.requestBody, parameters: op?.parameters }; } ``` **Find endpoints by path pattern** ```javascript async () => { return Object.entries(spec.paths) .filter(([path]) => path.includes('/workers/')) .map(([path, methods]) => ({ path, methods: Object.keys(methods).map(m => m.toUpperCase()) })); } ``` ``` -------------------------------- ### Response Building Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/authentication.md Builds the `AuthProps` object for use in tool execution and metrics. ```APIDOC ## buildAuthProps ### Description Builds `AuthProps` object for use in tool execution and metrics. ### Function Signature ```typescript function buildAuthProps( token: string, user?: { id: string; email: string } | null, accounts?: Array<{ id: string; name: string }>, accountCount?: number ): AuthProps ``` ``` -------------------------------- ### SQL Query to Find All Tool Calls Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Retrieves all records where the event type is 'tool_call' and the source is 'cloudflare-api', ordered by timestamp. ```sql SELECT * FROM mcp-metrics-* WHERE index1 = 'tool_call' AND blob1 = 'cloudflare-api' ORDER BY timestamp DESC ``` -------------------------------- ### Execute Tool Input Types (User Token) Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/types.md Defines the input for the execute tool when using a user token, requiring a code string and optionally an account ID for multi-account users. ```typescript // User token variant interface ExecuteInputUserToken { code: string; account_id?: string; // For multi-account users } ``` -------------------------------- ### SQL Query to Find Tool Calls by User Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Retrieves the top 100 users by the number of 'tool_call' events made through 'cloudflare-api', ordered by call count. ```sql SELECT blob3 as user_id, COUNT(*) as tool_calls FROM mcp-metrics-* WHERE index1 = 'tool_call' AND blob1 = 'cloudflare-api' GROUP BY blob3 ORDER BY tool_calls DESC LIMIT 100 ``` -------------------------------- ### Incoming MCP Request Flow Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/README.md Details the steps for handling an incoming HTTP POST request to the MCP endpoint, including authentication via API token or OAuth, and response creation. ```text 1. HTTP POST to /mcp endpoint ├─ Check for direct API token (Authorization header) │ ├─ If API token: fetch user/account info, create AuthProps │ └─ Create MCP response └─ If no API token: delegate to OAuth provider ├─ Check grant (OAuth session) ├─ If new user: show authorization dialog ├─ After approval: exchange code, fetch user/account, create AuthProps └─ Create MCP response 2. Create MCP server (code-mode or non-code-mode) ├─ Register tools (search/execute/docs or 2500 endpoint tools) ├─ Attach metrics if code-mode └─ Connect transport 3. Handle incoming request (tools/list or tools/call) ├─ Return tool list or execute tool └─ Log metrics event 4. Return response ``` -------------------------------- ### SQL Query for Tool Success Rate Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Calculates the success, failure, and total error counts for 'tool_call' events from 'cloudflare-api', broken down by tool name. ```sql SELECT blob4 as tool_name, SUM(CASE WHEN double1 IS NULL THEN 1 ELSE 0 END) as successes, SUM(CASE WHEN double1 = -1 THEN 1 ELSE 0 END) as failures, SUM(CASE WHEN double1 IS NOT NULL THEN 1 ELSE 0 END) as total_errors FROM mcp-metrics-* WHERE index1 = 'tool_call' AND blob1 = 'cloudflare-api' GROUP BY blob4 ORDER BY tool_name ``` -------------------------------- ### Execute Tool Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Executes sandboxed JavaScript code against the Cloudflare API. The code can make REST or GraphQL calls using the `cloudflare.request()` function. It supports account-pinned tokens and user tokens, with an optional `account_id` for multi-account scenarios. ```APIDOC ## Execute Tool ### Purpose Execute sandboxed JavaScript against the Cloudflare API. The code has access to a `cloudflare.request()` function that makes REST/GraphQL calls, and optionally an `accountId` parameter for multi-account users. ### Input Schema (Account Token) ```typescript interface ExecuteInputAccountToken { code: string; // JavaScript async arrow function to execute } ``` ### Input Schema (User Token) ```typescript interface ExecuteInputUserToken { code: string; // JavaScript async arrow function to execute account_id?: string; // Optional: Cloudflare account ID for multi-account tokens } ``` ### Input Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | code | string | Yes | — | Async arrow function that calls `cloudflare.request()` and returns a result | | account_id | string | No | Auto-resolved or throws | For multi-account user tokens, specifies which account to target | ### Return Type ```typescript interface ToolResponse { content: Array<{ type: 'text'; text: string }>; } ``` Result is JSON-stringified with 2-space indentation. Returns up to 24,000 characters; longer responses are truncated with a warning. ### Available in User Code ```typescript interface CloudflareRequestOptions { method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; path: string; query?: Record; body?: unknown; contentType?: string; // Custom Content-Type (default: application/json if body present) rawBody?: boolean; // If true, sends body as-is without JSON.stringify } interface CloudflareResponse { success: boolean; status: number; result: T; errors: Array<{ code: number; message: string }>; messages: Array<{ code: number; message: string }>; result_info?: { page: number; per_page: number; total_pages: number; count: number; total_count: number; }; } declare const cloudflare: { request(options: CloudflareRequestOptions): Promise>; }; declare const accountId: string; // Pre-set for single/account tokens, throws for unresolved multi-account ``` ### Usage Examples **List all Workers in an account** ```javascript async () => { const response = await cloudflare.request({ method: "GET", path: `/accounts/${accountId}/workers/scripts` }); return response.result; } ``` **Create a KV namespace** ```javascript async () => { const response = await cloudflare.request({ method: "POST", path: `/accounts/${accountId}/storage/kv/namespaces`, body: { title: "my-cache" } }); return response.result; } ``` **Upload a Worker script (multipart)** ```javascript async () => { const code = "export default { fetch: () => new Response('hi') }"; const metadata = { body_part: "script", bindings: [{ type: "kv_namespace", name: "MY_KV", namespace_id: "..." }] }; const boundary = `--F${Date.now()}`; const body = [ `--${boundary}`, 'Content-Disposition: form-data; name="metadata"', 'Content-Type: application/json', '', JSON.stringify(metadata), `--${boundary}`, 'Content-Disposition: form-data; name="script"', 'Content-Type: application/javascript', '', code, `--${boundary}--` ].join("\r\n"); return cloudflare.request({ method: "PUT", path: `/accounts/${accountId}/workers/scripts/my-worker`, body, contentType: `multipart/form-data; boundary=${boundary}`, rawBody: true }); } ``` **GraphQL query (Analytics API)** ```javascript async () => { return cloudflare.request({ method: "POST", path: "/client/v4/graphql", body: { query: `query { viewer { zones(filter: { zoneTag: "${zoneId}" }) { httpRequests1dGroups(limit: 7) { dimensions { date } sum { requests bytes } } } } }`, variables: {} } }); } ``` ### Account Resolution | Token Type | accountId Behavior | |-----------|-------------------| | Account token | Fixed to the token's pinned account; `accountId` not a parameter | | Single-account user token | Fixed to the user's only account; `accountId` not a parameter | | Multi-account user token | Optional `account_id` parameter; if omitted, reading `accountId` throws an error | ``` -------------------------------- ### createMcpResponse Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/api-reference.md Creates an MCP protocol response for an authenticated session. It handles parsing query parameters, setting up the MCP server and transport, and managing request handling and cleanup. ```APIDOC ## createMcpResponse ### Description Creates an MCP protocol response for an authenticated session. It handles parsing query parameters, setting up the MCP server and transport, and managing request handling and cleanup. ### Method async ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) HTTP Response containing MCP transport response #### Response Example None ``` -------------------------------- ### Documentation Search Tool Input Type Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/types.md Defines the input for the documentation search tool, requiring a query string to search for documentation. ```typescript interface DocsInput { query: string; } ``` -------------------------------- ### PKCECodes Interface Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/types.md Defines the structure for Proof Key for Code Exchange (PKCE) codes, including the code challenge and code verifier. Use `generatePKCECodes()` for generation. ```typescript interface PKCECodes { codeChallenge: string; // Base64url-encoded SHA-256(verifier) codeVerifier: string; // 96-character random string } ``` -------------------------------- ### Cloudflare MCP Repository Structure Source: https://github.com/cloudflare/mcp/blob/main/AGENTS.md This snippet outlines the directory structure of the cloudflare-mcp repository, detailing the purpose of key files and directories within the project. ```tree cloudflare-mcp/ ├── src/ │ ├── index.ts # Worker entry point & OAuth/Hono routing │ ├── server.ts # MCP server setup & tool registration │ ├── executor.ts # Code executor (Worker Loader API) │ ├── spec-processor.ts # OpenAPI spec fetching & $ref resolution │ ├── truncate.ts # Response truncation (~6K token limit) │ ├── metrics.ts # Analytics Engine metrics (session_start/tool_call) │ ├── auth/ │ │ ├── types.ts # Auth props schemas (Zod discriminated union) │ │ ├── api-token-mode.ts # Direct Cloudflare API token support │ │ ├── cloudflare-auth.ts # PKCE & OAuth utilities │ │ ├── oauth-handler.ts # OAuth authorization flow │ │ ├── scopes.ts # OAuth scope definitions (120+ scopes) │ │ └── workers-oauth-utils.ts # OAuth provider helpers ├── tests/ # Vitest suite (top-level, mirrors src/) │ ├── index.test.ts │ ├── auth/ │ ├── executor.test.ts │ ├── spec-processor.test.ts │ ├── truncate.test.ts │ └── e2e/ # End-to-end tests (real worker via exports.default.fetch) │ └── tool-call.test.ts ├── scripts/ │ └── seed-r2.ts # Seed OpenAPI spec to R2 bucket ├── .github/workflows/ │ ├── ci.yml # PR validation │ └── bonk.yml # AI code review ├── wrangler.jsonc # Workers config (dev/staging/prod) ├── .oxfmtrc.json # oxfmt formatter config └── README.md ``` -------------------------------- ### Register Docs Tool Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/tools.md Registers the docs search tool with the MCP server. This function is essential for enabling documentation search capabilities. ```typescript export function registerDocsTool(server: McpServer): void ``` -------------------------------- ### Attach Metrics to MCP Server Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/metrics.md Wires Cloudflare Analytics Engine metrics into a Code-Mode MCP server instance. It instruments server methods to capture and log tool execution success, failure, and exceptions. ```typescript function attachMetrics(server: McpServer, props?: AuthProps): void ``` -------------------------------- ### Configure AI Search Binding Source: https://github.com/cloudflare/mcp/blob/main/_autodocs/configuration.md JSON configuration for binding an AI service named AI, used for semantic search over Cloudflare documentation. This binding is optional. ```json { "name": "AI", "type": "ai" } ```