| 1 |
import apiFetch from "@wordpress/api-fetch"; |
| 2 |
|
| 3 |
/** |
| 4 |
* Every call on this page goes through one place, so the nonce is attached |
| 5 |
* exactly once per request and the route prefix is written once. The MCP |
| 6 |
* management routes are `manage_options`-gated cookie-authenticated REST |
| 7 |
* routes — without the nonce WordPress treats the request as logged out and |
| 8 |
* answers 401, which is the failure mode this wrapper exists to prevent. |
| 9 |
*/ |
| 10 |
const NS = () => window.betterdocs_admin?.mcp?.rest || "betterdocs/v1"; |
| 11 |
|
| 12 |
function withNonce() { |
| 13 |
apiFetch.use(apiFetch.createNonceMiddleware(window.betterdocs_admin?.nonce)); |
| 14 |
} |
| 15 |
|
| 16 |
function request(path, options = {}) { |
| 17 |
withNonce(); |
| 18 |
return apiFetch({ path: `${NS()}/${path}`, ...options }); |
| 19 |
} |
| 20 |
|
| 21 |
export const getConnection = () => request("mcp/connection"); |
| 22 |
export const connect = (readOnly = false) => |
| 23 |
request("mcp/connect", { method: "POST", data: { read_only: !!readOnly } }); |
| 24 |
export const rotate = (readOnly = null) => |
| 25 |
request("mcp/rotate", { |
| 26 |
method: "POST", |
| 27 |
data: readOnly === null ? {} : { read_only: !!readOnly }, |
| 28 |
}); |
| 29 |
export const disconnect = () => request("mcp/disconnect", { method: "POST" }); |
| 30 |
|
| 31 |
export const getApps = () => request("mcp/apps"); |
| 32 |
export const revokeApp = (clientId) => |
| 33 |
request("mcp/apps/revoke", { method: "POST", data: { client_id: clientId } }); |
| 34 |
|
| 35 |
export const getHealth = () => request("mcp/health"); |
| 36 |
export const runSelfTest = () => request("mcp/self-test", { method: "POST" }); |
| 37 |
|
| 38 |
/** |
| 39 |
* The master switch writes through BetterDocs' own settings route, the same |
| 40 |
* one the Settings screen uses, so the value is normalised by `Settings` and |
| 41 |
* every other consumer sees it immediately. |
| 42 |
*/ |
| 43 |
export const saveEnableMcp = (enabled) => { |
| 44 |
withNonce(); |
| 45 |
return apiFetch({ |
| 46 |
path: `${NS()}/settings`, |
| 47 |
method: "POST", |
| 48 |
data: { enable_mcp: !!enabled }, |
| 49 |
}); |
| 50 |
}; |
| 51 |
|