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.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Rate limit the MCP endpoint per token, by the minute and by the hour (#518)
David Idrisb569076fc8cf
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.phpindex 4d51069b7..af3668226 100644--- a/app/Providers/AppServiceProvider.php+++ b/app/Providers/AppServiceProvider.php@@ -188,6 +188,8 @@ class AppServiceProvider extends ServiceProviderreturn Limit::perMinute(60)->by($key);});+ RateLimiter::for('mcp', fn (Request $request): array => $this->mcpLimits($request));+RateLimiter::for('mcp-oauth',fn (Request $request): Limit => $request->isMethodCacheable()@@ -254,6 +256,30 @@ class AppServiceProvider extends ServiceProvider});}+ /**+ * Each MCP token (one AI client, for one user, in one workspace) has its+ * own budget, so ChatGPT's and Claude's shared addresses and a busy+ * teammate never spend anyone else's. ChatGPT listing the tools before+ * sign-in carries no token and is never limited.+ *+ * @return list<Limit>+ */+ private function mcpLimits(Request $request): array+ {+ $user = $request->user();++ if (blank($user) || ! $this->app->isProduction()) {+ return [];+ }++ $token = $user->token()->oauth_access_token_id;++ return [+ Limit::perMinute(config()->integer('trypost.mcp_requests_per_minute'))->by("minute:{$token}"),+ Limit::perHour(config()->integer('trypost.mcp_requests_per_hour'))->by("hour:{$token}"),+ ];+ }+protected function configureSocialite(): void{// Google Auth (login/signup) - separate from YouTube OAuthdiff --git a/config/trypost.php b/config/trypost.phpindex a868db244..fee505ece 100644--- a/config/trypost.php+++ b/config/trypost.php@@ -115,6 +115,19 @@ return ['mcp_claude_ip_ranges' => explode(',', env('MCP_CLAUDE_IP_RANGES', '160.79.104.0/21')),+ /*+ |--------------------------------------------------------------------------+ | MCP rate limit+ |--------------------------------------------------------------------------+ |+ | Requests one MCP token (one AI client, for one user, in one workspace)+ | may send to the MCP server. The REST API counts apart.+ |+ */++ 'mcp_requests_per_minute' => (int) env('MCP_REQUESTS_PER_MINUTE', 240),+ 'mcp_requests_per_hour' => (int) env('MCP_REQUESTS_PER_HOUR', 2400),+/*|--------------------------------------------------------------------------| Meta page walk budgetdiff --git a/routes/ai.php b/routes/ai.phpindex 1b4134e9a..91c93844a 100644--- a/routes/ai.php+++ b/routes/ai.php@@ -12,5 +12,5 @@ use Laravel\Mcp\Facades\Mcp;Route::middleware('throttle:mcp-oauth')->group(fn () => Mcp::oauthRoutes());Mcp::web('/mcp/trypost', TryPostServer::class)- ->middleware([ChallengeChatGptToolCalls::class, AuthenticateMcp::class.':api', LoadMcpWorkspace::class])+ ->middleware([ChallengeChatGptToolCalls::class, AuthenticateMcp::class.':api', LoadMcpWorkspace::class, 'throttle:mcp'])->name('mcp.trypost');diff --git a/tests/Feature/Mcp/McpRateLimitTest.php b/tests/Feature/Mcp/McpRateLimitTest.phpnew file mode 100644index 000000000..7f7e69992--- /dev/null+++ b/tests/Feature/Mcp/McpRateLimitTest.php@@ -0,0 +1,159 @@+<?php++declare(strict_types=1);++use App\Enums\Mcp\Method;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Arr;+use Illuminate\Support\Collection;+use Illuminate\Testing\TestResponse;+use Tests\TestCase;++const MCP_RATE_LIMIT_CHATGPT_IP = '203.0.113.5';++beforeEach(function () {+ app()->detectEnvironment(fn (): string => 'production');+ fakeChatGptEgressRanges(['203.0.113.0/24']);++ config([+ 'trypost.mcp_requests_per_minute' => 3,+ 'trypost.mcp_requests_per_hour' => 5,+ ]);+});++/**+ * A subscribed user and their workspace.+ *+ * @return array{user: User, workspace: Workspace}+ */+function mcpRateLimitWorkspace(): array+{+ ['user' => $user, 'workspace' => $workspace] = createApiTestToken();+ subscribeAccount($user->account);++ return ['user' => $user, 'workspace' => $workspace];+}++function mcpRateLimitToken(User $user, Workspace $workspace): string+{+ return mcpBearerToken($user, $workspace, clientName: 'Claude')['plain_token'];+}++/**+ * @param array<string, mixed> $params+ */+function mcpRateLimitCall(TestCase $test, ?string $token, Method $method = Method::Ping, array $params = [], ?string $ip = null): TestResponse+{+ auth()->forgetGuards();++ return $test->withServerVariables(Arr::whereNotNull(['REMOTE_ADDR' => $ip]))+ ->withHeaders(Arr::whereNotNull([+ 'Authorization' => transform($token, fn (string $token): string => "Bearer {$token}"),+ 'Accept' => 'application/json, text/event-stream',+ ]))+ ->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => $method->value,+ 'params' => (object) $params,+ ]);+}++function mcpRateLimitSpend(TestCase $test, string $token, int $requests): void+{+ Collection::times($requests, fn () => mcpRateLimitCall($test, $token)->assertOk());+}++test('a tool call past the minute limit is refused with 429 and Retry-After', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();+ $token = mcpRateLimitToken($user, $workspace);++ mcpRateLimitSpend($this, $token, 3);++ $response = mcpRateLimitCall($this, $token, Method::ToolsCall, ['name' => 'get-workspace-tool', 'arguments' => (object) []]);++ $response->assertTooManyRequests();++ expect((int) $response->headers->get('Retry-After'))->toBeBetween(1, 60);+});++test('the minute limit lifts once the minute is over', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();+ $token = mcpRateLimitToken($user, $workspace);++ mcpRateLimitSpend($this, $token, 3);+ mcpRateLimitCall($this, $token)->assertTooManyRequests();++ $this->travel(61)->seconds();++ mcpRateLimitCall($this, $token)->assertOk();+});++test('the hour limit holds across minutes until the hour is over', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();+ $token = mcpRateLimitToken($user, $workspace);++ mcpRateLimitSpend($this, $token, 3);+ $this->travel(61)->seconds();+ mcpRateLimitSpend($this, $token, 2);+ $this->travel(61)->seconds();++ mcpRateLimitCall($this, $token)->assertTooManyRequests();++ $this->travel(1)->hours();++ mcpRateLimitCall($this, $token)->assertOk();+});++test('a teammate in the same workspace keeps their own limit', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();++ mcpRateLimitSpend($this, mcpRateLimitToken($user, $workspace), 3);++ mcpRateLimitCall($this, mcpRateLimitToken(workspaceMember($workspace), $workspace))->assertOk();+});++test('requests refused at sign-in do not count', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();+ $token = mcpRateLimitToken($user, $workspace);++ Collection::times(4, fn () => mcpRateLimitCall($this, 'not-a-token')->assertUnauthorized());++ mcpRateLimitCall($this, $token)->assertOk();+});++test('requests refused for the workspace do not count', function () {+ ['workspace' => $workspace] = mcpRateLimitWorkspace();+ $outsider = workspaceOutsider($workspace);+ $token = mcpRateLimitToken($outsider, $workspace);++ Collection::times(4, fn () => mcpRateLimitCall($this, $token)->assertForbidden());++ $workspace->members()->attach($outsider->id, membershipPivot('member'));++ mcpRateLimitCall($this, $token)->assertOk();+});++test('ChatGPT with a token is limited by its token like any client', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();+ $token = mcpRateLimitToken($user, $workspace);++ Collection::times(3, fn () => mcpRateLimitCall($this, $token, ip: MCP_RATE_LIMIT_CHATGPT_IP)->assertOk());++ mcpRateLimitCall($this, $token, Method::ToolsCall, ['name' => 'get-workspace-tool', 'arguments' => (object) []], MCP_RATE_LIMIT_CHATGPT_IP)+ ->assertTooManyRequests();+});++test('ChatGPT listing the tools before sign-in is not limited', function () {+ Collection::times(4, fn () => mcpRateLimitCall($this, null, Method::ToolsList, ip: MCP_RATE_LIMIT_CHATGPT_IP)->assertOk());+});++test('outside production is not limited', function () {+ ['user' => $user, 'workspace' => $workspace] = mcpRateLimitWorkspace();+ $token = mcpRateLimitToken($user, $workspace);++ app()->detectEnvironment(fn (): string => 'staging');++ mcpRateLimitSpend($this, $token, 4);+});diff --git a/tests/Feature/Parity/CrossCuttingParityTest.php b/tests/Feature/Parity/CrossCuttingParityTest.phpindex f0db591d5..d2a8262d7 100644--- a/tests/Feature/Parity/CrossCuttingParityTest.php+++ b/tests/Feature/Parity/CrossCuttingParityTest.php@@ -13,10 +13,13 @@ use App\Models\AccessToken;use App\Models\Post;use App\Models\Repurpose;use App\Models\SocialAccount;+use App\Models\User;use App\Models\Webhook;use App\Models\WorkspaceLabel;use App\Models\WorkspaceSignature;use Illuminate\Database\Eloquent\Factories\Sequence;+use Illuminate\Http\Request;+use Illuminate\Support\Facades\RateLimiter;use Tests\TestCase;beforeEach(function () {@@ -88,3 +91,11 @@ test('a bad label color is rejected by the api, the web and mcp with the same meTryPostServer::actingAs($this->user)->tool(CreateLabelTool::class, $payload)->assertHasErrors([$api->json('errors.color.0')]);});++test('an mcp connection may send at least what the api allows a workspace per minute', function () {+ $request = Request::create(route('api.posts.index'));+ $request->setUserResolver(fn (): User => $this->user);++ expect(config()->integer('trypost.mcp_requests_per_minute'))+ ->toBeGreaterThanOrEqual(RateLimiter::limiter('api')($request)->maxAttempts);+});