Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Offer sign-in inside ChatGPT conversations (#431)

Paulo Castellano04f3355ae16f
diff --git a/AGENTS.md b/AGENTS.md
index 36b317f52..5f9131726 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -852,6 +852,16 @@ A controller serves **one resource**. Network-specific endpoints never pile up i
`tools/list` returns every tool in a single response (owner decision October 2026): some MCP clients do not follow `nextCursor` and silently see only the first page. `TryPostServer` sets both `defaultPaginationLength` and `maxPaginationLength` to 200; laravel/mcp uses the smaller of the two, so raising only the default does nothing (the package's max is 50). The same page size applies to `resources/list`, `resources/templates/list` and `prompts/list`. Raise both before the server reaches 200 tools. A client may still ask for a smaller page (`per_page`, a laravel/mcp extension; the MCP spec only defines `cursor`) and follow `nextCursor`; a bigger request is capped at 200. `tests/Feature/Mcp/ToolListPaginationTest.php` calls the real endpoint and fails when the list is split.
+## MCP sign-in inside ChatGPT
+
+ChatGPT offers sign-in inside the conversation when a user who never connected (or whose token expired) asks for something (owner decision October 2026). Every other MCP client, Claude included, keeps the plain flow: a 401 on any request without a token, so it signs in when it connects. Claude stays there on purpose: it shows "Connect to Claude" on the connector page, and its own Connect card already appears in the chat when a token expires, because a tool call gets a 401. Giving Claude the anonymous discovery below would stop it from asking to sign in when the connector is added.
+
+- **Recognising ChatGPT** goes through `App\Support\Mcp\ChatGptMcpClient::matches()`, by the egress ranges OpenAI publishes, the identification OpenAI documents: `chatgpt-connectors.json` (`trypost.mcp_chatgpt_ip_ranges_url`), read by `ListChatGptEgressRanges` on the first request that needs it and cached for an hour (a failed read for a minute); only valid IPv4 ranges of /8 or narrower are kept. Never by user agent: it is undocumented, and a local client sending the same one would lose its sign-in on connect. The IP is a hint, not a security boundary: behind `trustProxies(at: '*')` a client can fake it with `X-Forwarded-For`, which only lets it read the public tool list.
+- **Without a token, ChatGPT may only connect and list tools** (`initialize`, `notifications/initialized`, `ping`, `tools/list`), through `AuthenticateMcp` and `LoadMcpWorkspace` (the MCP route's own workspace middleware: it lets that discovery through and hands every other request to the shared `LoadWorkspaceFromToken` with `mcp`, which the MCP change leaves untouched). A tool call always needs a token, so no tool ever runs without a user. A request that carries a token, valid or not, is always authenticated; Passport blanks the `Authorization` header when it refuses a token, so `AuthenticateMcp` records `ChatGptMcpClient::TOKEN_SENT` before it runs.
+- **A refused tool call from ChatGPT** gets `ChallengeChatGptToolCalls`'s 200 tool result with `isError` and `_meta["mcp/www_authenticate"]`: ChatGPT never shows its sign-in prompt for a 401. 402 and 403 are unchanged.
+- **Every tool declares `securitySchemes`** (`oauth2`, `mcp:use`) through `ListToolsWithSecuritySchemes`; ChatGPT offers sign-in only for tools that declare it, other clients ignore it.
+- `tests/Feature/Mcp/ChatGptSignInTest.php` covers ChatGPT, Claude and other clients with no token, an invalid token and a valid one, and the cached ranges; every guard there fails its test when removed.
+
## MCP tool annotations
**Every MCP tool declares all three annotations explicitly, `false` included** (owner decision October 2026): `#[IsReadOnly(bool)]`, `#[IsDestructive(bool)]` and `#[IsOpenWorld(bool)]`, above its `#[Description]`. The OpenAI plugin directory refuses ("Not live") any tool without three explicit booleans, and the Claude directory requires `readOnlyHint` or `destructiveHint`. Annotations only describe the tool to the AI client (when to ask the user for confirmation); they never change what it does and are not rate limits.
diff --git a/app/Actions/Mcp/ListChatGptEgressRanges.php b/app/Actions/Mcp/ListChatGptEgressRanges.php
new file mode 100644
index 000000000..d9daf652a
--- /dev/null
+++ b/app/Actions/Mcp/ListChatGptEgressRanges.php
@@ -0,0 +1,74 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\Mcp;
+
+use DateTimeInterface;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
+
+class ListChatGptEgressRanges
+{
+ private const CACHE_KEY = 'mcp.chatgpt_egress_ranges';
+
+ private const TIMEOUT_SECONDS = 3;
+
+ /**
+ * The widest range kept from OpenAI's list: a wider one would take
+ * unrelated clients for ChatGPT.
+ */
+ private const MIN_PREFIX_LENGTH = 8;
+
+ private const MAX_PREFIX_LENGTH = 32;
+
+ /**
+ * The IPv4 ranges ChatGPT calls MCP servers from, read from OpenAI's
+ * published list and kept for an hour. A failed read answers no ranges,
+ * so ChatGPT is treated like any client, and is retried after a minute.
+ *
+ * @return list<string>
+ */
+ public static function execute(): array
+ {
+ return Cache::remember(
+ self::CACHE_KEY,
+ fn (array $ranges): DateTimeInterface => filled($ranges) ? now()->addHour() : now()->addMinute(),
+ fn (): array => self::read(),
+ );
+ }
+
+ /**
+ * @return list<string>
+ */
+ private static function read(): array
+ {
+ $prefixes = rescue(
+ fn (): mixed => Http::timeout(self::TIMEOUT_SECONDS)
+ ->get(config('trypost.mcp_chatgpt_ip_ranges_url'))
+ ->throw()
+ ->json('prefixes', []),
+ [],
+ report: false,
+ );
+
+ return collect($prefixes)
+ ->pluck('ipv4Prefix')
+ ->filter(self::isValidRange(...))
+ ->values()
+ ->all();
+ }
+
+ private static function isValidRange(mixed $range): bool
+ {
+ if (! is_string($range)) {
+ return false;
+ }
+
+ return filter_var(Str::before($range, '/'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false
+ && filter_var(Str::after($range, '/'), FILTER_VALIDATE_INT, [
+ 'options' => ['min_range' => self::MIN_PREFIX_LENGTH, 'max_range' => self::MAX_PREFIX_LENGTH],
+ ]) !== false;
+ }
+}
diff --git a/app/Http/Middleware/Mcp/AuthenticateMcp.php b/app/Http/Middleware/Mcp/AuthenticateMcp.php
new file mode 100644
index 000000000..01c459888
--- /dev/null
+++ b/app/Http/Middleware/Mcp/AuthenticateMcp.php
@@ -0,0 +1,40 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Middleware\Mcp;
+
+use App\Support\Mcp\ChatGptMcpClient;
+use Closure;
+use Illuminate\Auth\Middleware\Authenticate;
+use Illuminate\Http\Request;
+
+class AuthenticateMcp extends Authenticate
+{
+ /**
+ * @param Request $request
+ */
+ public function handle($request, Closure $next, ...$guards): mixed
+ {
+ $request->attributes->set(ChatGptMcpClient::TOKEN_SENT, filled($request->bearerToken()));
+
+ return parent::handle($request, $next, ...$guards);
+ }
+
+ /**
+ * ChatGPT may connect and list tools before the user signs in, so it can
+ * offer sign-in inside the conversation when a tool is called. Every
+ * other client, and every request that carries a token, is refused with
+ * the usual 401.
+ *
+ * @param array<int, string|null> $guards
+ */
+ protected function unauthenticated($request, array $guards): void
+ {
+ if (ChatGptMcpClient::allowsAnonymousDiscovery($request)) {
+ return;
+ }
+
+ parent::unauthenticated($request, $guards);
+ }
+}
diff --git a/app/Http/Middleware/Mcp/ChallengeChatGptToolCalls.php b/app/Http/Middleware/Mcp/ChallengeChatGptToolCalls.php
new file mode 100644
index 000000000..7c4876fd3
--- /dev/null
+++ b/app/Http/Middleware/Mcp/ChallengeChatGptToolCalls.php
@@ -0,0 +1,57 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Middleware\Mcp;
+
+use App\Support\Mcp\ChatGptMcpClient;
+use Closure;
+use Illuminate\Http\Request;
+use Laravel\Mcp\Transport\JsonRpcRequest;
+use Laravel\Mcp\Transport\JsonRpcResponse;
+use Symfony\Component\HttpFoundation\Response;
+
+class ChallengeChatGptToolCalls
+{
+ private const MESSAGE = 'Sign in to TryPost to continue.';
+
+ /**
+ * ChatGPT shows its sign-in prompt in the conversation only for a tool
+ * result carrying _meta["mcp/www_authenticate"], never for an HTTP 401
+ * (https://developers.openai.com/plugins/build/auth). A refused tool
+ * call from ChatGPT is answered in that shape; every other client keeps
+ * the 401 it signs in from.
+ */
+ public function handle(Request $request, Closure $next): Response
+ {
+ $response = $next($request);
+
+ if ($response->getStatusCode() !== Response::HTTP_UNAUTHORIZED || ! ChatGptMcpClient::matches($request)) {
+ return $response;
+ }
+
+ $call = rescue(fn (): JsonRpcRequest => JsonRpcRequest::from($request->json()->all()), report: false);
+
+ if ($call?->method !== 'tools/call') {
+ return $response;
+ }
+
+ return response()->json($this->signInPrompt($call, $request)->toArray());
+ }
+
+ private function signInPrompt(JsonRpcRequest $call, Request $request): JsonRpcResponse
+ {
+ $message = self::MESSAGE;
+ $resourceMetadata = route('mcp.oauth.protected-resource.nested', ['path' => $request->path()]);
+
+ return JsonRpcResponse::result($call->id, [
+ 'content' => [['type' => 'text', 'text' => $message]],
+ 'isError' => true,
+ '_meta' => [
+ 'mcp/www_authenticate' => [
+ "Bearer resource_metadata=\"{$resourceMetadata}\", error=\"insufficient_scope\", error_description=\"{$message}\"",
+ ],
+ ],
+ ]);
+ }
+}
diff --git a/app/Http/Middleware/Mcp/LoadMcpWorkspace.php b/app/Http/Middleware/Mcp/LoadMcpWorkspace.php
new file mode 100644
index 000000000..f486fc7f8
--- /dev/null
+++ b/app/Http/Middleware/Mcp/LoadMcpWorkspace.php
@@ -0,0 +1,30 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Middleware\Mcp;
+
+use App\Http\Middleware\Api\LoadWorkspaceFromToken;
+use App\Support\Mcp\ChatGptMcpClient;
+use Closure;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+class LoadMcpWorkspace
+{
+ public function __construct(private readonly LoadWorkspaceFromToken $loadWorkspace) {}
+
+ /**
+ * ChatGPT connecting or listing tools before the user signs in has no
+ * token and so no workspace; every other MCP request loads the workspace
+ * its token was issued for, like the API does.
+ */
+ public function handle(Request $request, Closure $next): Response
+ {
+ if (blank($request->user()) && ChatGptMcpClient::allowsAnonymousDiscovery($request)) {
+ return $next($request);
+ }
+
+ return $this->loadWorkspace->handle($request, $next, 'mcp');
+ }
+}
diff --git a/app/Mcp/Methods/ListToolsWithSecuritySchemes.php b/app/Mcp/Methods/ListToolsWithSecuritySchemes.php
new file mode 100644
index 000000000..ebad714c2
--- /dev/null
+++ b/app/Mcp/Methods/ListToolsWithSecuritySchemes.php
@@ -0,0 +1,33 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Mcp\Methods;
+
+use Laravel\Mcp\Server\Methods\ListTools;
+use Laravel\Mcp\Server\ServerContext;
+use Laravel\Mcp\Transport\JsonRpcRequest;
+use Laravel\Mcp\Transport\JsonRpcResponse;
+
+class ListToolsWithSecuritySchemes extends ListTools
+{
+ /**
+ * Every tool needs the user's account, so each one declares OAuth with
+ * the mcp:use scope. ChatGPT offers sign-in in the conversation only for
+ * tools that declare it (https://developers.openai.com/plugins/build/auth);
+ * other clients ignore the field.
+ */
+ public function handle(JsonRpcRequest $request, ServerContext $context): JsonRpcResponse
+ {
+ $result = data_get(parent::handle($request, $context)->toArray(), 'result', []);
+
+ data_set($result, 'tools', collect(data_get($result, 'tools', []))
+ ->map(fn (array $tool): array => [
+ ...$tool,
+ 'securitySchemes' => [['type' => 'oauth2', 'scopes' => ['mcp:use']]],
+ ])
+ ->all());
+
+ return JsonRpcResponse::result($request->id, $result);
+ }
+}
diff --git a/app/Mcp/Servers/TryPostServer.php b/app/Mcp/Servers/TryPostServer.php
index 40afad8e5..e7a302ee5 100644
--- a/app/Mcp/Servers/TryPostServer.php
+++ b/app/Mcp/Servers/TryPostServer.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Mcp\Servers;
+use App\Mcp\Methods\ListToolsWithSecuritySchemes;
use App\Mcp\Tools\Analytics\GetAnalyticsPublicationTool;
use App\Mcp\Tools\Analytics\GetAnalyticsReportTool;
use App\Mcp\Tools\Analytics\GetChannelInsightsTool;
@@ -202,4 +203,9 @@ class TryPostServer extends Server
protected array $resources = [];
protected array $prompts = [];
+
+ protected function boot(): void
+ {
+ $this->addMethod('tools/list', ListToolsWithSecuritySchemes::class);
+ }
}
diff --git a/app/Support/Mcp/ChatGptMcpClient.php b/app/Support/Mcp/ChatGptMcpClient.php
new file mode 100644
index 000000000..cb54fc428
--- /dev/null
+++ b/app/Support/Mcp/ChatGptMcpClient.php
@@ -0,0 +1,45 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Support\Mcp;
+
+use App\Actions\Mcp\ListChatGptEgressRanges;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\IpUtils;
+
+class ChatGptMcpClient
+{
+ /**
+ * JSON-RPC methods ChatGPT may call without a token: connecting and
+ * reading the tool list. A tool call always needs a token.
+ */
+ private const DISCOVERY_METHODS = ['initialize', 'notifications/initialized', 'ping', 'tools/list'];
+
+ /**
+ * Passport blanks the Authorization header when it refuses a token, so
+ * whether the client sent one is recorded before authentication runs.
+ */
+ public const TOKEN_SENT = 'mcp.token_sent';
+
+ /**
+ * ChatGPT, told by the egress ranges OpenAI publishes, the identification
+ * OpenAI documents. Any other client, Claude and local ones included,
+ * keeps the plain OAuth flow.
+ */
+ public static function matches(Request $request): bool
+ {
+ return IpUtils::checkIp((string) $request->ip(), ListChatGptEgressRanges::execute());
+ }
+
+ /**
+ * ChatGPT connecting or listing tools before the user signed in. A
+ * request that carries a token, valid or not, is always authenticated.
+ */
+ public static function allowsAnonymousDiscovery(Request $request): bool
+ {
+ return ! $request->attributes->get(self::TOKEN_SENT, filled($request->bearerToken()))
+ && collect(self::DISCOVERY_METHODS)->containsStrict($request->json('method'))
+ && self::matches($request);
+ }
+}
diff --git a/config/trypost.php b/config/trypost.php
index bca461521..ee9281671 100644
--- a/config/trypost.php
+++ b/config/trypost.php
@@ -64,6 +64,21 @@ return [
'openai-apps-challenge' => env('OPENAI_APPS_CHALLENGE'),
],
+ /*
+ |--------------------------------------------------------------------------
+ | ChatGPT MCP egress ranges
+ |--------------------------------------------------------------------------
+ |
+ | ChatGPT calls the MCP server from the ranges OpenAI publishes
+ | (https://developers.openai.com/api/docs/guides/ip-addresses). From
+ | there, a request without a token may list the tools, and a tool call
+ | is answered with the sign-in prompt ChatGPT shows in the conversation.
+ | Every other client keeps the plain 401.
+ |
+ */
+
+ 'mcp_chatgpt_ip_ranges_url' => env('MCP_CHATGPT_IP_RANGES_URL', 'https://openai.com/chatgpt-connectors.json'),
+
/*
|--------------------------------------------------------------------------
| Meta page walk budget
diff --git a/routes/ai.php b/routes/ai.php
index f615815e4..8dce487cd 100644
--- a/routes/ai.php
+++ b/routes/ai.php
@@ -2,6 +2,9 @@
declare(strict_types=1);
+use App\Http\Middleware\Mcp\AuthenticateMcp;
+use App\Http\Middleware\Mcp\ChallengeChatGptToolCalls;
+use App\Http\Middleware\Mcp\LoadMcpWorkspace;
use App\Mcp\Servers\TryPostServer;
use Illuminate\Support\Facades\Route;
use Laravel\Mcp\Facades\Mcp;
@@ -11,5 +14,5 @@ Route::middleware('throttle:mcp-oauth-registration')->group(function () {
});
Mcp::web('/mcp/trypost', TryPostServer::class)
- ->middleware(['auth:api', 'workspace.token:mcp'])
+ ->middleware([ChallengeChatGptToolCalls::class, AuthenticateMcp::class.':api', LoadMcpWorkspace::class])
->name('mcp.trypost');
diff --git a/tests/Feature/Mcp/ChatGptSignInTest.php b/tests/Feature/Mcp/ChatGptSignInTest.php
new file mode 100644
index 000000000..f25758799
--- /dev/null
+++ b/tests/Feature/Mcp/ChatGptSignInTest.php
@@ -0,0 +1,252 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Mcp\Servers\TryPostServer;
+use Illuminate\Http\Client\Request as HttpClientRequest;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Testing\TestResponse;
+
+const CHATGPT_SIGN_IN_CLAUDE_IP = '160.79.104.10';
+const CHATGPT_SIGN_IN_CHATGPT_IP = '203.0.113.5';
+const CHATGPT_SIGN_IN_OTHER_IP = '198.51.100.7';
+
+beforeEach(function () {
+ fakeChatGptEgressRanges(['203.0.113.0/24']);
+
+ $result = createApiTestToken();
+ subscribeAccount($result['user']->account);
+
+ $this->user = $result['user'];
+ $this->workspace = $result['workspace'];
+ $this->registeredTools = count((new ReflectionClass(TryPostServer::class))->getDefaultProperties()['tools']);
+});
+
+/**
+ * @param array<string, mixed> $params
+ */
+function chatGptSignInRequest(object $test, string $method, array $params = [], string $ip = CHATGPT_SIGN_IN_OTHER_IP, ?string $token = null, string $userAgent = 'test-client', bool $notification = false): TestResponse
+{
+ return $test->withServerVariables(['REMOTE_ADDR' => $ip])
+ ->withHeaders(array_filter([
+ 'Authorization' => $token ? "Bearer {$token}" : null,
+ 'Accept' => 'application/json, text/event-stream',
+ 'User-Agent' => $userAgent,
+ ]))
+ ->postJson(route('mcp.trypost'), array_filter([
+ 'jsonrpc' => '2.0',
+ 'id' => $notification ? null : 7,
+ 'method' => $method,
+ 'params' => (object) $params,
+ ], fn (mixed $value): bool => $value !== null));
+}
+
+/**
+ * @return array<string, mixed>
+ */
+function chatGptSignInInitializeParams(): array
+{
+ return [
+ 'protocolVersion' => '2025-03-26',
+ 'capabilities' => (object) [],
+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],
+ ];
+}
+
+/**
+ * @return array<string, mixed>
+ */
+function chatGptSignInToolCall(): array
+{
+ return ['name' => 'get-workspace-tool', 'arguments' => (object) []];
+}
+
+function chatGptSignInAssertOAuthChallenge(TestResponse $response): void
+{
+ $response->assertUnauthorized();
+
+ expect($response->headers->get('WWW-Authenticate'))
+ ->toContain('resource_metadata="'.route('mcp.oauth.protected-resource.nested', ['path' => 'mcp/trypost']).'"');
+}
+
+function chatGptSignInAssertChatGptChallenge(TestResponse $response): void
+{
+ $response->assertOk();
+
+ $challenge = $response->json('result._meta')['mcp/www_authenticate'][0];
+
+ expect($response->json('id'))->toBe(7)
+ ->and($response->json('result.isError'))->toBeTrue()
+ ->and($response->json('result.content.0.text'))->toBe('Sign in to TryPost to continue.')
+ ->and($challenge)->toStartWith('Bearer ')
+ ->toContain('resource_metadata="'.route('mcp.oauth.protected-resource.nested', ['path' => 'mcp/trypost']).'"')
+ ->toContain('error="insufficient_scope"')
+ ->toContain('error_description="Sign in to TryPost to continue."');
+}
+
+function chatGptSignInRangeReads(): int
+{
+ return Http::recorded(fn (HttpClientRequest $request): bool => $request->url() === config('trypost.mcp_chatgpt_ip_ranges_url'))->count();
+}
+
+describe('custom MCP clients keep the plain OAuth flow', function () {
+ test('every request without a token is refused with a 401 challenge', function (string $method, array $params) {
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, $method, $params));
+ })->with([
+ 'initialize' => ['initialize', chatGptSignInInitializeParams()],
+ 'ping' => ['ping', []],
+ 'tools/list' => ['tools/list', []],
+ 'tools/call' => ['tools/call', chatGptSignInToolCall()],
+ ]);
+
+ test('a client that only claims to be ChatGPT in its clientInfo is still refused', function () {
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'initialize', [...chatGptSignInInitializeParams(), 'clientInfo' => ['name' => 'openai-mcp', 'version' => '1.0']]));
+ });
+
+ test('a client is not taken for ChatGPT by its user agent', function (string $userAgent) {
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), userAgent: $userAgent));
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'tools/call', chatGptSignInToolCall(), userAgent: $userAgent));
+ })->with([
+ 'openai-mcp' => ['openai-mcp/1.0.0'],
+ 'ChatGPT-User' => ['Mozilla/5.0 (compatible; ChatGPT-User/1.0; +https://openai.com/bot)'],
+ ]);
+});
+
+describe('Claude keeps the plain OAuth flow', function () {
+ test('every request without a token is refused with the 401 Claude signs in from', function (string $method, array $params) {
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, $method, $params, CHATGPT_SIGN_IN_CLAUDE_IP));
+ })->with([
+ 'initialize' => ['initialize', chatGptSignInInitializeParams()],
+ 'ping' => ['ping', []],
+ 'tools/list' => ['tools/list', []],
+ 'tools/call' => ['tools/call', chatGptSignInToolCall()],
+ ]);
+});
+
+describe('ChatGPT connects without a token and signs in from the conversation', function () {
+ test('connecting and listing tools answer without a token, with the OAuth security scheme', function () {
+ chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk()->assertJsonPath('result.serverInfo.name', 'TryPost');
+ chatGptSignInRequest($this, 'notifications/initialized', ip: CHATGPT_SIGN_IN_CHATGPT_IP, notification: true)->assertAccepted();
+ chatGptSignInRequest($this, 'ping', ip: CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+
+ $tools = chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk()->json('result.tools');
+
+ expect($tools)->toHaveCount($this->registeredTools)
+ ->each(fn ($tool) => $tool->securitySchemes->toBe([['type' => 'oauth2', 'scopes' => ['mcp:use']]]));
+ });
+
+ test('a tool call without a valid token answers the sign-in prompt ChatGPT shows', function (?string $token) {
+ chatGptSignInAssertChatGptChallenge(chatGptSignInRequest($this, 'tools/call', chatGptSignInToolCall(), CHATGPT_SIGN_IN_CHATGPT_IP, token: $token));
+ })->with([
+ 'no token' => [null],
+ 'invalid token' => ['not-a-real-token'],
+ ]);
+
+ test('anything but connecting and listing tools is refused without a token', function (string $method, array $params) {
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, $method, $params, CHATGPT_SIGN_IN_CHATGPT_IP));
+ })->with([
+ 'resources/list' => ['resources/list', []],
+ 'prompts/list' => ['prompts/list', []],
+ ]);
+
+ test('a request with an invalid token is refused with a 401, even to connect', function () {
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), CHATGPT_SIGN_IN_CHATGPT_IP, token: 'not-a-real-token'));
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP, token: 'not-a-real-token'));
+ });
+
+ test('a tool call without a usable id keeps the 401', function (mixed $id) {
+ $response = $this->withServerVariables(['REMOTE_ADDR' => CHATGPT_SIGN_IN_CHATGPT_IP])
+ ->withHeaders(['Accept' => 'application/json, text/event-stream'])
+ ->postJson(route('mcp.trypost'), ['jsonrpc' => '2.0', 'id' => $id, 'method' => 'tools/call', 'params' => chatGptSignInToolCall()]);
+
+ chatGptSignInAssertOAuthChallenge($response);
+ })->with([
+ 'null' => [null],
+ 'object' => [['nested' => 1]],
+ ]);
+
+ test('a tool call with an expired token answers the sign-in prompt', function () {
+ $issued = mcpBearerToken($this->user, $this->workspace);
+ $issued['token']->forceFill(['expires_at' => now()->subMinute()])->save();
+
+ chatGptSignInAssertChatGptChallenge(chatGptSignInRequest($this, 'tools/call', chatGptSignInToolCall(), CHATGPT_SIGN_IN_CHATGPT_IP, $issued['plain_token']));
+ });
+});
+
+describe('OpenAI\'s published ranges', function () {
+ test('are read once and kept for an hour', function () {
+ chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+ chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+
+ $this->travel(59)->minutes();
+ chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+
+ expect(chatGptSignInRangeReads())->toBe(1);
+
+ $this->travel(2)->minutes();
+ chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+
+ expect(chatGptSignInRangeReads())->toBe(2);
+ });
+
+ test('are not read for a request that carries a token', function () {
+ $token = mcpBearerToken($this->user, $this->workspace)['plain_token'];
+
+ chatGptSignInRequest($this, 'tools/list', [], CHATGPT_SIGN_IN_CHATGPT_IP, $token)->assertOk();
+
+ expect(chatGptSignInRangeReads())->toBe(0);
+ });
+
+ test('a failed read treats ChatGPT like any client and is retried after a minute', function () {
+ fakeChatGptEgressRanges(null);
+
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), CHATGPT_SIGN_IN_CHATGPT_IP));
+
+ fakeChatGptEgressRanges(['203.0.113.0/24']);
+ $this->travel(2)->minutes();
+
+ chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+ });
+
+ test('only valid IPv4 ranges of /8 or narrower are kept', function () {
+ fakeChatGptEgressRanges(['0.0.0.0/0', '10.0.0.0/4', '198.51.100.0/24abc', '198.51.100.0', '198.51.100.0/33', 'not-a-range', '999.1.1.1/24', ['203.0.113.0/24'], '203.0.113.0/24']);
+
+ chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), CHATGPT_SIGN_IN_CHATGPT_IP)->assertOk();
+ chatGptSignInAssertOAuthChallenge(chatGptSignInRequest($this, 'initialize', chatGptSignInInitializeParams(), CHATGPT_SIGN_IN_OTHER_IP));
+ });
+});
+
+describe('a signed-in user gets the same answers from every client', function () {
+ test('a tool call runs normally', function (string $ip) {
+ $token = mcpBearerToken($this->user, $this->workspace)['plain_token'];
+
+ chatGptSignInRequest($this, 'tools/call', chatGptSignInToolCall(), $ip, $token)
+ ->assertOk()
+ ->assertJsonPath('result.isError', false);
+ })->with([
+ 'custom client' => [CHATGPT_SIGN_IN_OTHER_IP],
+ 'Claude' => [CHATGPT_SIGN_IN_CLAUDE_IP],
+ 'ChatGPT' => [CHATGPT_SIGN_IN_CHATGPT_IP],
+ ]);
+
+ test('an account without a subscription still gets the 402', function (string $ip) {
+ config(['trypost.self_hosted' => false, 'trypost.billing.require_card_for_trial' => true]);
+ $unsubscribed = createApiTestToken();
+ $token = mcpBearerToken($unsubscribed['user'], $unsubscribed['workspace'])['plain_token'];
+
+ chatGptSignInRequest($this, 'tools/call', chatGptSignInToolCall(), $ip, $token)->assertPaymentRequired();
+ })->with([
+ 'custom client' => [CHATGPT_SIGN_IN_OTHER_IP],
+ 'Claude' => [CHATGPT_SIGN_IN_CLAUDE_IP],
+ 'ChatGPT' => [CHATGPT_SIGN_IN_CHATGPT_IP],
+ ]);
+
+ test('every listed tool declares the OAuth security scheme', function () {
+ $token = mcpBearerToken($this->user, $this->workspace)['plain_token'];
+
+ $tools = chatGptSignInRequest($this, 'tools/list', [], token: $token)->assertOk()->json('result.tools');
+
+ expect($tools)->toHaveCount($this->registeredTools)
+ ->each(fn ($tool) => $tool->securitySchemes->toBe([['type' => 'oauth2', 'scopes' => ['mcp:use']]]));
+ });
+});
diff --git a/tests/Pest.php b/tests/Pest.php
index f487e4125..7c3ac6754 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -40,6 +40,7 @@ pest()->extend(TestCase::class)
->beforeEach(function (): void {
Http::preventStrayRequests();
fakePwnedPasswords();
+ fakeChatGptEgressRanges();
Queue::fake([BootstrapAccountAnalytics::class]);
})
->in('Feature', 'Unit');
@@ -130,6 +131,26 @@ function fakePwnedPasswords(): void
]);
}
+/**
+ * OpenAI's published ChatGPT egress ranges, answered from the
+ * testing.chatgpt_egress_ranges config so a test can change them after the
+ * global fake is registered. null answers a failed read.
+ *
+ * @param list<mixed>|null $ranges
+ */
+function fakeChatGptEgressRanges(?array $ranges = []): void
+{
+ config(['testing.chatgpt_egress_ranges' => $ranges]);
+
+ Http::fake([
+ config('trypost.mcp_chatgpt_ip_ranges_url') => fn () => config('testing.chatgpt_egress_ranges') === null
+ ? Http::response('', 500)
+ : Http::response([
+ 'prefixes' => collect(config('testing.chatgpt_egress_ranges'))->map(fn (mixed $range): array => ['ipv4Prefix' => $range])->all(),
+ ]),
+ ]);
+}
+
function passportToken(User $user, Workspace $workspace, array $scopes = []): string
{
$result = $user->createToken('Test', $scopes);