Skip to content

Commit cdf58f1

Browse files
author
Nitish Agarwal
committed
feat: implement daily publish rate limiting with atomic operations (modelcontextprotocol#21)
Implements daily rate limiting for server publications to prevent abuse and ensure fair usage of the registry. Publishers are limited to a configurable number of server publications per day (default: 10). ## Features - Daily publish limit enforcement (configurable via RATE_LIMIT_PER_DAY) - Namespace-based isolation for rate limiting - Exemption support with wildcard patterns (e.g., com.anthropic/*) - Atomic check-and-increment operations to prevent race conditions - Comprehensive error messages with guidance for limit increases ## Implementation Details - Added atomic CheckAndIncrementPublishCount to database interface - PostgreSQL: Uses CTE for atomic check-and-increment operations - MemoryDB: Uses mutex-based locking for thread safety - Service layer uses atomic database operations - Rate limits reset daily at midnight UTC ## Configuration - RATE_LIMIT_ENABLED: Enable/disable rate limiting (default: true) - RATE_LIMIT_PER_DAY: Maximum publishes per namespace per day (default: 10) - RATE_LIMIT_EXEMPTIONS: Comma-separated list of exempt namespaces ## Testing - Added comprehensive unit tests for service layer - Added database-level tests for persistence and atomicity - Concurrent testing verifies exact limit enforcement (no race conditions) - Tests cover exemptions, time windows, configuration changes Fixes modelcontextprotocol#21
1 parent 9d63afb commit cdf58f1

10 files changed

Lines changed: 1281 additions & 7 deletions

File tree

‎.env.example‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,14 @@ MCP_REGISTRY_OIDC_EXTRA_CLAIMS=[{"hd":"modelcontextprotocol.io"}]
3939
# Grant admin permissions to OIDC-authenticated users
4040
MCP_REGISTRY_OIDC_EDIT_PERMISSIONS=*
4141
MCP_REGISTRY_OIDC_PUBLISH_PERMISSIONS=*
42+
43+
# Rate Limiting Configuration
44+
# Enable/disable rate limiting for publish operations
45+
MCP_REGISTRY_RATE_LIMIT_ENABLED=true
46+
47+
# Maximum number of servers a namespace can publish per day
48+
MCP_REGISTRY_RATE_LIMIT_PER_DAY=10
49+
50+
# Comma-separated list of namespaces exempt from rate limiting
51+
# Supports wildcards: io.github.modelcontextprotocol/*
52+
MCP_REGISTRY_RATE_LIMIT_EXEMPTIONS=

‎internal/config/config.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ type Config struct {
3333
OIDCExtraClaims string `env:"OIDC_EXTRA_CLAIMS" envDefault:""`
3434
OIDCEditPerms string `env:"OIDC_EDIT_PERMISSIONS" envDefault:""`
3535
OIDCPublishPerms string `env:"OIDC_PUBLISH_PERMISSIONS" envDefault:""`
36+
37+
// Rate Limiting Configuration
38+
RateLimitEnabled bool `env:"RATE_LIMIT_ENABLED" envDefault:"true"`
39+
RateLimitPerDay int `env:"RATE_LIMIT_PER_DAY" envDefault:"10"`
40+
RateLimitExemptions string `env:"RATE_LIMIT_EXEMPTIONS" envDefault:""` // comma-separated
3641
}
3742

3843
// NewConfig creates a new configuration with default values

‎internal/database/database.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ type Database interface {
4040
UpdateServer(ctx context.Context, id string, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error)
4141
// Close closes the database connection
4242
Close() error
43+
44+
// Rate limiting methods
45+
IncrementPublishCount(ctx context.Context, namespace string) error
46+
GetPublishCount(ctx context.Context, namespace string, date time.Time) (int, error)
47+
// CheckAndIncrementPublishCount atomically checks if the count is under the limit and increments if so
48+
// Returns the current count and whether the increment was successful
49+
CheckAndIncrementPublishCount(ctx context.Context, namespace string, limit int) (currentCount int, incrementSuccessful bool, err error)
4350
}
4451

4552
// ConnectionType represents the type of database connection

‎internal/database/memory.go‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,24 @@ import (
66
"sort"
77
"strings"
88
"sync"
9+
"time"
910

1011
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
1112
)
1213

1314
// MemoryDB is an in-memory implementation of the Database interface
1415
type MemoryDB struct {
15-
entries map[string]*apiv0.ServerJSON // maps registry metadata ID to ServerJSON
16-
mu sync.RWMutex
16+
entries map[string]*apiv0.ServerJSON // maps registry metadata ID to ServerJSON
17+
publishAttempts map[string]map[string]int // namespace -> date -> count
18+
mu sync.RWMutex
1719
}
1820

1921
func NewMemoryDB() *MemoryDB {
2022
// Convert input ServerJSON entries to have proper metadata
2123
serverRecords := make(map[string]*apiv0.ServerJSON)
2224
return &MemoryDB{
23-
entries: serverRecords,
25+
entries: serverRecords,
26+
publishAttempts: make(map[string]map[string]int),
2427
}
2528
}
2629

@@ -139,6 +142,58 @@ func (db *MemoryDB) UpdateServer(ctx context.Context, id string, server *apiv0.S
139142
return server, nil
140143
}
141144

145+
// IncrementPublishCount increments the publish count for a namespace today
146+
func (db *MemoryDB) IncrementPublishCount(_ context.Context, namespace string) error {
147+
db.mu.Lock()
148+
defer db.mu.Unlock()
149+
150+
today := time.Now().Format("2006-01-02")
151+
if db.publishAttempts[namespace] == nil {
152+
db.publishAttempts[namespace] = make(map[string]int)
153+
}
154+
db.publishAttempts[namespace][today]++
155+
return nil
156+
}
157+
158+
// GetPublishCount returns the number of publishes for a namespace on a specific date
159+
func (db *MemoryDB) GetPublishCount(_ context.Context, namespace string, date time.Time) (int, error) {
160+
db.mu.RLock()
161+
defer db.mu.RUnlock()
162+
163+
dateStr := date.Format("2006-01-02")
164+
if db.publishAttempts[namespace] == nil {
165+
return 0, nil
166+
}
167+
return db.publishAttempts[namespace][dateStr], nil
168+
}
169+
170+
// CheckAndIncrementPublishCount atomically checks if the count is under the limit and increments if so
171+
func (db *MemoryDB) CheckAndIncrementPublishCount(_ context.Context, namespace string, limit int) (currentCount int, incrementSuccessful bool, err error) {
172+
db.mu.Lock()
173+
defer db.mu.Unlock()
174+
175+
today := time.Now().Format("2006-01-02")
176+
177+
// Initialize namespace map if needed
178+
if db.publishAttempts[namespace] == nil {
179+
db.publishAttempts[namespace] = make(map[string]int)
180+
}
181+
182+
// Get current count
183+
currentCount = db.publishAttempts[namespace][today]
184+
185+
// Check if under limit and increment if so
186+
if currentCount < limit {
187+
db.publishAttempts[namespace][today]++
188+
currentCount++ // Return the new count after increment
189+
incrementSuccessful = true
190+
} else {
191+
incrementSuccessful = false
192+
}
193+
194+
return currentCount, incrementSuccessful, nil
195+
}
196+
142197
// For an in-memory database, this is a no-op
143198
func (db *MemoryDB) Close() error {
144199
return nil
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
-- Add rate limiting table to track publish attempts by namespace and date
2+
CREATE TABLE publish_attempts (
3+
namespace VARCHAR(255) NOT NULL,
4+
attempt_date DATE NOT NULL DEFAULT CURRENT_DATE,
5+
attempt_count INTEGER NOT NULL DEFAULT 0,
6+
first_attempt_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
7+
last_attempt_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
8+
PRIMARY KEY (namespace, attempt_date)
9+
);
10+
11+
-- Index for efficient lookups by namespace
12+
CREATE INDEX idx_publish_attempts_namespace ON publish_attempts(namespace);
13+
14+
-- Index for cleanup queries by date
15+
CREATE INDEX idx_publish_attempts_date ON publish_attempts(attempt_date);
16+
17+
-- Comment for documentation
18+
COMMENT ON TABLE publish_attempts IS 'Tracks daily publish attempts per namespace for rate limiting';
19+
COMMENT ON COLUMN publish_attempts.namespace IS 'The reverse-DNS namespace (e.g., io.github.username)';
20+
COMMENT ON COLUMN publish_attempts.attempt_date IS 'The date of the attempts (resets daily)';
21+
COMMENT ON COLUMN publish_attempts.attempt_count IS 'Number of successful publishes on this date';

‎internal/database/postgres.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,80 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, id string, server *apiv0
281281
return server, nil
282282
}
283283

284+
// IncrementPublishCount atomically increments the publish count for a namespace today
285+
func (db *PostgreSQL) IncrementPublishCount(ctx context.Context, namespace string) error {
286+
query := `
287+
INSERT INTO publish_attempts (namespace, attempt_date, attempt_count, first_attempt_at, last_attempt_at)
288+
VALUES ($1, CURRENT_DATE, 1, NOW(), NOW())
289+
ON CONFLICT (namespace, attempt_date)
290+
DO UPDATE SET
291+
attempt_count = publish_attempts.attempt_count + 1,
292+
last_attempt_at = NOW()
293+
`
294+
_, err := db.pool.Exec(ctx, query, namespace)
295+
if err != nil {
296+
return fmt.Errorf("failed to increment publish count: %w", err)
297+
}
298+
return nil
299+
}
300+
301+
// GetPublishCount returns the number of publishes for a namespace on a specific date
302+
func (db *PostgreSQL) GetPublishCount(ctx context.Context, namespace string, date time.Time) (int, error) {
303+
var count int
304+
query := `
305+
SELECT COALESCE(attempt_count, 0)
306+
FROM publish_attempts
307+
WHERE namespace = $1 AND attempt_date = $2
308+
`
309+
err := db.pool.QueryRow(ctx, query, namespace, date.Format("2006-01-02")).Scan(&count)
310+
if err != nil {
311+
if errors.Is(err, pgx.ErrNoRows) {
312+
return 0, nil // No attempts yet
313+
}
314+
return 0, fmt.Errorf("failed to get publish count: %w", err)
315+
}
316+
return count, nil
317+
}
318+
319+
// CheckAndIncrementPublishCount atomically checks if the count is under the limit and increments if so
320+
func (db *PostgreSQL) CheckAndIncrementPublishCount(ctx context.Context, namespace string, limit int) (currentCount int, incrementSuccessful bool, err error) {
321+
// Use a CTE to atomically check and increment
322+
query := `
323+
WITH current_state AS (
324+
SELECT COALESCE(attempt_count, 0) as count
325+
FROM publish_attempts
326+
WHERE namespace = $1 AND attempt_date = CURRENT_DATE
327+
UNION ALL
328+
SELECT 0 WHERE NOT EXISTS (
329+
SELECT 1 FROM publish_attempts
330+
WHERE namespace = $1 AND attempt_date = CURRENT_DATE
331+
)
332+
LIMIT 1
333+
),
334+
increment AS (
335+
INSERT INTO publish_attempts (namespace, attempt_date, attempt_count, first_attempt_at, last_attempt_at)
336+
SELECT $1, CURRENT_DATE, 1, NOW(), NOW()
337+
WHERE (SELECT count FROM current_state) < $2
338+
ON CONFLICT (namespace, attempt_date)
339+
DO UPDATE SET
340+
attempt_count = publish_attempts.attempt_count + 1,
341+
last_attempt_at = NOW()
342+
WHERE publish_attempts.attempt_count < $2
343+
RETURNING attempt_count
344+
)
345+
SELECT
346+
COALESCE((SELECT attempt_count FROM increment), (SELECT count FROM current_state)) as final_count,
347+
EXISTS (SELECT 1 FROM increment) as was_incremented
348+
`
349+
350+
err = db.pool.QueryRow(ctx, query, namespace, limit).Scan(&currentCount, &incrementSuccessful)
351+
if err != nil {
352+
return 0, false, fmt.Errorf("failed to check and increment publish count: %w", err)
353+
}
354+
355+
return currentCount, incrementSuccessful, nil
356+
}
357+
284358
// Close closes the database connection
285359
func (db *PostgreSQL) Close() error {
286360
db.pool.Close()

0 commit comments

Comments
 (0)