pexels-mcp-server
This server is an MCP adapter that lets AI agents search, fetch, and discover free stock photos and videos from Pexels via tools, resources, and prompts.
Search photos (
pexels_search_photos): query with filters like orientation, size, color, locale, aspect ratio, min width/height.Get a single photo (
pexels_get_photo): fetch photo details by ID.Search videos (
pexels_search_videos): query with orientation, size, locale, aspect ratio, min dimensions.Get a single video (
pexels_get_video): fetch video details by ID.Read collection media (
pexels_get_collection_media): list photos and videos inside a Pexels collection, optionally filtered by type and dimensions.Get curated photos (
pexels_get_curated_photos): browse Pexels' editor-curated daily photo feed with post-hoc dimension/aspect filters.Get popular videos (
pexels_get_popular_videos): browse trending videos with native duration and dimension filters plus aspect ratio.Discover featured collections (
pexels_get_featured_collections): list collection metadata (IDs, titles, counts) to feed into collection-media lookups.Resources (
pexels://photo/{id},pexels://video/{id},pexels://collection/{id}): attach Pexels content directly from URLs without tool calls.Prompts (
find_hero_image,find_broll): pre-built user briefs for hero images and B-roll with topic, orientation, color/resolution, and aspect ratio.Returned data includes CDN image/MP4 URLs, photographer/uploader credit, dimensions, alt text, pagination, and filter diagnostics for retrying failed post-hoc filters.
Provides tools for searching and retrieving stock photos and videos from Pexels, including filters like orientation, size, color, and aspect ratio, as well as resources for direct access to photo, video, and collection data.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@pexels-mcp-server search for high-resolution photos of beaches"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
pexels-mcp-server
A Model Context Protocol (MCP) server that gives AI agents access to free stock photos and videos from Pexels. Plug it into claude.ai web, Claude Desktop, Claude Code, Cursor or any MCP-aware client and the model gains the three MCP primitives (tools, resources, prompts) over the Pexels REST surface.
Built around the MCP spec 2025-11-25
and Anthropic's Writing tools for agents
guidance: strict Pydantic input schemas, structured tool output via
structuredContent + outputSchema, isError=true on tool failure per
SEP-1303, OAuth 2.1 + RFC 9728 + RFC 7591 DCR + PKCE for the HTTP transport.
What the agent gets
8 tools (model-controlled)
Tool | Purpose |
| Search photos. Filters: |
| Fetch one photo by id. |
| Search videos. Same filters minus |
| Fetch one video by id. |
| Read photos + videos in a Pexels collection. |
| Pexels' editor-curated daily photo feed. Post-hoc dim/aspect filters. |
| Trending video feed. Native |
| Discover curated collection ids (metadata only — pipe an id into |
3 resources (app-controlled, URI templates)
URI template | MIME | Body |
|
|
|
|
|
|
|
|
|
A user pasting a pexels.com URL into a chat lets the host attach the
content directly without the agent invoking a tool.
2 prompts (user-controlled, claude.ai connector menu)
Prompt | Arguments | Use case |
|
| Marketing hero with brand fit |
|
| B-roll, reels, hero loops |
Each prompt renders a short user-message brief that names the tool, the filters and the attribution requirement — the agent acts in one turn instead of asking the user for parameters.
Related MCP server: MCP Image Resolver
Token economy
Payloads are kept small, but the tool result is still sent twice. What the server does:
Projected payloads. Tools return a few fields per item (
id,alt,page_url, credit, dimensions, oneimage_url/video_url) instead of the full Pexels object with its eightsrcrenditions.Tool descriptions trimmed to the minimum LLM-actionable signal (USE WHEN / DO NOT USE / filters / return shape).
Type docstrings removed from
MediaSize,PhotoProjection,VideoProjection,FilterDiagnosticsetc.: they leaked asdescriptionfields into every tool's$defs, duplicated across all tools that referenced them. Now Python comments only.serverInfo.instructionskept to three short sentences (what the server is, the attribution requirement, how to use the CDN URLs); the tool list is already shipped bytools/list.SDK patch (see
_sdk_patches.py):Forces
model_dump(exclude_unset=True)so unset optional TypedDict fields don't leak as"field": null.Writes the text copy in
content[]as compact JSON instead of the SDK'sindent=2. The copy itself stays: claude.ai's custom-connector path reads onlycontent, so the payload is sent both asstructuredContentand as text.
Measured on pexels_search_photos(query="paris", per_page=15) through an
in-process MCP client session (mcp.shared.memory), with the Pexels API
mocked by a 15-photo response of about 20 100 chars:
|
| total | |
| 6 810 chars | 5 668 chars | 12 478 chars |
This server (compact text) | 5 668 chars | 5 668 chars | 11 336 chars |
The compact text saves about 17 % of the text copy (9 % of the whole
result). Other sizes from the same run: serverInfo.instructions is
298 chars, and tools/list for the 8 tools is 24 205 chars of compact
JSON, 4 033 of which are descriptions.
How the agent picks the best image
Pexels already ranks results by relevance. The tools just let the agent narrow the field in one shot:
Frame query + filters —
orientationfor hero banners,aspect_ratiofor fixed-frame (Instagram 1:1, Story 9:16, hero 16:9),min_width/min_heightfor hard pixel floors (~4000 for A4 print, ~1920 for hero),colorfor brand fit.Read alt text —
pexels_search_photosreturns up to 15 candidates by default withalttext, dimensions and photographer credit. The agent drops anything off-topic and returns the bestimage_urlplus the mandatoryphotographer/photographer_url.
When a post-hoc filter (aspect_ratio etc.) wipes the page, the envelope
carries a filter_diagnostics block telling the agent how to retry.
Deployment
Designed for one hosted HTTPS endpoint with OAuth 2.1 + RFC 9728. Stdio is supported for local power-user clients (Cursor, scripts).
Auth model — bring-your-own-key (BYOK) during the OAuth flow
The Python process is both the Resource Server (holding /mcp) and the
Authorization Server. The MCP Python SDK mounts every well-known endpoint
automatically: /.well-known/oauth-protected-resource (RFC 9728),
/.well-known/oauth-authorization-server (RFC 8414), /authorize,
/token, /register (RFC 7591 DCR), all with PKCE.
register_client rejects redirect_uri schemes that aren't https://
or http:// loopback (OAuth 2.1 phishing mitigation).
After the standard handshake, the server redirects the user's browser to
/setup, a short HTML form asking for a Pexels API key. The user pastes
their free key (from https://www.pexels.com/api/), the server validates
it against api.pexels.com, then mints the OAuth code with the key bound
to the soon-to-be-issued access token (30-day TTL). Every tool / resource
call resolves the caller's key by Bearer-token lookup.
For per-request clients (Cursor stdio bridges, scripts), the server also
accepts an X-Pexels-Api-Key HTTP header as a fallback.
Environment variables
Variable | Required | Description |
| yes |
|
| yes (HTTP) | Public HTTPS URL of this service. No trailing slash. |
| no | Comma-separated |
| no (60) | Per-IP rate limit. |
| no (1) | Proxies in front of the app (Koyeb LB = 1, Cloudflare-then-Koyeb = 2, no proxy = 0). |
| no | When set, OAuth state lives in Redis and survives restarts. Supports |
| yes if | 32-byte url-safe base64 Fernet key. Pexels keys are encrypted at rest. Generate: |
| no | Default |
| no ( | Standard Python levels. |
| no |
|
| stdio only | Default key for local clients. Ignored in HTTP mode. |
Persistent sessions (Redis, optional but recommended in prod)
Without REDIS_URL, OAuth state is in-memory and every Koyeb deploy
forces users to re-walk /setup. With Redis, registered clients, access
tokens and bound keys survive restarts. Short-lived OAuth state (pending
/setup sessions, authorization codes) stays in process memory either
way, so Redis does not make multiple replicas safe.
The bound Pexels key is encrypted client-side with Fernet (AES-128-CBC +
HMAC-SHA256) before being written — a leaked Redis dump alone yields
opaque ciphertext.
Compatible providers: Upstash Redis (free tier
10k cmd/day, 256 MB, TLS), Redis Cloud, self-hosted. See
docker-compose.yml for the local dev setup.
Koyeb (one-command deploy)
koyeb service create pexels-mcp \
--git github.com/VictorNain26/pexels-mcp-server \
--git-branch main \
--git-builder docker \
--ports 8000:http \
--routes /:8000 \
--checks 8000:http:/healthz \
--env TRANSPORT=streamable-http \
--env "MCP_SERVER_URL=https://{{ KOYEB_PUBLIC_DOMAIN }}" \
--env "MCP_ALLOWED_HOSTS={{ KOYEB_PUBLIC_DOMAIN }}" \
--env LOG_FORMAT=json \
--instance-type nano \
--regions fraThen add REDIS_URL + MCP_ENCRYPTION_KEY for persistent sessions.
Smoke test
URL=https://<your-service>.koyeb.app
curl -s "$URL/healthz" # -> ok
curl -s "$URL/.well-known/oauth-protected-resource" | head -20
curl -i -X POST "$URL/mcp" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json,text/event-stream' \
-H 'MCP-Protocol-Version: 2025-11-25' \
-d '{}' | head -10
# -> 401 with WWW-Authenticate: Bearer ... resource_metadata="..."Connect a client
Client | Steps |
claude.ai web | Settings → Connectors → Add custom connector → URL |
Claude Desktop | Settings → Connectors → Add (remote) → same URL. Same |
Claude Code |
|
MCP Inspector |
|
Install
This package (pexels-mcp in pyproject.toml) is not published on
PyPI; install it from this repository. The pexels-mcp-server name on
PyPI belongs to an unrelated project, so do not pip install it.
Run the stdio server straight from Git:
PEXELS_API_KEY=your-key uvx --from git+https://github.com/VictorNain26/pexels-mcp-server pexels-mcp-serverLocal development
git clone https://github.com/VictorNain26/pexels-mcp-server
cd pexels-mcp-server
uv sync --all-extrasHTTP server (prod parity)
TRANSPORT=streamable-http HOST=127.0.0.1 PORT=8000 \
MCP_SERVER_URL=http://127.0.0.1:8000 \
uv run pexels-mcp-serverFull stack with Redis (Fernet path exercised)
echo "MCP_ENCRYPTION_KEY=$(python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())')" > .env
docker compose up --buildStdio (Cursor, local scripts)
PEXELS_API_KEY=your-key uv run pexels-mcp-serverStdio bypasses OAuth — the key comes from the env var directly.
Check suite
uv run ruff check && uv run ruff format --check
uv run mypy src
uv run python -m pytestResponse shape
pexels_search_photos(query="paris", per_page=1) ships:
structuredContent(canonical payload, machine-readable, ~600c):
{
"page": 1,
"per_page": 1,
"count": 1,
"has_more": true,
"next_page": 2,
"total_results": 8000,
"photos": [
{
"id": 28448939,
"alt": "Vibrant street view of central Paris ...",
"page_url": "https://www.pexels.com/photo/.../28448939/",
"photographer": "Sergey Guk",
"photographer_url": "https://www.pexels.com/@sergeyguk",
"width": 4000,
"height": 6000,
"image_url": "https://images.pexels.com/photos/28448939/.../original.jpeg"
}
]
}content[0]: the same object as compact JSON text ({"page":1,"per_page":1,...}).
The text copy is there because claude.ai's custom-connector path passes
only content to the model. Clients that read structuredContent can
ignore it.
Three usage examples
1. Hero image with brand color and aspect ratio
pexels_search_photos(
query="modern open-plan office workspace",
orientation="landscape",
size="large",
color="blue",
aspect_ratio="16:9",
min_width=1920,
per_page=6,
)2. 4K B-roll, fixed aspect
pexels_search_videos(
query="aerial drone shot of mountain lake at dawn",
orientation="landscape",
size="large",
aspect_ratio="16:9",
per_page=10,
)video_url is the direct MP4 of the top-resolution variant.
3. Drill into a Pexels collection
pexels_get_collection_media(collection_id="9j5dhpu", per_page=20)The response splits photos[] and videos[]. Filter to one type with
type="photos" or type="videos".
Rate limits and attribution
Pexels free tier: 200 requests/hour, 20 000 requests/month on the
caller's key (per Pexels' API docs).
The server warns to stderr below 100 remaining; the response envelope
does not carry rate-limit metadata (saves tokens — flip LOG_LEVEL=DEBUG
if you need it).
If you publish anything returned by this server you must credit the
photographer / videographer and link back to Pexels per the
Pexels licence. Every tool, resource
and prompt is shaped so the LLM sees photographer / uploader_name
and matching URLs and can surface them in the user-facing answer.
Architecture notes
3-of-3 MCP primitives. Tools (model-controlled), Resources (app-controlled, URI templates per RFC 6570), Prompts (user-controlled, surfaced in claude.ai's connector menu).
Spec-compliant auth. OAuth 2.1 Resource Server + Authorization Server in one process via the MCP Python SDK's
OAuthAuthorizationServerProvider. RFC 9728 PRM, RFC 8414 ASM, RFC 7591 DCR, PKCE — all served by the SDK. The only custom routes areGET /(landing) andGET/POST /setup(BYOK form).Stateless MCP transport, single-replica OAuth.
stateless_http=True, json_response=True: the MCP transport allocates no session IDs, so tool calls need no sticky sessions. Trade-off: no sampling / noctx.report_progress/ no resource subscriptions — documented inCLAUDE.md. The server as a whole is not horizontally scalable yet: pending/setupsessions, authorization codes and the transient code→key binding live in process memory (even withREDIS_URL), so an OAuth flow that hits a second replica fails. The rate limiter is per-process too. Run one replica.Read-only by construction. Every tool advertises
readOnlyHint=true, destructiveHint=false, idempotentHint=true, openWorldHint=trueplus atitle.Structured tool output +
isError=true. Tools return aTypedDict; the SDK auto-generatesoutputSchema. Errors raise → FastMCP wraps inCallToolResult(isError=true)per SEP-1303.Strict inputs. Pydantic v2 with
extra="forbid"; invalid values come back asInvalid parameters: <field>: <reason>.Token-lean payloads. See the Token economy section above.
SDK patches in
_sdk_patches.py. The only place in the repo that mutates third-party state.
Health and probes
GET /healthz (liveness) and GET /readyz (readiness) return 200 ok
and bypass auth. The Dockerfile declares HEALTHCHECK against /healthz.
Compatibility
Python 3.10, 3.11, 3.12.
mcpSDK pinned>=1.25,<2.Transport: stdio + Streamable HTTP. Legacy SSE is not enabled.
MCP spec 2025-11-25 (SDK negotiates downgrade to 2025-06-18 / 2025-03-26).
See SECURITY.md to report a vulnerability, PRIVACY.md for what the server does and doesn't store.
License
MIT. See LICENSE.
Available Tools
8 toolspexels_get_collection_mediaGet Pexels Collection ContentsARead-onlyIdempotent
Read the photos + videos inside a Pexels collection.
USE WHEN you have a collection id (pexels.com/collections/<id>).
Filter to one type with `type` ('photos' or 'videos').
Post-hoc filters (aspect_ratio, min_width, min_height) apply to both.
DO NOT USE for discovery — no public list-all-collections endpoint.
Per-item shape matches the search tools.
Inputs: collection_id (required), page, sort, type, +4 more. Returns: id, page, count, photos, +6 more
pexels_get_curated_photosGet Pexels Curated PhotosARead-onlyIdempotent
Fetch Pexels' editor-curated daily photo feed.
USE WHEN: feed-style discovery without a specific query — "what's
trending on Pexels today", brand-safe brainstorming, mood-board fuel.
DO NOT USE for targeted topic search — call pexels_search_photos.
Post-hoc filters (4x oversample, cap 80): aspect_ratio, min_width,
min_height. image_url is a public CDN link: render as Markdown or
pass to any URL-accepting downstream tool. Do not curl/download
the bytes. Always credit photographer per Pexels licence.
Inputs: page, per_page, min_width, min_height, +1 more. Returns: page, count, photos, has_more, +4 more
pexels_get_featured_collectionsGet Pexels Featured CollectionsARead-onlyIdempotent
Discover Pexels' editor-curated collections.
USE WHEN you need a collection id and don't have one — Pexels has no
public list-all-collections endpoint, so /featured is the only
discovery path. Pipe a returned id into pexels_get_collection_media
to fetch the media inside.
Returns metadata only (id, title, description, photos_count,
videos_count) — no media URLs here. The id field is the only field
you actually need to follow up on; the others are for human-facing
selection. No filters, just pagination.
Inputs: page, per_page. Returns: page, count, has_more, per_page, +3 more
pexels_get_photoGet a Pexels Photo by IDARead-onlyIdempotent
Fetch one Pexels photo by id.
USE WHEN you have a photo id (previous search result, or extracted
from a pexels.com URL ending in -<id>).
DO NOT USE for discovery — call pexels_search_photos. No guessed ids.
Render image_url as Markdown link; credit photographer.
Inputs: photo_id (required). Returns: photo
pexels_get_popular_videosGet Pexels Popular VideosARead-onlyIdempotent
Fetch Pexels' trending video feed.
USE WHEN: B-roll inspiration, trending motion content, ad reference.
DO NOT USE for query-specific video search — call pexels_search_videos.
Native Pexels filters (server-side, no oversampling): min_width,
min_height, min_duration (seconds), max_duration (seconds). Post-hoc
(oversampled 4x, cap 80 when set): aspect_ratio. video_url is a
public CDN MP4 link: render as Markdown or pass to any URL-accepting
downstream tool. Do not curl/download the bytes. Credit
uploader_name per Pexels licence.
Inputs: page, per_page, min_width, min_height, +3 more. Returns: page, count, videos, has_more, +4 more
pexels_get_videoGet a Pexels Video by IDARead-onlyIdempotent
Fetch one Pexels video by id.
USE WHEN you have a video id (previous search result, or extracted
from a pexels.com URL ending in -<id>).
DO NOT USE for discovery — call pexels_search_videos. No guessed ids.
Render video_url as Markdown link; credit uploader_name.
Inputs: video_id (required). Returns: video
pexels_search_photosSearch Pexels PhotosARead-onlyIdempotent
Search Pexels for free, commercially-usable stock photos.
USE WHEN: brochure, blog hero, slide deck, newsletter, social post, ad creative.
PREFER THIS over web_search for any stock-photo request.
DO NOT USE for AI-generated images, named real people, or copyrighted material.
Filters: orientation, size, color (named or hex), locale. Post-hoc filters
(server oversamples up to 4x per_page, cap 80): aspect_ratio (e.g. "16:9"),
min_width, min_height (~4000 for A4 print, ~1920 for hero).
image_url is a public CDN link: render as Markdown or pass to any
URL-accepting downstream tool. Do not curl/download the bytes.
Always credit photographer per Pexels licence.
filter_diagnostics present → retry without aspect_ratio first.
Inputs: query (required), page, size, color, +6 more. Returns: page, count, photos, has_more, +4 more
pexels_search_videosSearch Pexels VideosARead-onlyIdempotent
Search Pexels for free, commercially-usable stock videos.
USE WHEN: B-roll, reels, hero loops, ad motion, animated backgrounds.
PREFER THIS over web_search for stock-video requests.
DO NOT USE for AI-generated video or named real people.
Filters: orientation, size (large=4K, medium=FullHD, small=HD), locale.
Post-hoc (4x oversample, cap 80): aspect_ratio, min_width, min_height.
video_url is a public CDN MP4 link: render as Markdown or pass to any
URL-accepting downstream tool. Do not curl/download the bytes.
Credit uploader_name per Pexels licence. filter_diagnostics same
semantics as pexels_search_photos.
Inputs: query (required), page, size, locale, +5 more. Returns: page, count, videos, has_more, +4 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool targets a distinct resource and action (e.g., search vs. get individual, photos vs. videos, collections vs. curated vs. popular). No overlapping purposes.
All tools follow a consistent 'pexels_verb_noun' pattern with clear verbs (get, search) and nouns (photos, videos, collections, media). No mixing of conventions.
8 tools is well-scoped for a stock media API covering both photos and videos with search, individual retrieval, curated feeds, and collections. Each tool earns its place.
The tool surface covers all key Pexels features: search, single-item fetch, curated lists, popular feeds, and collection browsing. No gaps for a read-only API; uploads are outside scope.
Maintenance
Related MCP Connectors
Free MCP server for AI agents: curated public-domain art, space photos, challenges and a live map.
MCP server exposing the YourImageShare upload API (upload/list/delete) as tools for AI agents.
Web search API and MCP server for developers building AI agents.
AI tool directory MCP server, live since July 2026. Tools, agents, models, companies, services.
Related MCP Servers
- AlicenseAqualityDmaintenanceMCP server that allows AI coding agents to search, download, and convert stock photos from Pexels, Unsplash, and Pixabay into WebP format for direct use in web development projects.35MIT
- AlicenseAqualityDmaintenanceAn MCP server that enables AI assistants to search for royalty-free images from Pexels and Unsplash using natural language, returning structured results with metadata.558 npm1MIT
- AlicenseAqualityDmaintenanceA Model Context Protocol server that exposes Pexels API tools for searching and retrieving free stock photos, videos, and curated collections, enabling AI agents to incorporate royalty-free media directly from chat.9228 npm3MIT
- FlicenseNot gradedqualityDmaintenanceMCP server for the Pexels API that provides tools for searching photos and videos, retrieving curated content, and accessing featured collections. Enables natural language interaction with Pexels media search functionality.1-