PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.0.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.0.0
2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk 1.0.0 1.0.1 1.0.2 1.1.0 1.10.0 All 48 releases
thinkrank / includes / mcp / class-mcp-self-test.php

class-mcp-self-test.php in ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO 2.0.0, at includes/mcp/class-mcp-self-test.php

782 lines 29.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * MCP connection self-test.
4 *
5 * @package ThinkRank\Mcp
6 */
7
8 declare(strict_types=1);
9
10 namespace ThinkRank\Mcp;
11
12 use ThinkRank\Abilities\Abilities_Registrar;
13
14 if ( ! defined( 'ABSPATH' ) ) {
15 exit; // Exit if accessed directly.
16 }
17
18 /**
19 * Exercises the MCP round trip the way an external client would and reports
20 * *where* it broke, so an admin can tell a certificate problem from an
21 * authentication problem from an ability-discovery problem without leaving the
22 * MCP page (see #189).
23 *
24 * Four loopback checks, each against a surface a real client actually uses:
25 *
26 * 1. `endpoint` — the pretty URL the user pastes (/thinkrank/mcp), with the
27 * connection token. Depends on rewrite rules, so it fails on
28 * plain permalinks or an unflushed rule table.
29 * 2. `fallback` — the always-on /wp-json/thinkrank/v1/mcp route. Works even
30 * when rewrites do not, which is what separates "the whole
31 * MCP surface is down" from "only the pretty URL is".
32 * 3. `discovery` — the RFC 9728 / RFC 8414 metadata documents.
33 * 4. `challenge` — an UNAUTHENTICATED call, which must answer 401 with a
34 * WWW-Authenticate header. This is the only thing an
35 * OAuth-only client (ChatGPT, claude.ai) has to go on: if
36 * the challenge is missing it reports that the server does
37 * not implement OAuth, no matter how healthy the rest is.
38 *
39 * Checks 3 and 4 exist because a token-pasting client can be perfectly happy
40 * while every OAuth client is refused — the earlier version of this test only
41 * exercised check 2 and so reported `ok` in exactly that situation.
42 *
43 * The staged result names the first failing step: `disabled` → `not_connected`
44 * → `unreachable` → `tls` → `redirect` → `auth` → `no_tools` → `rewrite` →
45 * `discovery` → `challenge` → `ok`.
46 */
47 final class Mcp_Self_Test {
48
49 /**
50 * User agents to replay the challenge probe with, to detect a host that
51 * filters by User-Agent. These are the shapes real MCP backends send —
52 * none of them is a browser, which is exactly what "block bad bots" rules
53 * key on. A site that answers WordPress's own UA but 403s these is
54 * unreachable for every AI client while looking perfectly healthy from
55 * inside.
56 */
57 private const CLIENT_USER_AGENTS = [
58 'python-requests/2.32.3',
59 'node-fetch/3.3.2',
60 ];
61
62 /**
63 * Run the round-trip self-test.
64 *
65 * @return array<string, mixed>
66 */
67 public static function run(): array {
68 $endpoint = Mcp_Pairing::site_endpoint();
69 $fallback = Mcp_Pairing::site_endpoint_fallback();
70
71 $result = [
72 'ok' => false,
73 'stage' => '',
74 'message' => '',
75 'endpoint' => $endpoint,
76 'endpoint_rest' => $fallback,
77 'mcp_enabled' => Mcp_Manager::is_enabled(),
78 'connected' => Mcp_Pairing::is_connected(),
79 'http_status' => null,
80 'redirected' => false,
81 'authenticated' => false,
82 'tools_count' => null,
83 'checks' => [],
84 // url => decoded metadata (or the raw body when it isn't JSON).
85 'discovery_documents' => [],
86 ];
87
88 if ( ! $result['mcp_enabled'] ) {
89 $result['stage'] = 'disabled';
90 $result['message'] = __( 'MCP access is turned off, so the endpoint refuses every request. Enable MCP access above and try again.', 'thinkrank' );
91 return $result;
92 }
93
94 if ( ! $result['connected'] ) {
95 $result['stage'] = 'not_connected';
96 $result['message'] = __( 'No connection token exists yet. Click Connect to mint one, then run the test again.', 'thinkrank' );
97 return $result;
98 }
99
100 $token = Mcp_Pairing::site_token();
101
102 $pretty = self::probe_jsonrpc( $endpoint, $token );
103 $rest = self::probe_jsonrpc( $fallback, $token );
104
105 // Back-compat top-level fields describe the primary (pretty) endpoint,
106 // falling back to the REST route when the pretty URL never answered.
107 $primary = 'unreachable' === $pretty['stage'] ? $rest : $pretty;
108 $result['http_status'] = $primary['status'];
109 $result['redirected'] = 'redirect' === $primary['stage'];
110 $result['authenticated'] = $primary['authenticated'];
111 $result['tools_count'] = $primary['tools'];
112
113 $result['checks'][] = self::check( 'endpoint', __( 'Connection URL', 'thinkrank' ), $pretty['stage'], $pretty['detail'] );
114 $result['checks'][] = self::check( 'fallback', __( 'REST fallback URL', 'thinkrank' ), $rest['stage'], $rest['detail'] );
115
116 $discovery = self::probe_discovery();
117 // The documents themselves, so support can read what the site actually
118 // serves instead of asking the customer for screenshots.
119 $result['discovery_documents'] = $discovery['documents'];
120 $result['checks'][] = self::check( 'discovery', __( 'OAuth discovery', 'thinkrank' ), $discovery['stage'], $discovery['detail'] );
121
122 $challenge = self::probe_challenge( $endpoint, $fallback );
123 $result['checks'][] = self::check( 'challenge', __( 'OAuth challenge', 'thinkrank' ), $challenge['stage'], $challenge['detail'] );
124
125 // Only reported when it could actually run — claiming a pass we did
126 // not measure is the failure mode this whole test exists to avoid.
127 $user_agent = self::probe_user_agent( $endpoint );
128 if ( null !== $user_agent ) {
129 $result['checks'][] = self::check( 'user_agent', __( 'Client access', 'thinkrank' ), $user_agent['stage'], $user_agent['detail'] );
130 }
131
132 // Locked-out clients. The loopback below can pass while a REMOTE client
133 // is walled off by the failed-auth limiter — the exact state a connector
134 // still holding a rotated-away token produces. Reported only when the
135 // count is knowable (null under a persistent object cache).
136 $lockouts = Mcp_Rate_Limiter::active_lockouts();
137 $result['locked_clients'] = $lockouts;
138 if ( null !== $lockouts && $lockouts > 0 ) {
139 $result['checks'][] = self::check(
140 'lockouts',
141 __( 'Client lockouts', 'thinkrank' ),
142 'locked_clients',
143 sprintf(
144 /* translators: %d: number of currently locked-out clients. */
145 _n(
146 '%d client is currently locked out after repeated failed authentications — typically a connector still holding a rotated-away token. Remove and re-add the connector in the AI client; the lockout clears itself within 15 minutes of the retries stopping.',
147 '%d clients are currently locked out after repeated failed authentications — typically connectors still holding a rotated-away token. Remove and re-add the connector in the AI client; lockouts clear within 15 minutes of the retries stopping.',
148 $lockouts,
149 'thinkrank'
150 ),
151 $lockouts
152 )
153 );
154 }
155
156 // The pretty URL failing while the fallback works is its own finding:
157 // the site is usable, but only via the REST URL.
158 if ( 'ok' !== $pretty['stage'] && 'ok' === $rest['stage'] ) {
159 $result['stage'] = 'rewrite';
160 $result['message'] = sprintf(
161 /* translators: 1: pretty MCP endpoint URL, 2: REST fallback URL. */
162 __( 'The connection URL %1$s did not answer, but the REST fallback %2$s works. Re-save Settings → Permalinks to rebuild the rewrite rules; until then, give your AI client the fallback URL.', 'thinkrank' ),
163 $endpoint,
164 $fallback
165 );
166 return $result;
167 }
168
169 // Otherwise report the first failing check in order.
170 foreach ( [ $pretty, $rest, $discovery, $challenge, $user_agent ] as $check ) {
171 if ( null === $check ) {
172 continue;
173 }
174 if ( 'ok' !== $check['stage'] ) {
175 $result['stage'] = $check['stage'];
176 $result['message'] = $check['detail'];
177 return $result;
178 }
179 }
180
181 $result['ok'] = true;
182 $result['stage'] = 'ok';
183 $result['message'] = sprintf(
184 /* translators: %d: number of MCP tools returned. */
185 _n(
186 'Connection healthy: the endpoint authenticated, offered OAuth, and returned %d tool.',
187 'Connection healthy: the endpoint authenticated, offered OAuth, and returned %d tools.',
188 (int) $result['tools_count'],
189 'thinkrank'
190 ),
191 (int) $result['tools_count']
192 );
193 return $result;
194 }
195
196 // -- Probes ------------------------------------------------------------
197
198 /**
199 * One authenticated JSON-RPC `tools/list` round trip.
200 *
201 * @param string $url Endpoint to call.
202 * @param string $token Connection token.
203 * @return array{stage:string,status:?int,tools:?int,authenticated:bool,detail:string}
204 */
205 private static function probe_jsonrpc( string $url, string $token ): array {
206 $response = wp_remote_post(
207 $url,
208 [
209 'timeout' => 10,
210 // Don't follow redirects: a 301/302 here IS the finding (the
211 // classic http<->https scheme bounce), so surface it verbatim.
212 'redirection' => 0,
213 'headers' => [
214 'Authorization' => 'Bearer ' . $token,
215 'Content-Type' => 'application/json',
216 'Accept' => 'application/json',
217 ],
218 'body' => wp_json_encode(
219 [
220 'jsonrpc' => '2.0',
221 'id' => 1,
222 'method' => 'tools/list',
223 ]
224 ),
225 ]
226 );
227
228 $out = [
229 'stage' => 'ok',
230 'status' => null,
231 'tools' => null,
232 'authenticated' => false,
233 'detail' => '',
234 ];
235
236 if ( is_wp_error( $response ) ) {
237 $err = $response->get_error_message();
238 $is_tls = false !== stripos( $err, 'ssl' ) || false !== stripos( $err, 'certificate' );
239 $out['stage'] = $is_tls ? 'tls' : 'unreachable';
240 $out['detail'] = $is_tls
241 /* translators: 1: endpoint URL, 2: underlying transport error. */
242 ? sprintf( __( '%1$s could not be reached over HTTPS: %2$s. On local/dev sites this is usually a self-signed certificate the AI client must be told to trust.', 'thinkrank' ), $url, $err )
243 /* translators: 1: endpoint URL, 2: underlying transport error. */
244 : sprintf( __( '%1$s could not be reached: %2$s.', 'thinkrank' ), $url, $err );
245 return $out;
246 }
247
248 $status = (int) wp_remote_retrieve_response_code( $response );
249 $out['status'] = $status;
250
251 if ( in_array( $status, [ 301, 302, 307, 308 ], true ) ) {
252 $location = (string) wp_remote_retrieve_header( $response, 'location' );
253 $out['stage'] = 'redirect';
254 $out['detail'] = $location
255 /* translators: 1: endpoint URL, 2: redirect target URL. */
256 ? sprintf( __( '%1$s redirected to %2$s instead of answering. A redirect between HTTP and HTTPS usually means the site address and WordPress address schemes disagree.', 'thinkrank' ), $url, $location )
257 /* translators: %s: endpoint URL. */
258 : sprintf( __( '%s redirected instead of answering, which usually means the site address and WordPress address schemes disagree.', 'thinkrank' ), $url );
259 return $out;
260 }
261
262 if ( 404 === $status ) {
263 $out['stage'] = 'rewrite';
264 $out['detail'] = sprintf(
265 /* translators: %s: endpoint URL. */
266 __( '%s returned 404 — WordPress does not know this URL. Re-save Settings → Permalinks to rebuild the rewrite rules.', 'thinkrank' ),
267 $url
268 );
269 return $out;
270 }
271
272 if ( 401 === $status || 403 === $status ) {
273 $out['stage'] = 'auth';
274 $out['detail'] = sprintf(
275 /* translators: %s: endpoint URL. */
276 __( '%s rejected the connection token (authentication failed). Rotate the token and reconnect your AI client.', 'thinkrank' ),
277 $url
278 );
279 return $out;
280 }
281
282 if ( 429 === $status ) {
283 $out['stage'] = 'auth';
284 $out['detail'] = sprintf(
285 /* translators: %s: endpoint URL. */
286 __( '%s is rate-limiting this server after repeated failed tokens. Wait for the lockout to lapse, then rotate the token and reconnect.', 'thinkrank' ),
287 $url
288 );
289 return $out;
290 }
291
292 $out['authenticated'] = true;
293 $body = json_decode( (string) wp_remote_retrieve_body( $response ), true );
294 $tools = ( is_array( $body ) && isset( $body['result']['tools'] ) && is_array( $body['result']['tools'] ) )
295 ? $body['result']['tools']
296 : null;
297
298 // An EMPTY tools array counts as a failure, not a pass: that is exactly
299 // the shape of #241 — a connection an AI client reports as healthy
300 // while it has nothing to call. The abilities snapshot goes into the
301 // detail so support can tell "no ThinkRank abilities registered"
302 // (foreign Abilities API copy owns the registry) from "the runtime is
303 // missing entirely".
304 if ( 200 !== $status || null === $tools || [] === $tools ) {
305 $out['stage'] = 'no_tools';
306 $out['tools'] = is_array( $tools ) ? count( $tools ) : 0;
307 $out['detail'] = sprintf(
308 /* translators: 1: endpoint URL, 2: abilities-registry diagnostic summary. */
309 __( '%1$s answered but returned no tool catalog. Confirm the MCP runtime is built and abilities are registered. Diagnostics — %2$s', 'thinkrank' ),
310 $url,
311 Abilities_Registrar::summary()
312 );
313 return $out;
314 }
315
316 $out['tools'] = count( $tools );
317 $out['detail'] = sprintf(
318 /* translators: 1: endpoint URL, 2: number of tools. */
319 __( '%1$s authenticated and returned %2$d tools.', 'thinkrank' ),
320 $url,
321 count( $tools )
322 );
323 return $out;
324 }
325
326 /**
327 * Fetch both OAuth discovery documents and confirm they are served and
328 * well-formed. An OAuth client reads these before it holds any credential,
329 * so a 404 here is invisible to every other check.
330 *
331 * @return array{stage:string,detail:string}
332 */
333 private static function probe_discovery(): array {
334 $documents = [];
335
336 // --- The documents clients are POINTED at (must work) -------------
337 // The 401 challenge advertises the REST-served resource metadata, and
338 // spec-compliant clients derive the OIDC-suffix form of the AS
339 // metadata from our path-based issuer. Neither lives under the site
340 // root's /.well-known/ directory, so both survive hosts that
341 // intercept that directory at the proxy edge (SiteGround). Each must
342 // carry an identifier EXACTLY equal to the one we compute locally — a
343 // mere "the key exists" check passes on another plugin's metadata,
344 // which is the hijack case the rewrite rules already warn about.
345 $primary = [
346 Mcp_OAuth::resource_metadata_url() => [
347 'key' => 'resource',
348 'expected' => Mcp_Pairing::site_endpoint(),
349 ],
350 rest_url( 'thinkrank/v1/mcp/oauth/authorization-server' ) => [
351 'key' => 'issuer',
352 'expected' => Mcp_OAuth::issuer(),
353 ],
354 Mcp_OAuth::issuer() . '/.well-known/openid-configuration' => [
355 'key' => 'issuer',
356 'expected' => Mcp_OAuth::issuer(),
357 ],
358 ];
359
360 foreach ( $primary as $url => $spec ) {
361 $issue = self::probe_document( $url, $spec, $documents );
362 if ( null !== $issue ) {
363 return $issue;
364 }
365 }
366
367 // --- The spec-derived /.well-known/ forms (should work) -----------
368 // A client that ignores the challenge pointer derives these itself
369 // (RFC 9728 / RFC 8414 path-insert). Some hosts resolve the root
370 // /.well-known/ directory at their proxy as physical files, 404ing
371 // before WordPress runs — measurably different from broken rewrites,
372 // and fixable by publishing the documents AS physical files.
373 $derived = [
374 home_url( '/.well-known/oauth-protected-resource/' . Mcp_Pairing::SITE_ENDPOINT_PATH ) => [
375 'key' => 'resource',
376 'expected' => Mcp_Pairing::site_endpoint(),
377 ],
378 home_url( '/.well-known/oauth-authorization-server/' . Mcp_Pairing::SITE_ENDPOINT_PATH ) => [
379 'key' => 'issuer',
380 'expected' => Mcp_OAuth::issuer(),
381 ],
382 ];
383
384 $root_issue = null;
385 foreach ( $derived as $url => $spec ) {
386 $root_issue = self::probe_document( $url, $spec, $documents );
387 if ( null !== $root_issue ) {
388 break;
389 }
390 }
391
392 if ( null !== $root_issue ) {
393 // A document that answers with SOMEONE ELSE'S identity is a plugin
394 // conflict poisoning derive-only clients — that stays a hard fail.
395 // Only the intercepted/unreachable shapes are softened below.
396 if ( 'mismatch' === ( $root_issue['kind'] ?? '' ) ) {
397 return $root_issue;
398 }
399
400 // The host's own trick becomes the fix: if the proxy insists on
401 // serving /.well-known/ as physical files, give it physical files.
402 /**
403 * Filter whether the self-test may publish static /.well-known/
404 * discovery files when the dynamic route is unreachable.
405 *
406 * @since 1.32.0
407 *
408 * @param bool $allowed Defaults to whether the install can host them.
409 */
410 $may_publish = apply_filters( 'thinkrank_mcp_static_discovery_publish', Mcp_Static_Discovery::applicable() );
411
412 $healed = false;
413 if ( $may_publish && Mcp_Static_Discovery::publish() ) {
414 $healed = true;
415 foreach ( $derived as $url => $spec ) {
416 if ( null !== self::probe_document( $url, $spec, $documents ) ) {
417 $healed = false;
418 break;
419 }
420 }
421 }
422
423 if ( ! $healed ) {
424 // Not fatal on its own any more: the challenge points clients
425 // at the REST document (verified above), so the flow survives.
426 // Say what is degraded instead of failing the whole check.
427 $scheme_issue = self::probe_scheme();
428 if ( null !== $scheme_issue ) {
429 $scheme_issue['documents'] = $documents;
430 return $scheme_issue;
431 }
432 return [
433 'stage' => 'ok',
434 'documents' => $documents,
435 'detail' => __( 'The primary discovery documents are served and correct, but the host intercepts the site root\'s /.well-known/ directory before WordPress runs (common on SiteGround shared hosting), and static files could not be published there. Clients that follow the challenge — ChatGPT, Claude — still connect; a client that only derives the root /.well-known/ URL itself may not. If write access to the site root is possible, granting it lets ThinkRank publish static discovery files that fix this completely.', 'thinkrank' ),
436 ];
437 }
438 }
439
440 // Documents agree with us — but they agree on whatever home_url()
441 // says, so a site whose stored URL is http:// while it actually serves
442 // https:// is self-consistently wrong. Clients connect over https and
443 // then reject the http identifier.
444 $scheme_issue = self::probe_scheme();
445 if ( null !== $scheme_issue ) {
446 $scheme_issue['documents'] = $documents;
447 return $scheme_issue;
448 }
449
450 return [
451 'stage' => 'ok',
452 'documents' => $documents,
453 'detail' => __( 'All OAuth discovery documents are served and advertise this site\'s MCP endpoint exactly.', 'thinkrank' ),
454 ];
455 }
456
457 /**
458 * Fetch and validate one discovery document. Appends what was actually
459 * served to $documents either way, so support can read the site's real
460 * responses instead of asking the customer for screenshots.
461 *
462 * @param string $url Document URL.
463 * @param array{key:string,expected:string} $spec Identity field + required value.
464 * @param array<string,mixed> $documents Accumulator (by reference).
465 * @return array{stage:string,documents:array<string,mixed>,detail:string}|null Null when the document is valid.
466 */
467 private static function probe_document( string $url, array $spec, array &$documents ): ?array {
468 $response = wp_remote_get(
469 $url,
470 [
471 'timeout' => 10,
472 'redirection' => 0,
473 ]
474 );
475 if ( is_wp_error( $response ) ) {
476 return [
477 'stage' => 'discovery',
478 'kind' => 'unreachable',
479 'documents' => $documents,
480 'detail' => sprintf(
481 /* translators: 1: discovery document URL, 2: transport error. */
482 __( 'The OAuth discovery document %1$s could not be fetched: %2$s. Clients that connect by URL alone cannot authenticate without it.', 'thinkrank' ),
483 $url,
484 $response->get_error_message()
485 ),
486 ];
487 }
488 $status = (int) wp_remote_retrieve_response_code( $response );
489 $raw = (string) wp_remote_retrieve_body( $response );
490 $body = json_decode( $raw, true );
491 $documents[ $url ] = is_array( $body ) ? $body : $raw;
492
493 if ( 200 !== $status || ! is_array( $body ) || ! isset( $body[ $spec['key'] ] ) ) {
494 return [
495 'stage' => 'discovery',
496 'kind' => 'invalid',
497 'documents' => $documents,
498 'detail' => sprintf(
499 /* translators: 1: discovery document URL, 2: HTTP status code. */
500 __( 'The OAuth discovery document %1$s returned %2$d instead of valid metadata. Re-save Settings → Permalinks; if it persists, the host may be intercepting the URL before WordPress runs, or another plugin may be claiming it.', 'thinkrank' ),
501 $url,
502 $status
503 ),
504 ];
505 }
506
507 $advertised = (string) $body[ $spec['key'] ];
508 if ( $advertised !== $spec['expected'] ) {
509 return [
510 'stage' => 'discovery',
511 'kind' => 'mismatch',
512 'documents' => $documents,
513 'detail' => sprintf(
514 /* translators: 1: metadata field name, 2: value found in the document, 3: value it should be, 4: discovery document URL. */
515 __( 'The discovery document %4$s advertises %1$s "%2$s" but this site\'s MCP endpoint is "%3$s". RFC 9728 requires an exact match, so clients reject the metadata and report that the server does not implement OAuth. If the two differ only by scheme, a reverse proxy is terminating TLS without passing X-Forwarded-Proto; otherwise another plugin is serving this URL.', 'thinkrank' ),
516 $spec['key'],
517 $advertised,
518 $spec['expected'],
519 $url
520 ),
521 ];
522 }
523
524 return null;
525 }
526
527 /**
528 * Catch the reverse-proxy scheme trap: WordPress stores an http:// home
529 * URL, so every advertised OAuth identifier is http://, while the site is
530 * really served over https://. Everything is internally consistent, so no
531 * comparison against our own values can see it — the only tell is that the
532 * https:// variant of the endpoint answers too.
533 *
534 * @return array{stage:string,detail:string}|null Null when nothing is wrong.
535 */
536 private static function probe_scheme(): ?array {
537 $endpoint = Mcp_Pairing::site_endpoint();
538 if ( 'https' === wp_parse_url( $endpoint, PHP_URL_SCHEME ) ) {
539 return null;
540 }
541
542 $secure = set_url_scheme( $endpoint, 'https' );
543 if ( null === self::probe_status( $secure, null ) ) {
544 // No HTTPS at all. A plain-HTTP site is its own (reported) problem,
545 // not the proxy misconfiguration this check is for.
546 return null;
547 }
548
549 return [
550 'stage' => 'discovery',
551 'detail' => sprintf(
552 /* translators: 1: http endpoint URL advertised, 2: https endpoint URL that also answers. */
553 __( 'The discovery documents advertise %1$s, but %2$s answers as well — WordPress is storing an http:// site address behind a proxy that terminates TLS. AI clients connect over https and reject the http identifier as a mismatch. Fix the Site Address in Settings → General, or have the proxy send X-Forwarded-Proto.', 'thinkrank' ),
554 $endpoint,
555 $secure
556 ),
557 ];
558 }
559
560 /**
561 * Confirm an unauthenticated call answers 401 WITH the RFC 9728
562 * WWW-Authenticate challenge. A client that connects by URL alone has
563 * nothing else to discover OAuth from — a bare 401, or any other status,
564 * reads to it as "this server does not implement OAuth".
565 *
566 * @param string $endpoint Pretty endpoint URL.
567 * @param string $fallback REST fallback URL.
568 * @return array{stage:string,detail:string}
569 */
570 private static function probe_challenge( string $endpoint, string $fallback ): array {
571 $answered = false;
572
573 foreach ( [ $endpoint, $fallback ] as $url ) {
574 $response = wp_remote_post(
575 $url,
576 [
577 'timeout' => 10,
578 'redirection' => 0,
579 'headers' => [
580 'Content-Type' => 'application/json',
581 'Accept' => 'application/json',
582 ],
583 'body' => wp_json_encode(
584 [
585 'jsonrpc' => '2.0',
586 'id' => 1,
587 'method' => 'initialize',
588 'params' => [],
589 ]
590 ),
591 ]
592 );
593 if ( is_wp_error( $response ) ) {
594 continue; // Reachability is the other checks' job.
595 }
596 $answered = true;
597
598 $status = (int) wp_remote_retrieve_response_code( $response );
599 $challenge = (string) wp_remote_retrieve_header( $response, 'www-authenticate' );
600
601 if ( 401 !== $status ) {
602 return [
603 'stage' => 'challenge',
604 'detail' => sprintf(
605 /* translators: 1: endpoint URL, 2: HTTP status code. */
606 __( 'An unauthenticated call to %1$s answered %2$d instead of 401. Clients that connect by URL alone need the 401 challenge to start the OAuth flow.', 'thinkrank' ),
607 $url,
608 $status
609 ),
610 ];
611 }
612 if ( '' === $challenge ) {
613 return [
614 'stage' => 'challenge',
615 'detail' => sprintf(
616 /* translators: %s: endpoint URL. */
617 __( '%s answered 401 but sent no WWW-Authenticate header — a security plugin or proxy is likely stripping it. Clients that connect by URL alone will report that this server does not implement OAuth.', 'thinkrank' ),
618 $url
619 ),
620 ];
621 }
622
623 // The challenge is only useful if the URL inside it resolves —
624 // that URL is the client's entire entry point into the flow.
625 if ( ! preg_match( '/resource_metadata="([^"]+)"/i', $challenge, $m ) ) {
626 return [
627 'stage' => 'challenge',
628 'detail' => sprintf(
629 /* translators: 1: endpoint URL, 2: the WWW-Authenticate header value received. */
630 __( '%1$s sent a WWW-Authenticate header with no resource_metadata URL (%2$s). Clients have nowhere to look up this site\'s OAuth metadata.', 'thinkrank' ),
631 $url,
632 $challenge
633 ),
634 ];
635 }
636
637 $metadata_url = $m[1];
638 $metadata = wp_remote_get(
639 $metadata_url,
640 [
641 'timeout' => 10,
642 'redirection' => 2, // A host-level redirect to the real doc is fine.
643 ]
644 );
645 $reachable = ! is_wp_error( $metadata )
646 && 200 === (int) wp_remote_retrieve_response_code( $metadata )
647 && is_array( json_decode( (string) wp_remote_retrieve_body( $metadata ), true ) );
648
649 if ( ! $reachable ) {
650 return [
651 'stage' => 'challenge',
652 'detail' => sprintf(
653 /* translators: 1: resource_metadata URL from the challenge header, 2: endpoint URL. */
654 __( 'The challenge from %2$s points at %1$s, but that URL does not return OAuth metadata. This is the first thing a client fetches, so the connection fails there. A security plugin or edge rule blocking the REST API for visitors is the usual cause.', 'thinkrank' ),
655 $metadata_url,
656 $url
657 ),
658 ];
659 }
660 }
661
662 // Neither URL answered at all. Reporting `ok` here would be the exact
663 // false pass this test exists to prevent — an unreachable endpoint is
664 // not a passing challenge. The other checks name the reachability
665 // failure, so this one only has to refuse to claim success.
666 if ( ! $answered ) {
667 return [
668 'stage' => 'challenge',
669 'detail' => __( 'The OAuth challenge could not be checked because the endpoint did not answer. Fix the connection error above and re-run the test.', 'thinkrank' ),
670 ];
671 }
672
673 return [
674 'stage' => 'ok',
675 'detail' => __( 'Unauthenticated calls answer with the OAuth challenge, so URL-only clients can authenticate.', 'thinkrank' ),
676 ];
677 }
678
679 /**
680 * Detect a host that answers WordPress but refuses AI clients by
681 * User-Agent. Replays the unauthenticated probe under the UAs a real MCP
682 * backend sends and compares against the baseline; a 403/406/503 that the
683 * baseline did not get is a bot filter, not a plugin problem.
684 *
685 * Blind spot worth stating plainly: this runs from the server's own IP,
686 * which host firewalls usually trust, so it catches UA filtering but NOT
687 * an IP-range block of the AI vendor. A green result here does not prove
688 * an external client can connect.
689 *
690 * @param string $endpoint Pretty endpoint URL.
691 * @return array{stage:string,detail:string}|null Null when it could not run.
692 */
693 private static function probe_user_agent( string $endpoint ): ?array {
694 $baseline = self::probe_status( $endpoint, null );
695 if ( null === $baseline ) {
696 return null; // Endpoint unreachable — the other checks own that.
697 }
698
699 foreach ( self::CLIENT_USER_AGENTS as $agent ) {
700 $status = self::probe_status( $endpoint, $agent );
701 if ( null === $status || $status === $baseline ) {
702 continue;
703 }
704 // A different status is only damning when it is a refusal. An MCP
705 // answer (401 challenge / 200 / 202) under any UA is fine.
706 if ( in_array( $status, [ 200, 202, 401 ], true ) ) {
707 continue;
708 }
709 return [
710 'stage' => 'ua_filter',
711 'detail' => sprintf(
712 /* translators: 1: user agent string, 2: HTTP status returned for it, 3: HTTP status returned for WordPress's own user agent. */
713 __( 'The endpoint answered %3$d for WordPress but %2$d for an AI client\'s User-Agent (%1$s). ThinkRank deliberately tests with the generic agents real MCP backends send; this refusal means a security plugin, firewall or host-level "block bad bots" rule (SiteGround\'s edge protection does this) will also refuse the real AI client. Ask the host to exempt the MCP and /.well-known/ paths, or allowlist these User-Agents.', 'thinkrank' ),
714 $agent,
715 $status,
716 $baseline
717 ),
718 ];
719 }
720
721 return [
722 'stage' => 'ok',
723 'detail' => __( 'The endpoint answers AI-client User-Agents the same way it answers WordPress, so no bot filter is blocking them. This cannot see an IP-level block of the AI vendor.', 'thinkrank' ),
724 ];
725 }
726
727 // -- Helpers -----------------------------------------------------------
728
729 /**
730 * Status code of one unauthenticated probe, or null if it never answered.
731 *
732 * @param string $url Endpoint to call.
733 * @param string|null $agent User-Agent to send, or null for WordPress's own.
734 * @return int|null
735 */
736 private static function probe_status( string $url, ?string $agent ): ?int {
737 $args = [
738 'timeout' => 10,
739 'redirection' => 0,
740 'headers' => [
741 'Content-Type' => 'application/json',
742 'Accept' => 'application/json',
743 ],
744 'body' => wp_json_encode(
745 [
746 'jsonrpc' => '2.0',
747 'id' => 1,
748 'method' => 'initialize',
749 'params' => [],
750 ]
751 ),
752 ];
753 if ( null !== $agent ) {
754 $args['user-agent'] = $agent;
755 }
756
757 $response = wp_remote_post( $url, $args );
758 if ( is_wp_error( $response ) ) {
759 return null;
760 }
761 return (int) wp_remote_retrieve_response_code( $response );
762 }
763
764 /**
765 * Shape one check for the UI list.
766 *
767 * @param string $id Check id.
768 * @param string $label Human label.
769 * @param string $stage Resulting stage ('ok' when it passed).
770 * @param string $detail Explanatory line.
771 * @return array{id:string,label:string,ok:bool,detail:string}
772 */
773 private static function check( string $id, string $label, string $stage, string $detail ): array {
774 return [
775 'id' => $id,
776 'label' => $label,
777 'ok' => 'ok' === $stage,
778 'detail' => $detail,
779 ];
780 }
781 }
782