Skip to content
Merged
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,50 @@ Register the server in your MCP client. Example for Claude Code's `~/.claude.jso

Restart your MCP client. Run `npm run inspect` to test the tools interactively.

### Sites behind Cloudflare Access or another login gateway

A login gateway checks every request before WordPress sees it. Set
`WORDPRESS_CUSTOM_HEADERS` to a JSON object of the headers it requires, and Block MCP
sends them with every request to the site.

For Cloudflare Access, ask your IT team for a service token and a policy that uses the
**Service Auth** action. An **Allow** policy still sends requests to the login page. Set the
variable when you run the connector, and it saves the headers in your client's config.

To keep the secret out of your shell history, paste the JSON at the prompt, then press Enter:

```bash
read -rs WORDPRESS_CUSTOM_HEADERS && export WORDPRESS_CUSTOM_HEADERS
npx -y @gravitykit/block-mcp connect --site https://staging.example.com --client cursor
unset WORDPRESS_CUSTOM_HEADERS
```

Use `--client` to name your client (`cursor`, `claude-code` or `claude-desktop`). Without it, `connect` only prints the config, with the password hidden.

The JSON looks like this:

```json
{"CF-Access-Client-Id":"<client id>","CF-Access-Client-Secret":"<client secret>"}
```

For manual setup, add it to the `env` block with the other variables, with the quotes
escaped:

```json
"WORDPRESS_CUSTOM_HEADERS": "{\"CF-Access-Client-Id\":\"<client id>\",\"CF-Access-Client-Secret\":\"<client secret>\"}"
```

- Block MCP removes these headers and your WordPress credentials from any request that a redirect sends to another site. A site's `www.` and apex addresses count as the same site.
- `connect` won't save these headers if the site reports a different address from `--site`.
- You can't use this setting to replace headers Block MCP sets itself, such as
`Authorization`, `Host` or `Content-Type`.
- Printing the config hides the header values, like the password, unless you pass `--reveal` or `--client print`.
- The Claude Desktop `.mcpb` installer has no field for this setting. Use
`connect --client claude-desktop` instead.

If a tool call returns `gateway_page`, something in front of WordPress answered the request. The
gateway blocked it, or the headers are missing, wrong or not allowed by its policy.

### 4. (Optional) Tune the settings

When the plugin is active, an admin page appears at **Settings → Block MCP**. The defaults work out of the box, but it's worth a look — this is where you decide which blocks AI agents are allowed to write, what to suggest as replacements, and which post types `create_post` can target.
Expand Down
56 changes: 53 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,32 @@ import axios, { AxiosInstance, AxiosError, AxiosRequestConfig } from 'axios';
import { translateWpError } from './error-translator.js';
import { restRouteUrl } from './rest-url.js';
import { coercePostId, isNonEmptyArray, isNonEmptyString } from './coerce.js';
import { CUSTOM_HEADERS_ENV, isGatewayRefusal, stripHeadersOffSite } from './custom-headers.js';

/**
* What to tell an agent when something in front of WordPress answered a REST
* call. The REST API only speaks JSON, so an HTML page means WordPress never saw
* the request.
*/
const GATEWAY_PAGE_MESSAGE =
'something in front of WordPress answered this request, not the REST API. ' +
'A login gateway such as Cloudflare Access or a security plugin is probably blocking it. ' +
`If the gateway needs extra headers, set ${CUSTOM_HEADERS_ENV} in the MCP client config. ` +
'If they are already set, check that the gateway accepts them: a Cloudflare Access policy must use the Service Auth action and include this service token.';

/**
* True when a response body is an unparsed HTML page rather than REST API JSON. JSON
* has already been parsed by this point, even when a host labels it text/html. The
* body is checked as well because a gateway can send a page with the wrong type or none.
*/
function isHtmlPage(data: unknown, contentType: unknown): boolean {
if (typeof data !== 'string') {
return false;
}
const isLabeledHtml = /text\/html/i.test(String(contentType ?? ''));
const startsLikeHtml = /^\s*<(!doctype\s+html|html)[\s>]/i.test(data);
return isLabeledHtml || startsLikeHtml;
}

/** Best-effort MIME type from a filename extension, for multipart uploads. */
function mimeForFilename(filename: string): string {
Expand Down Expand Up @@ -204,7 +230,7 @@ export class WordPressBlockClient {
* @param config - MCP server configuration with URL and credentials
*/
constructor(config: BlockMCPConfig) {
const { wordpress_url, auth } = config;
const { wordpress_url, auth, custom_headers: customHeaders = {} } = config;

if (!wordpress_url) {
throw new Error('WordPress site URL is required (WORDPRESS_URL)');
Expand All @@ -231,12 +257,14 @@ export class WordPressBlockClient {
this.client = axios.create({
baseURL,
headers: {
...customHeaders,
Authorization: `Basic ${credentials}`,
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'GravityKit Block MCP Server (https://github.com/GravityKit/block-mcp)',
},
timeout: 30000,
beforeRedirect: (options) => stripHeadersOffSite(options, baseURL, customHeaders),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

// Request interceptor: once a host is known to reject real verbs, send the
Expand All @@ -256,7 +284,19 @@ export class WordPressBlockClient {
// then format any final error so it carries wpCode/wpData/wpStatus for
// the server-level catch in src/index.ts.
this.client.interceptors.response.use(
(r) => r,
(r) => {
const isGatewayPage = isHtmlPage(r.data, r.headers?.['content-type']);
if (!isGatewayPage) {
return r;
}
const err = new Error(`Block API Error (${r.status}): ${GATEWAY_PAGE_MESSAGE}`) as Error & {
wpCode?: string;
wpStatus?: number;
};
err.wpCode = 'gateway_page';
err.wpStatus = r.status;
throw err;
},
async (error: AxiosError) => {
const config = error.config as
| (AxiosRequestConfig & { __retryCount?: number; __overrideMethod?: boolean })
Expand Down Expand Up @@ -323,7 +363,17 @@ export class WordPressBlockClient {
if ('code' in body && typeof body.code === 'string') code = body.code;
if ('data' in body) wpData = body.data;
} else if (typeof body === 'string') {
detail = body;
// A gateway refusing a bad token answers 401/403 with a full HTML page.
const isGatewayPage = isHtmlPage(body, error.response.headers?.['content-type']);
detail = isGatewayPage ? GATEWAY_PAGE_MESSAGE : body;
code = isGatewayPage ? 'gateway_page' : undefined;
}

if (isGatewayRefusal(status, body)) {
// Keep the gateway's own reason when it gave one. HTML pages were already replaced above.
const hasOwnReason = detail !== 'Unknown error' && detail !== GATEWAY_PAGE_MESSAGE && detail.trim() !== '';
detail = hasOwnReason ? `${detail} (${GATEWAY_PAGE_MESSAGE})` : GATEWAY_PAGE_MESSAGE;
code = 'gateway_page';
}

// Replace HTTP-shaped detail with an agent-actionable hint when we
Expand Down
25 changes: 22 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@
* only as an opaque -32000 with the real reason stranded on stderr.
*/

import { CUSTOM_HEADERS_ENV, parseCustomHeaders, type CustomHeaders } from './custom-headers.js';

export interface WordPressConfig {
url: string;
user: string;
password: string;
/** Extra headers sent with every request to the site, such as a gateway's service token. */
customHeaders: CustomHeaders;
}

export type ConfigResult =
Expand Down Expand Up @@ -38,8 +42,10 @@ function readEnv(env: NodeJS.ProcessEnv, primary: string, legacy: string): strin
* Resolve the WordPress connection config from the process environment.
*
* Returns `{ ok: false, missing, message }` when any of the three required
* values is absent — the caller starts the server in a degraded mode and
* surfaces `message` on tool calls, rather than exiting.
* values is absent, or when the optional custom headers can't be used — the
* caller starts the server in a degraded mode and surfaces `message` on tool
* calls, rather than exiting. Bad headers stop the server instead of being
* ignored: without them every request would just hit the gateway's login page.
*/
export function resolveWordPressConfig(env: NodeJS.ProcessEnv): ConfigResult {
const url = readEnv(env, 'WORDPRESS_URL', 'GK_SITE_URL');
Expand All @@ -65,7 +71,20 @@ export function resolveWordPressConfig(env: NodeJS.ProcessEnv): ConfigResult {
return { ok: false, missing, message };
}

return { ok: true, config: { url: url as string, user: user as string, password: password as string } };
const headers = parseCustomHeaders(env[CUSTOM_HEADERS_ENV]);
if (!headers.ok) {
return { ok: false, missing: [], message: `Block MCP is not configured: ${headers.message}` };
}

return {
ok: true,
config: {
url: url as string,
user: user as string,
password: password as string,
customHeaders: headers.headers,
},
};
}

/**
Expand Down
Loading
Loading