#
tokens: 25498/50000 3/388 files (page 6/27)
lines: off (toggle) GitHub
raw markdown copy
This is page 6 of 27. Use http://codebase.md/cloudflare/mcp-server-cloudflare?lines=false&page={x} to view the full context.

# Directory Structure

```
├── .changeset
│   ├── config.json
│   └── README.md
├── .dockerignore
├── .editorconfig
├── .eslintrc.cjs
├── .github
│   ├── actions
│   │   └── setup
│   │       └── action.yml
│   ├── ISSUE_TEMPLATE
│   │   └── bug_report.md
│   └── workflows
│       ├── branches.yml
│       ├── main.yml
│       └── release.yml
├── .gitignore
├── .npmrc
├── .prettierignore
├── .prettierrc.cjs
├── .syncpackrc.cjs
├── .vscode
│   ├── extensions.json
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── apps
│   ├── ai-gateway
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── ai-gateway.app.ts
│   │   │   ├── ai-gateway.context.ts
│   │   │   ├── tools
│   │   │   │   └── ai-gateway.tools.ts
│   │   │   └── types.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── auditlogs
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── auditlogs.app.ts
│   │   │   ├── auditlogs.context.ts
│   │   │   └── tools
│   │   │       └── auditlogs.tools.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── autorag
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── autorag.app.ts
│   │   │   ├── autorag.context.ts
│   │   │   ├── tools
│   │   │   │   └── autorag.tools.ts
│   │   │   └── types.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── browser-rendering
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── browser.app.ts
│   │   │   ├── browser.context.ts
│   │   │   └── tools
│   │   │       └── browser.tools.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── cloudflare-one-casb
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── cf1-casb.app.ts
│   │   │   ├── cf1-casb.context.ts
│   │   │   └── tools
│   │   │       └── integrations.tools.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── demo-day
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── frontend
│   │   │   ├── index.html
│   │   │   ├── public
│   │   │   │   ├── anthropic.svg
│   │   │   │   ├── asana.svg
│   │   │   │   ├── atlassian.svg
│   │   │   │   ├── canva.svg
│   │   │   │   ├── cloudflare_logo.svg
│   │   │   │   ├── cloudflare.svg
│   │   │   │   ├── dina.jpg
│   │   │   │   ├── favicon-16x16.png
│   │   │   │   ├── favicon-32x32.png
│   │   │   │   ├── favicon.ico
│   │   │   │   ├── favicon.png
│   │   │   │   ├── intercom.svg
│   │   │   │   ├── linear.svg
│   │   │   │   ├── matt.jpg
│   │   │   │   ├── mcp_demo_day.svg
│   │   │   │   ├── mcpog.png
│   │   │   │   ├── more.svg
│   │   │   │   ├── paypal.svg
│   │   │   │   ├── pete.jpeg
│   │   │   │   ├── sentry.svg
│   │   │   │   ├── special_guest.png
│   │   │   │   ├── square.svg
│   │   │   │   ├── stripe.svg
│   │   │   │   ├── sunil.jpg
│   │   │   │   └── webflow.svg
│   │   │   ├── script.js
│   │   │   └── styles.css
│   │   ├── package.json
│   │   ├── src
│   │   │   └── demo-day.app.ts
│   │   ├── tsconfig.json
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.json
│   ├── dex-analysis
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── dex-analysis.app.ts
│   │   │   ├── dex-analysis.context.ts
│   │   │   ├── tools
│   │   │   │   └── dex-analysis.tools.ts
│   │   │   └── warp_diag_reader.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── dns-analytics
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── dns-analytics.app.ts
│   │   │   ├── dns-analytics.context.ts
│   │   │   └── tools
│   │   │       └── dex-analytics.tools.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── docs-ai-search
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── docs-ai-search.app.ts
│   │   │   └── docs-ai-search.context.ts
│   │   ├── tsconfig.json
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── docs-autorag
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── docs-autorag.app.ts
│   │   │   ├── docs-autorag.context.ts
│   │   │   └── tools
│   │   │       └── docs-autorag.tools.ts
│   │   ├── tsconfig.json
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── docs-vectorize
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── docs-vectorize.app.ts
│   │   │   └── docs-vectorize.context.ts
│   │   ├── tsconfig.json
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── graphql
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── graphql.app.ts
│   │   │   ├── graphql.context.ts
│   │   │   └── tools
│   │   │       └── graphql.tools.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── logpush
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── logpush.app.ts
│   │   │   ├── logpush.context.ts
│   │   │   └── tools
│   │   │       └── logpush.tools.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── radar
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── radar.app.ts
│   │   │   ├── radar.context.ts
│   │   │   ├── tools
│   │   │   │   ├── radar.tools.ts
│   │   │   │   └── url-scanner.tools.ts
│   │   │   ├── types
│   │   │   │   ├── radar.ts
│   │   │   │   └── url-scanner.ts
│   │   │   └── utils.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── sandbox-container
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── container
│   │   │   ├── fileUtils.spec.ts
│   │   │   ├── fileUtils.ts
│   │   │   ├── sandbox.container.app.ts
│   │   │   └── tsconfig.json
│   │   ├── CONTRIBUTING.md
│   │   ├── Dockerfile
│   │   ├── evals
│   │   │   ├── exec.eval.ts
│   │   │   ├── files.eval.ts
│   │   │   ├── initialize.eval.ts
│   │   │   └── utils.ts
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── server
│   │   │   ├── containerHelpers.ts
│   │   │   ├── containerManager.ts
│   │   │   ├── containerMcp.ts
│   │   │   ├── metrics.ts
│   │   │   ├── prompts.ts
│   │   │   ├── sandbox.server.app.ts
│   │   │   ├── sandbox.server.context.ts
│   │   │   ├── userContainer.ts
│   │   │   ├── utils.spec.ts
│   │   │   └── utils.ts
│   │   ├── shared
│   │   │   ├── consts.ts
│   │   │   └── schema.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.evals.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── workers-bindings
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── .gitignore
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── evals
│   │   │   ├── accounts.eval.ts
│   │   │   ├── hyperdrive.eval.ts
│   │   │   ├── kv_namespaces.eval.ts
│   │   │   ├── types.d.ts
│   │   │   └── utils.ts
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── bindings.app.ts
│   │   │   └── bindings.context.ts
│   │   ├── tsconfig.json
│   │   ├── vitest.config.evals.ts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   ├── workers-builds
│   │   ├── .dev.vars.example
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── CONTRIBUTING.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── tools
│   │   │   │   └── workers-builds.tools.ts
│   │   │   ├── workers-builds.app.ts
│   │   │   └── workers-builds.context.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vite.config.mts
│   │   ├── vitest.config.ts
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.jsonc
│   └── workers-observability
│       ├── .dev.vars.example
│       ├── .eslintrc.cjs
│       ├── CHANGELOG.md
│       ├── CONTRIBUTING.md
│       ├── package.json
│       ├── README.md
│       ├── src
│       │   ├── tools
│       │   │   └── workers-observability.tools.ts
│       │   ├── workers-observability.app.ts
│       │   └── workers-observability.context.ts
│       ├── tsconfig.json
│       ├── types.d.ts
│       ├── vitest.config.ts
│       ├── worker-configuration.d.ts
│       └── wrangler.jsonc
├── CONTRIBUTING.md
├── implementation-guides
│   ├── evals.md
│   ├── tools.md
│   └── type-validators.md
├── LICENSE
├── package.json
├── packages
│   ├── eslint-config
│   │   ├── CHANGELOG.md
│   │   ├── default.cjs
│   │   ├── package.json
│   │   └── README.md
│   ├── eval-tools
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── src
│   │   │   ├── runTask.ts
│   │   │   ├── scorers.ts
│   │   │   └── test-models.ts
│   │   ├── tsconfig.json
│   │   ├── worker-configuration.d.ts
│   │   └── wrangler.json
│   ├── mcp-common
│   │   ├── .eslintrc.cjs
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── api
│   │   │   │   ├── account.api.ts
│   │   │   │   ├── cf1-integration.api.ts
│   │   │   │   ├── workers-builds.api.ts
│   │   │   │   ├── workers-observability.api.ts
│   │   │   │   ├── workers.api.ts
│   │   │   │   └── zone.api.ts
│   │   │   ├── api-handler.ts
│   │   │   ├── api-token-mode.ts
│   │   │   ├── cloudflare-api.ts
│   │   │   ├── cloudflare-auth.ts
│   │   │   ├── cloudflare-oauth-handler.ts
│   │   │   ├── config.ts
│   │   │   ├── constants.ts
│   │   │   ├── durable-kv-store.ts
│   │   │   ├── durable-objects
│   │   │   │   └── user_details.do.ts
│   │   │   ├── env.ts
│   │   │   ├── format.spec.ts
│   │   │   ├── format.ts
│   │   │   ├── get-props.ts
│   │   │   ├── mcp-error.ts
│   │   │   ├── poll.ts
│   │   │   ├── prompts
│   │   │   │   ├── docs-ai-search.prompts.ts
│   │   │   │   └── docs-vectorize.prompts.ts
│   │   │   ├── scopes.ts
│   │   │   ├── sentry.ts
│   │   │   ├── server.ts
│   │   │   ├── tools
│   │   │   │   ├── account.tools.ts
│   │   │   │   ├── d1.tools.ts
│   │   │   │   ├── docs-ai-search.tools.ts
│   │   │   │   ├── docs-vectorize.tools.ts
│   │   │   │   ├── hyperdrive.tools.ts
│   │   │   │   ├── kv_namespace.tools.ts
│   │   │   │   ├── r2_bucket.tools.ts
│   │   │   │   ├── worker.tools.ts
│   │   │   │   └── zone.tools.ts
│   │   │   ├── types
│   │   │   │   ├── cf1-integrations.types.ts
│   │   │   │   ├── cloudflare-mcp-agent.types.ts
│   │   │   │   ├── d1.types.ts
│   │   │   │   ├── hyperdrive.types.ts
│   │   │   │   ├── kv_namespace.types.ts
│   │   │   │   ├── r2_bucket.types.ts
│   │   │   │   ├── shared.types.ts
│   │   │   │   ├── tools.types.ts
│   │   │   │   ├── workers-builds.types.ts
│   │   │   │   ├── workers-logs.types.ts
│   │   │   │   └── workers.types.ts
│   │   │   ├── utils.spec.ts
│   │   │   ├── utils.ts
│   │   │   ├── v4-api.ts
│   │   │   └── workers-oauth-utils.ts
│   │   ├── tests
│   │   │   └── utils
│   │   │       └── cloudflare-mock.ts
│   │   ├── tsconfig.json
│   │   ├── types.d.ts
│   │   ├── vitest.config.ts
│   │   └── worker-configuration.d.ts
│   ├── mcp-observability
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── src
│   │   │   ├── analytics-engine.ts
│   │   │   ├── index.ts
│   │   │   └── metrics.ts
│   │   ├── tsconfig.json
│   │   └── worker-configuration.d.ts
│   ├── tools
│   │   ├── .eslintrc.cjs
│   │   ├── bin
│   │   │   ├── run-changeset-new
│   │   │   ├── run-eslint-workers
│   │   │   ├── run-fix-deps
│   │   │   ├── run-tsc
│   │   │   ├── run-turbo
│   │   │   ├── run-vitest
│   │   │   ├── run-vitest-ci
│   │   │   ├── run-wrangler-deploy
│   │   │   ├── run-wrangler-types
│   │   │   └── runx
│   │   ├── CHANGELOG.md
│   │   ├── package.json
│   │   ├── README.md
│   │   ├── src
│   │   │   ├── bin
│   │   │   │   └── runx.ts
│   │   │   ├── changesets.spec.ts
│   │   │   ├── changesets.ts
│   │   │   ├── cmd
│   │   │   │   └── deploy-published-packages.ts
│   │   │   ├── proc.ts
│   │   │   ├── test
│   │   │   │   ├── fixtures
│   │   │   │   │   └── changesets
│   │   │   │   │       ├── empty
│   │   │   │   │       │   └── .gitkeep
│   │   │   │   │       ├── invalid-json
│   │   │   │   │       │   └── published-packages.json
│   │   │   │   │       ├── invalid-schema
│   │   │   │   │       │   └── published-packages.json
│   │   │   │   │       └── valid
│   │   │   │   │           └── published-packages.json
│   │   │   │   └── setup.ts
│   │   │   └── tsconfig.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.ts
│   └── typescript-config
│       ├── CHANGELOG.md
│       ├── package.json
│       ├── tools.json
│       ├── workers-lib.json
│       └── workers.json
├── pnpm-lock.yaml
├── pnpm-workspace.yaml
├── README.md
├── server.json
├── tsconfig.json
├── turbo.json
└── vitest.workspace.ts
```

# Files

--------------------------------------------------------------------------------
/packages/mcp-common/src/tools/r2_bucket.tools.ts:
--------------------------------------------------------------------------------

```typescript
import { getCloudflareClient } from '../cloudflare-api'
import { MISSING_ACCOUNT_ID_RESPONSE } from '../constants'
import { getProps } from '../get-props'
import { type CloudflareMcpAgent } from '../types/cloudflare-mcp-agent.types'
import {
	BucketListCursorParam,
	BucketListDirectionParam,
	BucketListNameContainsParam,
	BucketListStartAfterParam,
	BucketNameSchema,
} from '../types/r2_bucket.types'
import { PaginationPerPageParam } from '../types/shared.types'

export function registerR2BucketTools(agent: CloudflareMcpAgent) {
	agent.server.tool(
		'r2_buckets_list',
		'List r2 buckets in your Cloudflare account',
		{
			cursor: BucketListCursorParam,
			direction: BucketListDirectionParam,
			name_contains: BucketListNameContainsParam,
			per_page: PaginationPerPageParam,
			start_after: BucketListStartAfterParam,
		},
		{
			title: 'List R2 buckets',
			annotations: {
				readOnlyHint: true,
			},
		},
		async ({ cursor, direction, name_contains, per_page, start_after }) => {
			const account_id = await agent.getActiveAccountId()
			if (!account_id) {
				return MISSING_ACCOUNT_ID_RESPONSE
			}
			try {
				const props = getProps(agent)
				const client = getCloudflareClient(props.accessToken)
				const listResponse = await client.r2.buckets.list({
					account_id,
					cursor: cursor ?? undefined,
					direction: direction ?? undefined,
					name_contains: name_contains ?? undefined,
					per_page: per_page ?? undefined,
					start_after: start_after ?? undefined,
				})

				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								buckets: listResponse.buckets,
								count: listResponse.buckets?.length ?? 0,
							}),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: `Error listing R2 buckets: ${error instanceof Error && error.message}`,
						},
					],
				}
			}
		}
	)

	agent.server.tool(
		'r2_bucket_create',
		'Create a new r2 bucket in your Cloudflare account',
		{ name: BucketNameSchema },
		{
			title: 'Create R2 bucket',
			annotations: {
				readOnlyHint: false,
				destructiveHint: false,
			},
		},
		async ({ name }) => {
			const account_id = await agent.getActiveAccountId()
			if (!account_id) {
				return MISSING_ACCOUNT_ID_RESPONSE
			}
			try {
				const props = getProps(agent)
				const client = getCloudflareClient(props.accessToken)
				const bucket = await client.r2.buckets.create({
					account_id,
					name,
				})
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(bucket),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: `Error creating KV namespace: ${error instanceof Error && error.message}`,
						},
					],
				}
			}
		}
	)

	agent.server.tool(
		'r2_bucket_get',
		'Get details about a specific R2 bucket',
		{ name: BucketNameSchema },
		{
			title: 'Get R2 bucket',
			annotations: {
				readOnlyHint: true,
			},
		},
		async ({ name }) => {
			const account_id = await agent.getActiveAccountId()
			if (!account_id) {
				return MISSING_ACCOUNT_ID_RESPONSE
			}
			try {
				const props = getProps(agent)
				const client = getCloudflareClient(props.accessToken)
				const bucket = await client.r2.buckets.get(name, { account_id })
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(bucket),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: `Error getting R2 bucket: ${error instanceof Error && error.message}`,
						},
					],
				}
			}
		}
	)

	agent.server.tool(
		'r2_bucket_delete',
		'Delete an R2 bucket',
		{ name: BucketNameSchema },
		{
			title: 'Delete R2 bucket',
			annotations: {
				readOnlyHint: false,
				destructiveHint: true,
			},
		},
		async ({ name }) => {
			const account_id = await agent.getActiveAccountId()
			if (!account_id) {
				return MISSING_ACCOUNT_ID_RESPONSE
			}
			try {
				const props = getProps(agent)
				const client = getCloudflareClient(props.accessToken)
				const result = await client.r2.buckets.delete(name, { account_id })
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(result),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: `Error deleting R2 bucket: ${error instanceof Error && error.message}`,
						},
					],
				}
			}
		}
	)

	// Commenting out non-CRUD tools for now to keep the bindings MCP surface small
	// agent.server.tool(
	// 	'r2_bucket_cors_get',
	// 	'Get CORS configuration for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		params: CorsGetParamsSchema.optional(),
	// 	},
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const cors = await client.r2.buckets.cors.get(name, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(cors),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error getting R2 bucket CORS configuration: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_cors_update',
	// 	'Update CORS configuration for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		cors_config: CorsRulesSchema,
	// 	},
	// 	async ({ name, cors_config }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.cors.update(name, {
	// 				account_id,
	// 				...cors_config,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error updating R2 bucket CORS configuration: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_cors_delete',
	// 	'Delete CORS configuration for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		params: CorsDeleteParamsSchema.optional(),
	// 	},
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.cors.delete(name, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error deleting R2 bucket CORS configuration: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_domains_list',
	// 	'List all of the domains for an R2 bucket',
	// 	{ name: BucketNameSchema, params: CustomDomainListParamsSchema.optional() },
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const domains = await client.r2.buckets.domains.custom.list(name, { account_id, ...params })
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(domains),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error listing R2 bucket domains: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_domains_get',
	// 	'Get details about a specific domain for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		domain: CustomDomainNameSchema,
	// 		params: CustomDomainGetParamsSchema.optional(),
	// 	},
	// 	async ({ name, domain, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.domains.custom.get(name, domain, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error getting R2 bucket domain: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_domains_create',
	// 	'Create a new domain for an R2 bucket',
	// 	{ name: BucketNameSchema, params: CustomDomainCreateParamsSchema },
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.domains.custom.create(name, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error creating R2 bucket domain: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_domains_delete',
	// 	'Delete a domain for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		domain: CustomDomainNameSchema,
	// 		params: CustomDomainDeleteParamsSchema.optional(),
	// 	},
	// 	async ({ name, domain, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.domains.custom.delete(name, domain, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error deleting R2 bucket domain: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_domains_update',
	// 	'Update a domain for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		domain: CustomDomainNameSchema,
	// 		params: CustomDomainUpdateParamsSchema,
	// 	},
	// 	async ({ name, domain, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.domains.custom.update(name, domain, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error updating R2 bucket domain: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_event_notifications_get',
	// 	'Get event notifications for an R2 bucket',
	// 	{ name: BucketNameSchema, params: EventNotificationGetParamsSchema.optional() },
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.eventNotifications.get(name, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error getting R2 bucket event notifications: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_event_notifications_update',
	// 	'Update event notifications for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		queueId: QueueIdSchema,
	// 		params: EventNotificationUpdateParamsSchema.optional(),
	// 	},
	// 	async ({ name, queueId, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.eventNotifications.update(name, queueId, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error updating R2 bucket event notifications: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_event_notifications_delete',
	// 	'Delete event notifications for an R2 bucket',
	// 	{
	// 		name: BucketNameSchema,
	// 		queueId: QueueIdSchema,
	// 		params: EventNotificationDeleteParamsSchema.optional(),
	// 	},
	// 	async ({ name, queueId, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.eventNotifications.delete(name, queueId, {
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error deleting R2 bucket event notifications: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_locks_get',
	// 	'Get locks for an R2 bucket',
	// 	{ name: BucketNameSchema, params: LockGetParamsSchema.optional() },
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.locks.get(name, { account_id, ...params })
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error getting R2 bucket locks: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_locks_update',
	// 	'Update locks for an R2 bucket',
	// 	{ name: BucketNameSchema, params: LockUpdateParamsSchema },
	// 	async ({ name, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.locks.update(name, { account_id, ...params })
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error updating R2 bucket locks: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_bucket_temporary_credentials_create',
	// 	'Create temporary credentials for an R2 bucket',
	// 	{ params: TemporaryCredentialsCreateParamsSchema },
	// 	async ({ params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.temporaryCredentials.create({
	// 				account_id,
	// 				...params,
	// 			})
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error creating temporary credentials for R2 bucket: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool('r2_metrics_list', 'List metrics for an R2 bucket', async () => {
	// 	const account_id = await agent.getActiveAccountId()
	// 	if (!account_id) {
	// 		return MISSING_ACCOUNT_ID_RESPONSE
	// 	}
	// 	try {
	// 		const client = getCloudflareClient(props.accessToken)
	// 		const result = await client.r2.buckets.metrics.list({ account_id })
	// 		return {
	// 			content: [
	// 				{
	// 					type: 'text',
	// 					text: JSON.stringify(result),
	// 				},
	// 			],
	// 		}
	// 	} catch (error) {
	// 		return {
	// 			content: [
	// 				{
	// 					type: 'text',
	// 					text: `Error listing R2 bucket metrics: ${error instanceof Error && error.message}`,
	// 				},
	// 			],
	// 		}
	// 	}
	// })

	// agent.server.tool(
	// 	'r2_sippy_get',
	// 	'Get configuration for sippy for an R2 bucket',
	// 	{ bucketName: BucketNameSchema, params: SippyGetParamsSchema.optional() },
	// 	async ({ bucketName, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.sippy.get(bucketName, { account_id, ...params })
	// 			console.log('sippy get result', result)
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result ?? null),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error getting R2 bucket sippy: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_sippy_update',
	// 	'Update configuration for sippy for an R2 bucket',
	// 	{ bucketName: BucketNameSchema, params: SippyUpdateParamsSchema },
	// 	async ({ bucketName, params }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.sippy.update(bucketName, { account_id, ...params })
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error updating R2 bucket sippy: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )

	// agent.server.tool(
	// 	'r2_sippy_delete',
	// 	'Delete sippy for an R2 bucket',
	// 	{ bucketName: BucketNameSchema },
	// 	async ({ bucketName }) => {
	// 		const account_id = await agent.getActiveAccountId()
	// 		if (!account_id) {
	// 			return MISSING_ACCOUNT_ID_RESPONSE
	// 		}
	// 		try {
	// 			const client = getCloudflareClient(props.accessToken)
	// 			const result = await client.r2.buckets.sippy.delete(bucketName, { account_id })
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: JSON.stringify(result),
	// 					},
	// 				],
	// 			}
	// 		} catch (error) {
	// 			return {
	// 				content: [
	// 					{
	// 						type: 'text',
	// 						text: `Error deleting R2 bucket sippy: ${error instanceof Error && error.message}`,
	// 					},
	// 				],
	// 			}
	// 		}
	// 	}
	// )
}

```

--------------------------------------------------------------------------------
/packages/mcp-common/src/workers-oauth-utils.ts:
--------------------------------------------------------------------------------

```typescript
import { z } from 'zod'

import type { AuthRequest, ClientInfo } from '@cloudflare/workers-oauth-provider'

const COOKIE_NAME = '__Host-MCP_APPROVED_CLIENTS'
const ONE_YEAR_IN_SECONDS = 31536000

/**
 * OAuth error class for handling OAuth-specific errors
 */
export class OAuthError extends Error {
	constructor(
		public code: string,
		public description: string,
		public statusCode = 400
	) {
		super(description)
		this.name = 'OAuthError'
	}

	toResponse(): Response {
		return new Response(
			JSON.stringify({
				error: this.code,
				error_description: this.description,
			}),
			{
				status: this.statusCode,
				headers: { 'Content-Type': 'application/json' },
			}
		)
	}
}

/**
 * Imports a secret key string for HMAC-SHA256 signing.
 * @param secret - The raw secret key string.
 * @returns A promise resolving to the CryptoKey object.
 */
async function importKey(secret: string): Promise<CryptoKey> {
	if (!secret) {
		throw new Error('COOKIE_SECRET is not defined. A secret key is required for signing cookies.')
	}
	const enc = new TextEncoder()
	return crypto.subtle.importKey(
		'raw',
		enc.encode(secret),
		{ hash: 'SHA-256', name: 'HMAC' },
		false, // not extractable
		['sign', 'verify'] // key usages
	)
}

/**
 * Signs data using HMAC-SHA256.
 * @param key - The CryptoKey for signing.
 * @param data - The string data to sign.
 * @returns A promise resolving to the signature as a hex string.
 */
async function signData(key: CryptoKey, data: string): Promise<string> {
	const enc = new TextEncoder()
	const signatureBuffer = await crypto.subtle.sign('HMAC', key, enc.encode(data))
	// Convert ArrayBuffer to hex string
	return Array.from(new Uint8Array(signatureBuffer))
		.map((b) => b.toString(16).padStart(2, '0'))
		.join('')
}

/**
 * Verifies an HMAC-SHA256 signature.
 * @param key - The CryptoKey for verification.
 * @param signatureHex - The signature to verify (hex string).
 * @param data - The original data that was signed.
 * @returns A promise resolving to true if the signature is valid, false otherwise.
 */
async function verifySignature(
	key: CryptoKey,
	signatureHex: string,
	data: string
): Promise<boolean> {
	const enc = new TextEncoder()
	try {
		const signatureBytes = new Uint8Array(
			signatureHex.match(/.{1,2}/g)!.map((byte) => Number.parseInt(byte, 16))
		)
		return await crypto.subtle.verify('HMAC', key, signatureBytes.buffer, enc.encode(data))
	} catch (e) {
		console.error('Error verifying signature:', e)
		return false
	}
}

/**
 * Parses the signed cookie and verifies its integrity.
 * @param cookieHeader - The value of the Cookie header from the request.
 * @param secret - The secret key used for signing.
 * @returns A promise resolving to the list of approved client IDs if the cookie is valid, otherwise null.
 */
async function getApprovedClientsFromCookie(
	cookieHeader: string | null,
	secret: string
): Promise<string[] | null> {
	if (!cookieHeader) return null

	const cookies = cookieHeader.split(';').map((c) => c.trim())
	const targetCookie = cookies.find((c) => c.startsWith(`${COOKIE_NAME}=`))

	if (!targetCookie) return null

	const cookieValue = targetCookie.substring(COOKIE_NAME.length + 1)
	const parts = cookieValue.split('.')

	if (parts.length !== 2) {
		console.warn('Invalid cookie format received.')
		return null // Invalid format
	}

	const [signatureHex, base64Payload] = parts
	const payload = atob(base64Payload) // Assuming payload is base64 encoded JSON string

	const key = await importKey(secret)
	const isValid = await verifySignature(key, signatureHex, payload)

	if (!isValid) {
		console.warn('Cookie signature verification failed.')
		return null // Signature invalid
	}

	try {
		const approvedClients = JSON.parse(payload)
		if (!Array.isArray(approvedClients)) {
			console.warn('Cookie payload is not an array.')
			return null // Payload isn't an array
		}
		// Ensure all elements are strings
		if (!approvedClients.every((item) => typeof item === 'string')) {
			console.warn('Cookie payload contains non-string elements.')
			return null
		}
		return approvedClients as string[]
	} catch (e) {
		console.error('Error parsing cookie payload:', e)
		return null // JSON parsing failed
	}
}

/**
 * Checks if a given client ID has already been approved by the user,
 * based on a signed cookie.
 *
 * @param request - The incoming Request object to read cookies from.
 * @param clientId - The OAuth client ID to check approval for.
 * @param cookieSecret - The secret key used to sign/verify the approval cookie.
 * @returns A promise resolving to true if the client ID is in the list of approved clients in a valid cookie, false otherwise.
 */
export async function clientIdAlreadyApproved(
	request: Request,
	clientId: string,
	cookieSecret: string
): Promise<boolean> {
	if (!clientId) return false
	const cookieHeader = request.headers.get('Cookie')
	const approvedClients = await getApprovedClientsFromCookie(cookieHeader, cookieSecret)

	return approvedClients?.includes(clientId) ?? false
}

/**
 * Configuration for the approval dialog
 */
export interface ApprovalDialogOptions {
	/**
	 * Client information to display in the approval dialog
	 */
	client: ClientInfo | null
	/**
	 * Server information to display in the approval dialog
	 */
	server: {
		name: string
		logo?: string
		description?: string
	}
	/**
	 * Arbitrary state data to pass through the approval flow
	 * Will be encoded in the form and returned when approval is complete
	 */
	state: Record<string, any>
	/**
	 * CSRF token to include in the approval form
	 */
	csrfToken: string
	/**
	 * Set-Cookie header to include in the approval response
	 */
	setCookie: string
}

/**
 * Renders an approval dialog for OAuth authorization
 * The dialog displays information about the client and server
 * and includes a form to submit approval
 *
 * @param request - The HTTP request
 * @param options - Configuration for the approval dialog
 * @returns A Response containing the HTML approval dialog
 */
export function renderApprovalDialog(request: Request, options: ApprovalDialogOptions): Response {
	const { client, server, state, csrfToken, setCookie } = options
	const encodedState = btoa(JSON.stringify(state))

	const serverName = sanitizeHtml(server.name)
	const clientName = client?.clientName ? sanitizeHtml(client.clientName) : 'Unknown MCP Client'
	const serverDescription = server.description ? sanitizeHtml(server.description) : ''

	const logoUrl = server.logo ? sanitizeHtml(server.logo) : ''
	const clientUri = client?.clientUri ? sanitizeHtml(client.clientUri) : ''
	const policyUri = client?.policyUri ? sanitizeHtml(client.policyUri) : ''
	const tosUri = client?.tosUri ? sanitizeHtml(client.tosUri) : ''

	const contacts =
		client?.contacts && client.contacts.length > 0 ? sanitizeHtml(client.contacts.join(', ')) : ''

	const redirectUris =
		client?.redirectUris && client.redirectUris.length > 0
			? client.redirectUris.map((uri) => sanitizeHtml(uri)).filter((uri) => uri !== '')
			: []

	const htmlContent = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${clientName} | Authorization Request</title>
        <style>
          /* Modern, responsive styling with system fonts */
          :root {
            --primary-color: #0070f3;
            --error-color: #f44336;
            --border-color: #e5e7eb;
            --text-color: #333;
            --background-color: #fff;
            --card-shadow: 0 8px 36px 8px rgba(0, 0, 0, 0.1);
          }
          
          body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, 
                         Helvetica, Arial, sans-serif, "Apple Color Emoji", 
                         "Segoe UI Emoji", "Segoe UI Symbol";
            line-height: 1.6;
            color: var(--text-color);
            background-color: #f9fafb;
            margin: 0;
            padding: 0;
          }
          
          .container {
            max-width: 600px;
            margin: 2rem auto;
            padding: 1rem;
          }
          
          .precard {
            padding: 2rem;
            text-align: center;
          }
          
          .card {
            background-color: var(--background-color);
            border-radius: 8px;
            box-shadow: var(--card-shadow);
            padding: 2rem;
          }
          
          .header {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1.5rem;
          }
          
          .logo {
            width: 48px;
            height: 48px;
            margin-right: 1rem;
            border-radius: 8px;
            object-fit: contain;
          }
          
          .title {
            margin: 0;
            font-size: 1.3rem;
            font-weight: 400;
          }
          
          .alert {
            margin: 0;
            font-size: 1.5rem;
            font-weight: 400;
            margin: 1rem 0;
            text-align: center;
          }
          
          .description {
            color: #555;
          }
          
          .client-info {
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 1rem 1rem 0.5rem;
            margin-bottom: 1.5rem;
          }
          
          .client-name {
            font-weight: 600;
            font-size: 1.2rem;
            margin: 0 0 0.5rem 0;
          }
          
          .client-detail {
            display: flex;
            margin-bottom: 0.5rem;
            align-items: baseline;
          }
          
          .detail-label {
            font-weight: 500;
            min-width: 120px;
          }
          
          .detail-value {
            font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
            word-break: break-all;
          }
          
          .detail-value a {
            color: inherit;
            text-decoration: underline;
          }
          
          .detail-value.small {
            font-size: 0.8em;
          }
          
          .external-link-icon {
            font-size: 0.75em;
            margin-left: 0.25rem;
            vertical-align: super;
          }
          
          .actions {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            margin-top: 2rem;
          }
          
          .button {
            padding: 0.75rem 1.5rem;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            font-size: 1rem;
          }
          
          .button-primary {
            background-color: var(--primary-color);
            color: white;
          }
          
          .button-secondary {
            background-color: transparent;
            border: 1px solid var(--border-color);
            color: var(--text-color);
          }
          
          /* Responsive adjustments */
          @media (max-width: 640px) {
            .container {
              margin: 1rem auto;
              padding: 0.5rem;
            }
            
            .card {
              padding: 1.5rem;
            }
            
            .client-detail {
              flex-direction: column;
            }
            
            .detail-label {
              min-width: unset;
              margin-bottom: 0.25rem;
            }
            
            .actions {
              flex-direction: column;
            }
            
            .button {
              width: 100%;
            }
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="precard">
            <div class="header">
              ${logoUrl ? `<img src="${logoUrl}" alt="${serverName} Logo" class="logo">` : ''}
            <h1 class="title"><strong>${serverName}</strong></h1>
            </div>
            
            ${serverDescription ? `<p class="description">${serverDescription}</p>` : ''}
          </div>
            
          <div class="card">
            
            <h2 class="alert"><strong>${clientName || 'A new MCP Client'}</strong> is requesting access</h1>
            
            <div class="client-info">
              <div class="client-detail">
                <div class="detail-label">Name:</div>
                <div class="detail-value">
                  ${clientName}
                </div>
              </div>
              
              ${
								clientUri
									? `
                <div class="client-detail">
                  <div class="detail-label">Website:</div>
                  <div class="detail-value small">
                    <a href="${clientUri}" target="_blank" rel="noopener noreferrer">
                      ${clientUri}
                    </a>
                  </div>
                </div>
              `
									: ''
							}
              
              ${
								policyUri
									? `
                <div class="client-detail">
                  <div class="detail-label">Privacy Policy:</div>
                  <div class="detail-value">
                    <a href="${policyUri}" target="_blank" rel="noopener noreferrer">
                      ${policyUri}
                    </a>
                  </div>
                </div>
              `
									: ''
							}
              
              ${
								tosUri
									? `
                <div class="client-detail">
                  <div class="detail-label">Terms of Service:</div>
                  <div class="detail-value">
                    <a href="${tosUri}" target="_blank" rel="noopener noreferrer">
                      ${tosUri}
                    </a>
                  </div>
                </div>
              `
									: ''
							}
              
              ${
								redirectUris.length > 0
									? `
                <div class="client-detail">
                  <div class="detail-label">Redirect URIs:</div>
                  <div class="detail-value small">
                    ${redirectUris.map((uri) => `<div>${uri}</div>`).join('')}
                  </div>
                </div>
              `
									: ''
							}
              
              ${
								contacts
									? `
                <div class="client-detail">
                  <div class="detail-label">Contact:</div>
                  <div class="detail-value">${contacts}</div>
                </div>
              `
									: ''
							}
            </div>
            
            <p>This MCP Client is requesting to be authorized on ${serverName}. If you approve, you will be redirected to complete authentication.</p>
            
            <form method="post" action="${new URL(request.url).pathname}">
              <input type="hidden" name="state" value="${encodedState}">
              <input type="hidden" name="csrf_token" value="${csrfToken}">

              <div class="actions">
                <button type="button" class="button button-secondary" onclick="window.history.back()">Cancel</button>
                <button type="submit" class="button button-primary">Approve</button>
              </div>
            </form>
          </div>
        </div>
      </body>
    </html>
  `

	return new Response(htmlContent, {
		headers: {
			'Content-Security-Policy': "frame-ancestors 'none'",
			'Content-Type': 'text/html; charset=utf-8',
			'Set-Cookie': setCookie,
			'X-Frame-Options': 'DENY',
		},
	})
}

/**
 * Result of parsing the approval form submission.
 */
export interface ParsedApprovalResult {
	/** The original state object containing the OAuth request information. */
	state: { oauthReqInfo?: AuthRequest }
	/** Headers to set on the redirect response, including the Set-Cookie header. */
	headers: Record<string, string>
}

/**
 * Parses the form submission from the approval dialog, extracts the state,
 * and generates Set-Cookie headers to mark the client as approved.
 *
 * @param request - The incoming POST Request object containing the form data.
 * @param cookieSecret - The secret key used to sign the approval cookie.
 * @returns A promise resolving to an object containing the parsed state and necessary headers.
 * @throws If the request method is not POST, form data is invalid, or state is missing.
 */
export async function parseRedirectApproval(
	request: Request,
	cookieSecret: string
): Promise<ParsedApprovalResult> {
	if (request.method !== 'POST') {
		throw new Error('Invalid request method. Expected POST.')
	}

	const formData = await request.formData()

	const tokenFromForm = formData.get('csrf_token')
	if (!tokenFromForm || typeof tokenFromForm !== 'string') {
		throw new Error('Missing CSRF token in form data')
	}

	const cookieHeader = request.headers.get('Cookie') || ''
	const cookies = cookieHeader.split(';').map((c) => c.trim())
	const csrfCookie = cookies.find((c) => c.startsWith('__Host-CSRF_TOKEN='))
	const tokenFromCookie = csrfCookie ? csrfCookie.substring('__Host-CSRF_TOKEN='.length) : null

	if (!tokenFromCookie || tokenFromForm !== tokenFromCookie) {
		throw new Error('CSRF token mismatch')
	}

	const encodedState = formData.get('state')
	if (!encodedState || typeof encodedState !== 'string') {
		throw new Error('Missing state in form data')
	}

	const state = JSON.parse(atob(encodedState))
	if (!state.oauthReqInfo || !state.oauthReqInfo.clientId) {
		throw new Error('Invalid state data')
	}

	const existingApprovedClients =
		(await getApprovedClientsFromCookie(request.headers.get('Cookie'), cookieSecret)) || []
	const updatedApprovedClients = Array.from(
		new Set([...existingApprovedClients, state.oauthReqInfo.clientId])
	)

	const payload = JSON.stringify(updatedApprovedClients)
	const key = await importKey(cookieSecret)
	const signature = await signData(key, payload)
	const newCookieValue = `${signature}.${btoa(payload)}` // signature.base64(payload)

	const headers: Record<string, string> = {
		'Set-Cookie': `${COOKIE_NAME}=${newCookieValue}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=${ONE_YEAR_IN_SECONDS}`,
	}

	return { headers, state }
}

/**
 * Result from bindStateToSession containing the cookie to set
 */
export interface BindStateResult {
	/**
	 * Set-Cookie header value to bind the state to the user's session
	 */
	setCookie: string
}

/**
 * Result from validateOAuthState containing the original OAuth request info and cookie to clear
 */
export interface ValidateStateResult {
	/**
	 * The original OAuth request information that was stored with the state token
	 */
	oauthReqInfo: AuthRequest

	/**
	 * The PKCE code verifier retrieved from server-side storage (never transmitted to client)
	 */
	codeVerifier: string

	/**
	 * Set-Cookie header value to clear the state cookie
	 */
	clearCookie: string
}

export function generateCSRFProtection(): { token: string; setCookie: string } {
	const token = crypto.randomUUID()
	const setCookie = `__Host-CSRF_TOKEN=${token}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`
	return { token, setCookie }
}

export async function createOAuthState(
	oauthReqInfo: AuthRequest,
	kv: KVNamespace,
	codeVerifier: string
): Promise<string> {
	const stateToken = crypto.randomUUID()
	const stateData = { oauthReqInfo, codeVerifier } satisfies {
		oauthReqInfo: AuthRequest
		codeVerifier: string
	}

	await kv.put(`oauth:state:${stateToken}`, JSON.stringify(stateData), {
		expirationTtl: 600,
	})
	return stateToken
}

/**
 * Binds an OAuth state token to the user's browser session using a secure cookie.
 *
 * @param stateToken - The state token to bind to the session
 * @returns Object containing the Set-Cookie header to send to the client
 */
export async function bindStateToSession(stateToken: string): Promise<BindStateResult> {
	const consentedStateCookieName = '__Host-CONSENTED_STATE'

	// Hash the state token to provide defense-in-depth
	const encoder = new TextEncoder()
	const data = encoder.encode(stateToken)
	const hashBuffer = await crypto.subtle.digest('SHA-256', data)
	const hashArray = Array.from(new Uint8Array(hashBuffer))
	const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')

	const setCookie = `${consentedStateCookieName}=${hashHex}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`

	return { setCookie }
}

/**
 * Validates OAuth state from the request, ensuring:
 * 1. The state parameter exists in KV (proves it was created by our server)
 * 2. The state hash matches the session cookie (proves this browser consented to it)
 *
 * This prevents attacks where an attacker's valid state token is injected into
 * a victim's OAuth flow.
 *
 * @param request - The HTTP request containing state parameter and cookies
 * @param kv - Cloudflare KV namespace for storing OAuth state data
 * @returns Object containing the original OAuth request info and cookie to clear
 * @throws If state is missing, mismatched, or expired
 */
export async function validateOAuthState(
	request: Request,
	kv: KVNamespace
): Promise<ValidateStateResult> {
	const consentedStateCookieName = '__Host-CONSENTED_STATE'
	const url = new URL(request.url)
	const stateFromQuery = url.searchParams.get('state')

	if (!stateFromQuery) {
		throw new Error('Missing state parameter')
	}

	// Decode the state parameter to extract the embedded stateToken
	let stateToken: string
	try {
		const decodedState = JSON.parse(atob(stateFromQuery))
		stateToken = decodedState.state
		if (!stateToken) {
			throw new Error('State token not found in decoded state')
		}
	} catch (e) {
		throw new Error('Failed to decode state parameter')
	}

	const storedDataJson = await kv.get(`oauth:state:${stateToken}`)
	if (!storedDataJson) {
		throw new Error('Invalid or expired state')
	}

	const cookieHeader = request.headers.get('Cookie') || ''
	const cookies = cookieHeader.split(';').map((c) => c.trim())
	const consentedStateCookie = cookies.find((c) => c.startsWith(`${consentedStateCookieName}=`))
	const consentedStateHash = consentedStateCookie
		? consentedStateCookie.substring(consentedStateCookieName.length + 1)
		: null

	if (!consentedStateHash) {
		throw new Error('Missing session binding cookie - authorization flow must be restarted')
	}

	const encoder = new TextEncoder()
	const data = encoder.encode(stateToken)
	const hashBuffer = await crypto.subtle.digest('SHA-256', data)
	const hashArray = Array.from(new Uint8Array(hashBuffer))
	const stateHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')

	if (stateHash !== consentedStateHash) {
		throw new Error('State token does not match session - possible CSRF attack detected')
	}

	// Parse and validate stored OAuth state data
	const StoredOAuthStateSchema = z.object({
		oauthReqInfo: z
			.object({
				clientId: z.string(),
				scope: z.array(z.string()),
				state: z.string(),
				responseType: z.string(),
				redirectUri: z.string(),
			})
			.passthrough(), // preserve any other fields from oauth-provider
		codeVerifier: z.string().min(1), // Our code verifier for Cloudflare OAuth
	})

	const parseResult = StoredOAuthStateSchema.safeParse(JSON.parse(storedDataJson))
	if (!parseResult.success) {
		throw new Error('Invalid OAuth state data format - PKCE security violation')
	}

	await kv.delete(`oauth:state:${stateToken}`)
	const clearCookie = `${consentedStateCookieName}=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0`

	return {
		oauthReqInfo: parseResult.data.oauthReqInfo,
		codeVerifier: parseResult.data.codeVerifier,
		clearCookie,
	}
}

/**
 * Sanitizes HTML content to prevent XSS attacks
 * @param unsafe - The unsafe string that might contain HTML
 * @returns A safe string with HTML special characters escaped
 */
function sanitizeHtml(unsafe: string): string {
	return unsafe
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#039;')
}

```

--------------------------------------------------------------------------------
/apps/graphql/src/tools/graphql.tools.ts:
--------------------------------------------------------------------------------

```typescript
import * as LZString from 'lz-string'
import { z } from 'zod'

import { getProps } from '@repo/mcp-common/src/get-props'

import type { GraphQLMCP } from '../graphql.app'

// GraphQL API endpoint
const CLOUDFLARE_GRAPHQL_ENDPOINT = 'https://api.cloudflare.com/client/v4/graphql'

// Type definitions for GraphQL schema responses
interface GraphQLTypeRef {
	kind: string
	name: string | null
	ofType?: GraphQLTypeRef | null
}

interface GraphQLField {
	name: string
	description: string | null
	args: Array<{
		name: string
		description: string | null
		type: GraphQLTypeRef
	}>
	type: GraphQLTypeRef
}

interface GraphQLType {
	name: string
	kind: string
	description: string | null
	fields?: GraphQLField[] | null
	inputFields?: Array<{
		name: string
		description: string | null
		type: GraphQLTypeRef
	}> | null
	interfaces?: Array<{ name: string }> | null
	enumValues?: Array<{
		name: string
		description: string | null
	}> | null
	possibleTypes?: Array<{ name: string }> | null
}

interface SchemaOverviewResponse {
	data: {
		__schema: {
			queryType: { name: string } | null
			mutationType: { name: string } | null
			subscriptionType: { name: string } | null
			types: Array<{
				name: string
				kind: string
				description: string | null
			}>
		}
	}
}

interface TypeDetailsResponse {
	data: {
		__type: GraphQLType
	}
}

// Define the structure of a single error
const graphQLErrorSchema = z.object({
	message: z.string(),
	path: z.array(z.union([z.string(), z.number()])),
	extensions: z.object({
		code: z.string(),
		timestamp: z.string(),
		ray_id: z.string(),
	}),
})

// Define the overall GraphQL response schema
const graphQLResponseSchema = z.object({
	data: z.union([z.record(z.unknown()), z.null()]),
	errors: z.union([z.array(graphQLErrorSchema), z.null()]),
})

/**
 * Fetches the high-level overview of the GraphQL schema
 * @param apiToken Cloudflare API token
 * @returns Basic schema structure
 */
async function fetchSchemaOverview(apiToken: string): Promise<SchemaOverviewResponse> {
	const overviewQuery = `
		query SchemaOverview {
			__schema {
				queryType { name }
				mutationType { name }
				subscriptionType { name }
				types {
					name
					kind
					description
				}
			}
		}
	`

	const response = await executeGraphQLRequest<SchemaOverviewResponse>(overviewQuery, apiToken)
	return response
}

/**
 * Fetches detailed information about a specific GraphQL type
 * @param typeName The name of the type to fetch details for
 * @param apiToken Cloudflare API token
 * @returns Detailed type information
 */
async function fetchTypeDetails(typeName: string, apiToken: string): Promise<TypeDetailsResponse> {
	const typeDetailsQuery = `
		query TypeDetails {
			__type(name: "${typeName}") {
				name
				kind
				description
				fields(includeDeprecated: false) {
					name
					description
					args {
						name
						description
						type {
							kind
							name
							ofType {
								kind
								name
							}
						}
					}
					type {
						kind
						name
						ofType {
							kind
							name
							ofType {
								kind
								name
							}
						}
					}
				}
				inputFields {
					name
					description
					type {
						kind
						name
						ofType {
							kind
							name
						}
					}
				}
				interfaces {
					name
				}
				enumValues(includeDeprecated: false) {
					name
					description
				}
				possibleTypes {
					name
				}
			}
		}
	`

	const response = await executeGraphQLRequest<TypeDetailsResponse>(typeDetailsQuery, apiToken)
	return response
}

/**
 * Helper function to execute GraphQL requests
 * @param query GraphQL query to execute
 * @param apiToken Cloudflare API token
 * @returns Response data
 */
async function executeGraphQLRequest<T>(query: string, apiToken: string): Promise<T> {
	const response = await fetch(CLOUDFLARE_GRAPHQL_ENDPOINT, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			Authorization: `Bearer ${apiToken}`,
		},
		body: JSON.stringify({ query }),
	})

	if (!response.ok) {
		throw new Error(`Failed to execute GraphQL request: ${response.statusText}`)
	}

	const data = graphQLResponseSchema.parse(await response.json())

	// Check for GraphQL errors in the response
	if (data && data.errors && Array.isArray(data.errors) && data.errors.length > 0) {
		const errorMessages = data.errors.map((e: { message: string }) => e.message).join(', ')
		console.warn(`GraphQL errors: ${errorMessages}`)

		// If the error is about mutations not being supported, we can handle it gracefully
		if (errorMessages.includes('Mutations are not supported')) {
			console.info('Mutations are not supported by the Cloudflare GraphQL API')
		}
	}

	return data as T
}

/**
 * Executes a GraphQL query against Cloudflare's API
 * @param query The GraphQL query to execute
 * @param variables Variables for the query
 * @param apiToken Cloudflare API token
 * @returns The query results
 */
async function executeGraphQLQuery(query: string, variables: any, apiToken: string) {
	// Clone the variables to avoid modifying the original
	const queryVariables = { ...variables }

	const response = await fetch(CLOUDFLARE_GRAPHQL_ENDPOINT, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			Authorization: `Bearer ${apiToken}`,
		},
		body: JSON.stringify({
			query,
			variables: queryVariables,
		}),
	})

	if (!response.ok) {
		throw new Error(`Failed to execute GraphQL query: ${response.statusText}`)
	}

	const result = graphQLResponseSchema.parse(await response.json())

	// Check for GraphQL errors in the response
	if (result && result.errors && Array.isArray(result.errors) && result.errors.length > 0) {
		const errorMessages = result.errors.map((e: { message: string }) => e.message).join(', ')
		console.warn(`GraphQL query errors: ${errorMessages}`)
	}

	return result
}

/**
 * Searches for matching types and fields in a GraphQL schema
 * @param schema The GraphQL schema to search
 * @param keyword The keyword to search for
 * @param typeDetails Optional map of type details for deeper searching
 * @returns Matching types and fields
 */
async function searchGraphQLSchema(
	schema: SchemaOverviewResponse,
	keyword: string,
	accountId: string,
	apiToken: string,
	maxDetailsToFetch: number = 10,
	onlyObjectTypes: boolean = true
) {
	const normalizedKeyword = keyword.toLowerCase()
	const results = {
		types: [] as Array<{
			name: string
			kind: string
			description: string | null
			matchReason: string
		}>,
		fields: [] as Array<{
			typeName: string
			fieldName: string
			description: string | null
			matchReason: string
		}>,
		enumValues: [] as Array<{
			typeName: string
			enumValue: string
			description: string | null
			matchReason: string
		}>,
		args: [] as Array<{
			typeName: string
			fieldName: string
			argName: string
			description: string | null
			matchReason: string
		}>,
	}

	// First pass: Search through type names and descriptions
	const matchingTypeNames: string[] = []

	for (const type of schema.data.__schema.types || []) {
		// Skip internal types (those starting with __)
		if (type.name?.startsWith('__')) continue

		// Check if type name or description matches
		if (type.name?.toLowerCase().includes(normalizedKeyword)) {
			results.types.push({
				...type,
				matchReason: `Type name contains "${keyword}"`,
			})
			matchingTypeNames.push(type.name)
		} else if (type.description?.toLowerCase().includes(normalizedKeyword)) {
			results.types.push({
				...type,
				matchReason: `Type description contains "${keyword}"`,
			})
			matchingTypeNames.push(type.name)
		}
	}

	// Second pass: For potentially relevant types, fetch details and search deeper
	// Start with matching types, then add important schema types if we have capacity
	let typesToExamine = [...matchingTypeNames]

	// Add root operation types if they're not already included
	const rootTypes = [
		schema.data.__schema.queryType?.name,
		schema.data.__schema.mutationType?.name,
		schema.data.__schema.subscriptionType?.name,
	].filter(Boolean) as string[]

	for (const rootType of rootTypes) {
		if (!typesToExamine.includes(rootType)) {
			typesToExamine.push(rootType)
		}
	}

	// Add object types that might contain relevant fields
	const objectTypes = schema.data.__schema.types
		.filter((t) => {
			// If onlyObjectTypes is true, only include OBJECT types
			if (onlyObjectTypes) {
				return t.kind === 'OBJECT' && !t.name.startsWith('__')
			}
			// Otherwise include both OBJECT and INTERFACE types
			return (t.kind === 'OBJECT' || t.kind === 'INTERFACE') && !t.name.startsWith('__')
		})
		.map((t) => t.name)

	// Combine all potential types to examine, but limit to a reasonable number
	typesToExamine = [...new Set([...typesToExamine, ...objectTypes])].slice(0, maxDetailsToFetch)

	// Fetch details for these types and search through their fields
	for (const typeName of typesToExamine) {
		try {
			const typeDetails = await fetchTypeDetails(typeName, apiToken)
			const type = typeDetails.data.__type

			if (!type) continue

			// Search through fields
			if (type.fields) {
				for (const field of type.fields) {
					// Check if field name or description matches
					if (field.name.toLowerCase().includes(normalizedKeyword)) {
						results.fields.push({
							typeName: type.name,
							fieldName: field.name,
							description: field.description,
							matchReason: `Field name contains "${keyword}"`,
						})
					} else if (field.description?.toLowerCase().includes(normalizedKeyword)) {
						results.fields.push({
							typeName: type.name,
							fieldName: field.name,
							description: field.description,
							matchReason: `Field description contains "${keyword}"`,
						})
					}

					// Search through field arguments
					if (field.args) {
						for (const arg of field.args) {
							if (arg.name.toLowerCase().includes(normalizedKeyword)) {
								results.args.push({
									typeName: type.name,
									fieldName: field.name,
									argName: arg.name,
									description: arg.description,
									matchReason: `Argument name contains "${keyword}"`,
								})
							} else if (arg.description?.toLowerCase().includes(normalizedKeyword)) {
								results.args.push({
									typeName: type.name,
									fieldName: field.name,
									argName: arg.name,
									description: arg.description,
									matchReason: `Argument description contains "${keyword}"`,
								})
							}
						}
					}
				}
			}

			// Search through enum values
			if (type.enumValues) {
				for (const enumValue of type.enumValues) {
					if (enumValue.name.toLowerCase().includes(normalizedKeyword)) {
						results.enumValues.push({
							typeName: type.name,
							enumValue: enumValue.name,
							description: enumValue.description,
							matchReason: `Enum value contains "${keyword}"`,
						})
					} else if (enumValue.description?.toLowerCase().includes(normalizedKeyword)) {
						results.enumValues.push({
							typeName: type.name,
							enumValue: enumValue.name,
							description: enumValue.description,
							matchReason: `Enum value description contains "${keyword}"`,
						})
					}
				}
			}
		} catch (error) {
			console.error(`Error fetching details for type ${typeName}:`, error)
		}
	}

	return results
}

/**
 * Registers GraphQL tools with the MCP server
 * @param agent The MCP agent instance
 */
export function registerGraphQLTools(agent: GraphQLMCP) {
	// Tool to search the GraphQL schema for types, fields, and enum values matching a keyword
	agent.server.tool(
		'graphql_schema_search',
		`Search the Cloudflare GraphQL API schema for types, fields, and enum values matching a keyword

		Use this tool when:

			- You are unsure which dataset to use for your query.
			- A user is looking for specific types, fields, or enum values in the Cloudflare GraphQL API schema.

		IMPORTANT GUIDELINES:
			- DO NOT query for dimensions unless the user explicitly asked to group by or show dimensions.
			- Only include fields that the user specifically requested in their query.
			- Keep queries as simple as possible while fulfilling the user's request.

		Workflow:
			1. Use this tool to search for dataset types by keyword.
			2. When a relevant dataset type is found, immediately use graphql_schema_details to get the complete structure of that dataset.
			3. After understanding the schema structure, proceed directly to constructing and executing queries using the graphql_query tool.
			4. Do not use graphql_schema_overview or graphql_complete_schema after finding the relevant dataset - these are redundant steps.

		This tool searches the Cloudflare GraphQL API schema for any schema elements (such as object types, field names, or enum options) that match a given keyword. It returns schema fragments and definitions to assist in constructing valid and precise GraphQL queries.
		`,
		{
			keyword: z.string().describe('The keyword to search for in the schema'),
			maxDetailsToFetch: z
				.number()
				.min(1)
				.max(50)
				.default(10)
				.describe('Maximum number of types to fetch details for'),
			includeInternalTypes: z
				.boolean()
				.default(false)
				.describe(
					'Whether to include internal types (those starting with __) in the search results'
				),
			onlyObjectTypes: z
				.boolean()
				.default(true)
				.describe(
					'Whether to only include OBJECT kind types in the search results with descriptions'
				),
		},
		async (params) => {
			const {
				keyword,
				maxDetailsToFetch = 10,
				includeInternalTypes = false,
				onlyObjectTypes = true,
			} = params
			const accountId = await agent.getActiveAccountId()
			if (!accountId) {
				return {
					content: [
						{
							type: 'text',
							text: 'No currently active accountId. Try listing your accounts (accounts_list) and then setting an active account (set_active_account)',
						},
					],
				}
			}

			try {
				const props = getProps(agent)
				// First fetch the schema overview
				const schemaOverview = await fetchSchemaOverview(props.accessToken)

				// Search the schema for the keyword
				const searchResults = await searchGraphQLSchema(
					schemaOverview,
					keyword,
					accountId,
					props.accessToken,
					maxDetailsToFetch,
					onlyObjectTypes
				)

				// Filter out internal types if requested
				if (!includeInternalTypes) {
					searchResults.types = searchResults.types.filter((t) => !t.name.startsWith('__'))
					searchResults.fields = searchResults.fields.filter((f) => !f.typeName.startsWith('__'))
					searchResults.enumValues = searchResults.enumValues.filter(
						(e) => !e.typeName.startsWith('__')
					)
					searchResults.args = searchResults.args.filter((a) => !a.typeName.startsWith('__'))
				}

				// Filter out items without descriptions when onlyObjectTypes is true
				if (onlyObjectTypes) {
					searchResults.types = searchResults.types.filter((t) => {
						return t.description && t.description.trim() !== ''
					})
					searchResults.fields = searchResults.fields.filter((f) => {
						return f.description && f.description.trim() !== ''
					})
					searchResults.enumValues = searchResults.enumValues.filter((e) => {
						return e.description && e.description.trim() !== ''
					})
					searchResults.args = searchResults.args.filter((a) => {
						return a.description && a.description.trim() !== ''
					})
				}

				// Add summary information
				const results = {
					keyword,
					summary: {
						totalMatches:
							searchResults.types.length +
							searchResults.fields.length +
							searchResults.enumValues.length +
							searchResults.args.length,
						typeMatches: searchResults.types.length,
						fieldMatches: searchResults.fields.length,
						enumValueMatches: searchResults.enumValues.length,
						argumentMatches: searchResults.args.length,
					},
					results: searchResults,
				}

				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(results),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								error: `Error searching GraphQL schema: ${error instanceof Error ? error.message : String(error)}`,
							}),
						},
					],
				}
			}
		}
	)

	// Tool to fetch the GraphQL schema overview (high-level structure)
	agent.server.tool(
		'graphql_schema_overview',
		`Fetch the high-level overview of the Cloudflare GraphQL API schema
		
		Use this tool when:

			- A user requests insights into the structure or capabilities of Cloudflare’s GraphQL API.
			- You need to explore available types, queries, mutations, or schema relationships exposed by Cloudflare’s GraphQL interface.
			- You're generating or validating GraphQL queries against Cloudflare’s schema.
			- You are troubleshooting or developing integrations with Cloudflare’s API and require up-to-date schema information.

		This tool returns a high-level summary of the Cloudflare GraphQL API schema. It provides a structured outline of API entry points, data models, and relationships to help guide query construction or system integration.
		`,
		{
			pageSize: z
				.number()
				.min(10)
				.max(1000)
				.default(100)
				.describe('Number of types to return per page'),
			page: z.number().min(1).default(1).describe('Page number to fetch'),
		},
		async (params) => {
			const { pageSize = 100, page = 1 } = params
			const accountId = await agent.getActiveAccountId()
			if (!accountId) {
				return {
					content: [
						{
							type: 'text',
							text: 'No currently active accountId. Try listing your accounts (accounts_list) and then setting an active account (set_active_account)',
						},
					],
				}
			}

			try {
				const props = getProps(agent)
				const schemaOverview = await fetchSchemaOverview(props.accessToken)

				// Apply pagination to the types array
				const allTypes = schemaOverview.data.__schema.types || []
				const totalTypes = allTypes.length
				const totalPages = Math.ceil(totalTypes / pageSize)

				// Calculate start and end indices for the current page
				const startIndex = (page - 1) * pageSize
				const endIndex = Math.min(startIndex + pageSize, totalTypes)

				// Create a paginated version of the schema
				const paginatedSchema = {
					data: {
						__schema: {
							queryType: schemaOverview.data.__schema.queryType,
							mutationType: schemaOverview.data.__schema.mutationType,
							subscriptionType: schemaOverview.data.__schema.subscriptionType,
							types: allTypes.slice(startIndex, endIndex),
						},
					},
					pagination: {
						page,
						pageSize,
						totalTypes,
						totalPages,
						hasNextPage: page < totalPages,
						hasPreviousPage: page > 1,
					},
				}

				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(paginatedSchema),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								error: `Error fetching GraphQL schema overview: ${error instanceof Error ? error.message : String(error)}`,
							}),
						},
					],
				}
			}
		}
	)

	// Tool to fetch detailed information about a specific GraphQL type
	agent.server.tool(
		'graphql_type_details',
		`Fetch detailed information about a specific GraphQL type (dataset)

		IMPORTANT: After exploring the schema, DO NOT generate overly complicated GraphQL queries that the user didn't explicitly ask for. Only include fields that were specifically requested.

		Use this tool when:

			- You need to explore the fields by the type name (dataset) for detailed information
			- You're building or debugging GraphQL queries and want to ensure the correct usage of schema components
			- You need contextual information about how a certain concept or object is represented in Cloudflare's GraphQL API.

		Guidelines for query construction:
			- Keep queries as simple as possible while fulfilling the user's request
			- Only include fields that the user specifically asked for
			- Do not add dimensions or additional fields unless explicitly requested
			- When in doubt, ask the user for clarification rather than creating a complex query
		`,
		{
			typeName: z
				.string()
				.describe('The type name (dataset) of the GraphQL type to fetch details for'),
			fieldsPageSize: z
				.number()
				.min(5)
				.max(500)
				.default(50)
				.describe('Number of fields to return per page'),
			fieldsPage: z.number().min(1).default(1).describe('Page number for fields to fetch'),
			enumValuesPageSize: z
				.number()
				.min(5)
				.max(500)
				.default(50)
				.describe('Number of enum values to return per page'),
			enumValuesPage: z.number().min(1).default(1).describe('Page number for enum values to fetch'),
		},
		async (params) => {
			const {
				typeName,
				fieldsPageSize = 50,
				fieldsPage = 1,
				enumValuesPageSize = 50,
				enumValuesPage = 1,
			} = params

			const accountId = await agent.getActiveAccountId()
			if (!accountId) {
				return {
					content: [
						{
							type: 'text',
							text: 'No currently active accountId. Try listing your accounts (accounts_list) and then setting an active account (set_active_account)',
						},
					],
				}
			}

			try {
				const props = getProps(agent)
				const typeDetails = await fetchTypeDetails(typeName, props.accessToken)

				// Apply pagination to fields if they exist
				const allFields = typeDetails.data.__type.fields || []
				const totalFields = allFields.length
				const totalFieldsPages = Math.ceil(totalFields / fieldsPageSize)

				// Calculate start and end indices for the fields page
				const fieldsStartIndex = (fieldsPage - 1) * fieldsPageSize
				const fieldsEndIndex = Math.min(fieldsStartIndex + fieldsPageSize, totalFields)

				// Apply pagination to enum values if they exist
				const allEnumValues = typeDetails.data.__type.enumValues || []
				const totalEnumValues = allEnumValues.length
				const totalEnumValuesPages = Math.ceil(totalEnumValues / enumValuesPageSize)

				// Calculate start and end indices for the enum values page
				const enumValuesStartIndex = (enumValuesPage - 1) * enumValuesPageSize
				const enumValuesEndIndex = Math.min(
					enumValuesStartIndex + enumValuesPageSize,
					totalEnumValues
				)

				// Create a paginated version of the type details
				const paginatedTypeDetails = {
					data: {
						__type: {
							...typeDetails.data.__type,
							fields: allFields.slice(fieldsStartIndex, fieldsEndIndex),
							enumValues: allEnumValues.slice(enumValuesStartIndex, enumValuesEndIndex),
						},
					},
					pagination: {
						fields: {
							page: fieldsPage,
							pageSize: fieldsPageSize,
							totalFields,
							totalPages: totalFieldsPages,
							hasNextPage: fieldsPage < totalFieldsPages,
							hasPreviousPage: fieldsPage > 1,
						},
						enumValues: {
							page: enumValuesPage,
							pageSize: enumValuesPageSize,
							totalEnumValues,
							totalPages: totalEnumValuesPages,
							hasNextPage: enumValuesPage < totalEnumValuesPages,
							hasPreviousPage: enumValuesPage > 1,
						},
					},
				}

				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(paginatedTypeDetails),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								error: `Error fetching type details: ${error instanceof Error ? error.message : String(error)}`,
							}),
						},
					],
				}
			}
		}
	)

	// Tool to fetch the complete GraphQL schema (combines overview and important type details)
	agent.server.tool(
		'graphql_complete_schema',
		'Fetch the complete Cloudflare GraphQL API schema (combines overview and important type details)',
		{
			typesPageSize: z
				.number()
				.min(10)
				.max(500)
				.default(100)
				.describe('Number of types to return per page'),
			typesPage: z.number().min(1).default(1).describe('Page number for types to fetch'),
			includeRootTypeDetails: z
				.boolean()
				.default(true)
				.describe('Whether to include detailed information about root types'),
			maxTypeDetailsToFetch: z
				.number()
				.min(0)
				.max(10)
				.default(3)
				.describe('Maximum number of important types to fetch details for'),
		},
		async (params) => {
			const {
				typesPageSize = 100,
				typesPage = 1,
				includeRootTypeDetails = true,
				maxTypeDetailsToFetch = 3,
			} = params

			const accountId = await agent.getActiveAccountId()
			if (!accountId) {
				return {
					content: [
						{
							type: 'text',
							text: 'No currently active accountId. Try listing your accounts (accounts_list) and then setting an active account (set_active_account)',
						},
					],
				}
			}

			try {
				const props = getProps(agent)
				// First fetch the schema overview
				const schemaOverview = await fetchSchemaOverview(props.accessToken)

				// Apply pagination to the types array
				const allTypes = schemaOverview.data.__schema.types || []
				const totalTypes = allTypes.length
				const totalPages = Math.ceil(totalTypes / typesPageSize)

				// Calculate start and end indices for the current page
				const startIndex = (typesPage - 1) * typesPageSize
				const endIndex = Math.min(startIndex + typesPageSize, totalTypes)

				// Get the paginated types
				const paginatedTypes = allTypes.slice(startIndex, endIndex)

				// Create the base schema with paginated types
				const schema: {
					data: {
						__schema: {
							queryType: { name: string } | null
							mutationType: { name: string } | null
							subscriptionType: { name: string } | null
							types: Array<{
								name: string
								kind: string
								description: string | null
							}>
						}
					}
					typeDetails: Record<string, GraphQLType>
					pagination: {
						types: {
							page: number
							pageSize: number
							totalTypes: number
							totalPages: number
							hasNextPage: boolean
							hasPreviousPage: boolean
						}
					}
				} = {
					data: {
						__schema: {
							queryType: schemaOverview.data.__schema.queryType,
							mutationType: schemaOverview.data.__schema.mutationType,
							subscriptionType: schemaOverview.data.__schema.subscriptionType,
							types: paginatedTypes,
						},
					},
					typeDetails: {} as Record<string, GraphQLType>,
					pagination: {
						types: {
							page: typesPage,
							pageSize: typesPageSize,
							totalTypes,
							totalPages,
							hasNextPage: typesPage < totalPages,
							hasPreviousPage: typesPage > 1,
						},
					},
				}

				// If requested, fetch details for root types
				if (includeRootTypeDetails) {
					// Identify important root types
					const rootTypes = [
						schemaOverview.data.__schema.queryType?.name,
						...(schemaOverview.data.__schema.mutationType?.name
							? [schemaOverview.data.__schema.mutationType.name]
							: []),
					].filter(Boolean) as string[]

					// Limit the number of types to fetch details for
					const typesToFetch = rootTypes.slice(0, maxTypeDetailsToFetch)

					// Fetch details for each type
					for (const typeName of typesToFetch) {
						try {
							const typeDetails = await fetchTypeDetails(typeName, props.accessToken)
							if (typeDetails.data.__type) {
								schema.typeDetails[typeName] = typeDetails.data.__type
							}
						} catch (error) {
							console.error(`Error fetching details for type ${typeName}:`, error)
						}
					}
				}

				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify(schema),
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								error: `Error fetching GraphQL schema: ${error instanceof Error ? error.message : String(error)}`,
							}),
						},
					],
				}
			}
		}
	)

	// Tool to execute a GraphQL query
	agent.server.tool(
		'graphql_query',
		`Execute a GraphQL query against the Cloudflare API

		IMPORTANT: ONLY execute the EXACT GraphQL query provided by the user. DO NOT generate complicated queries that the user didn't explicitly ask for.

		CRITICAL: When querying, make sure to set a LIMIT (e.g., first: 10, limit: 20) otherwise the response may be too large for the MCP server to process.

		Use this tool when:

			- A user provides a GraphQL query and expects real-time data from Cloudflare's API.
			- You need to retrieve live information from Cloudflare, such as analytics, logs, account data, or configuration details.
			- You want to validate the behavior of a GraphQL query or inspect its runtime results.

		This tool sends a user-defined GraphQL query to the Cloudflare API and returns the raw response exactly as received. When filtering or querying by time, use ISO 8601 datetime format (e.g., "2020-08-03T02:07:05Z").

		For each query execution, a clickable GraphQL API Explorer link will be provided in the response. Users can click this link to open the query in Cloudflare's GraphQL Explorer interface where they can further modify and experiment with the query.

		Guidelines:
			- Only use the exact query provided by the user. Do not modify or expand it unless explicitly requested.
			- Always suggest including limits in queries (e.g., first: 10, limit: 20) to prevent response size issues.
			- If a query fails due to size limits, advise the user to add or reduce limits in their query.
		`,
		{
			query: z.string().describe('The GraphQL query to execute'),
			variables: z.record(z.any()).optional().describe('Variables for the query'),
		},
		async (params) => {
			const accountId = await agent.getActiveAccountId()
			if (!accountId) {
				return {
					content: [
						{
							type: 'text',
							text: 'No currently active accountId. Try listing your accounts (accounts_list) and then setting an active account (set_active_account)',
						},
					],
				}
			}

			try {
				const props = getProps(agent)
				const { query, variables = {} } = params

				// Execute the GraphQL query and get the raw result
				const result = await executeGraphQLQuery(query, variables, props.accessToken)

				// Generate GraphQL API Explorer link for this query
				const compressedQuery = LZString.compressToEncodedURIComponent(query)
				const compressedVariables = LZString.compressToEncodedURIComponent(
					JSON.stringify(variables)
				)
				const explorerUrl = `https://graphql.cloudflare.com/explorer?query=${compressedQuery}&variables=${compressedVariables}`

				// Check if the response is too large (MCP server will fail if > 1MB)
				const resultString = JSON.stringify(result)
				const SIZE_LIMIT = 800000 // Set a safer limit (800KB) to ensure we stay under 1MB
				if (resultString.length > SIZE_LIMIT) {
					return {
						content: [
							{
								type: 'text',
								text: `ERROR: Query result exceeds size limit (${Math.round(resultString.length / 1024)}KB). MCP server will fail with results larger than 1MB. Please use a lower LIMIT in your GraphQL query to reduce the number of returned items. For example:

- Add 'first: 10' or 'limit: 10' parameters to your query
- Reduce the number of requested fields
- Add more specific filters to narrow down results`,
							},
						],
					}
				}

				return {
					content: [
						{
							type: 'text',
							text: `${resultString}\n\n**[Open in GraphQL Explorer](${explorerUrl})**\nClick the link above to view and modify this query in the Cloudflare GraphQL API Explorer.`,
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								error: `Error executing GraphQL query: ${error instanceof Error ? error.message : String(error)}`,
							}),
						},
					],
				}
			}
		}
	)

	// Tool to generate a GraphQL API Explorer link
	agent.server.tool(
		'graphql_api_explorer',
		`Generate a Cloudflare GraphQL API Explorer link

		Use this tool when:

			- A user asks for any GraphQL queries and wants to explore them in the Cloudflare GraphQL API Explorer.
			- You want to provide a shareable link to a specific GraphQL query for the user to explore and modify.
			- You need to help the user visualize or interact with GraphQL queries in a user-friendly interface.

		This tool generates a direct link to the Cloudflare GraphQL API Explorer with a pre-populated query and variables.
		The response includes a clickable Markdown link that users can click to open the query in Cloudflare's interactive GraphQL playground.
		The original query and variables are also displayed for reference.
		`,
		{
			query: z.string().describe('The GraphQL query to include in the explorer link'),
			variables: z.record(z.any()).optional().describe('Variables for the query in JSON format'),
		},
		async (params) => {
			try {
				const { query, variables = {} } = params

				// Compress the query and variables using lz-string
				const compressedQuery = LZString.compressToEncodedURIComponent(query)
				const compressedVariables = LZString.compressToEncodedURIComponent(
					JSON.stringify(variables)
				)

				// Generate the GraphQL API Explorer URL
				const explorerUrl = `https://graphql.cloudflare.com/explorer?query=${compressedQuery}&variables=${compressedVariables}`

				return {
					content: [
						{
							type: 'text',
							text: `**[Open in GraphQL Explorer](${explorerUrl})**\n\nYou can click the link above to open the Cloudflare GraphQL API Explorer with your query pre-populated.\n\n**Query:**\n\`\`\`graphql\n${query}\n\`\`\`\n\n${Object.keys(variables).length > 0 ? `**Variables:**\n\`\`\`json\n${JSON.stringify(variables, null, 2)}\n\`\`\`\n` : ''}`,
						},
					],
				}
			} catch (error) {
				return {
					content: [
						{
							type: 'text',
							text: JSON.stringify({
								error: `Error generating GraphQL API Explorer link: ${error instanceof Error ? error.message : String(error)}`,
							}),
						},
					],
				}
			}
		}
	)
}

```
Page 6/27FirstPrevNextLast