Skip to main content
Glama
afshinator

mcp-server-pexels

Search Pexels Photos

pexels_search_photos
Read-onlyIdempotent

Search for stock photos by query with optional filters for orientation, size, color, and locale. Returns results with mandatory photographer attribution.

Instructions

Search for stock photos by query with optional filters for orientation, size, color, and locale. Returns 3-5 results with mandatory photographer attribution.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
orientationNo
sizeNo
colorNo
localeNo
per_pageNo
force_refreshNo

Implementation Reference

  • The main handler function `handlePhotoSearch` that executes the pexels_search_photos tool logic. It extracts query params (query, orientation, size, color, locale, per_page), checks cache, calls fetchPhotoSearch, formats results with attribution via formatPhotoResult and buildPhotoStructuredData, and returns content blocks.
    export async function handlePhotoSearch(
      args: z.infer<typeof photoSearchSchema>,
    ): Promise<CallToolResult> {
      const start = Date.now();
      const forceRefresh = args.force_refresh ?? false;
      const params = {
        query: args.query,
        orientation: args.orientation,
        size: args.size,
        color: args.color,
        locale: args.locale,
        per_page: args.per_page || 5,
      };
    
      logDebug('tool: pexels_search_photos', 'params:', JSON.stringify(params));
    
      const cacheKey = makeCacheKey(params);
    
      if (!forceRefresh) {
        const cached = getFromCache<ContentBlock[]>(cacheKey);
        if (cached) {
          logDebug('cache: HIT', 'key:', cacheKey, `${Date.now() - start}ms`);
          return { content: cached };
        }
        logDebug('cache: MISS', 'key:', cacheKey);
      }
    
      try {
        const response = await fetchPhotoSearch(params);
        const photos = response.photos?.slice(0, params.per_page) || [];
        const contentBlocks = photos.flatMap(formatPhotoResult);
        const structured = { results: photos.map(buildPhotoStructuredData) };
        contentBlocks.push({ type: 'text', text: JSON.stringify(structured) });
        setCache(cacheKey, contentBlocks, 600);
        logDebug('result:', 'count:', photos.length, `${Date.now() - start}ms`);
        return { content: contentBlocks };
      } catch (error) {
        logDebug('error:', error instanceof Error ? error.message : String(error));
        return formatApiError(error);
      }
    }
  • Registers the tool 'pexels_search_photos' on the McpServer with title, description, input schema, annotations (readOnlyHint, idempotentHint), and wires it to handlePhotoSearch.
    export function registerPhotoSearch(server: McpServer): void {
      server.registerTool(
        'pexels_search_photos',
        {
          title: 'Search Pexels Photos',
          description:
            'Search for stock photos by query with optional filters for orientation, size, color, and locale. Returns 3-5 results with mandatory photographer attribution.',
          inputSchema: photoSearchSchema,
          annotations: {
            readOnlyHint: true,
            idempotentHint: true,
          },
        },
        (args) => handlePhotoSearch(args),
      );
    }
  • The `photoSearchSchema` Zod schema used for input validation of pexels_search_photos. Defines fields: query (trimmed + max 100), orientation, size, color, locale, per_page (1-10), force_refresh.
    export const photoSearchSchema = z.object({
      query: z.string().trim().transform((val) => val.slice(0, 100)),
      orientation: z.enum(['landscape', 'portrait', 'square']).optional(),
      size: z.enum(['large', 'medium', 'small']).optional(),
      color: colorSchema.optional(),
      locale: z.string().optional(),
      per_page: z.number().min(1).max(10).optional(),
      force_refresh: z.boolean().optional(),
    });
  • Helper function `buildPhotoStructuredData` that converts a PexelsPhoto into structured output data conforming to photoOutputSchema.
    export function buildPhotoStructuredData(photo: PexelsPhoto): z.infer<typeof photoOutputSchema> {
      const bestSrc = photo.src.medium;
      return {
        id: photo.id,
        kind: 'photo',
        creatorName: photo.photographer,
        creatorUrl: photo.photographer_url,
        pageUrl: photo.url,
        previewUrl: bestSrc,
        mediaUrl: photo.src.large2x || bestSrc,
        mediaMimeType: 'image/jpeg',
        dimensions: { width: photo.width, height: photo.height },
        avgColor: photo.avg_color,
        alt: photo.alt || '',
      };
    }
  • Helper function `formatPhotoResult` that formats a PexelsPhoto into a text block with markdown (photographer attribution, dimensions, color, alt text, image preview) and a resource_link block.
    export function formatPhotoResult(photo: PexelsPhoto): ContentBlock[] {
      const text = `Photo by [${photo.photographer}](${photo.photographer_url}) on Pexels
    
    **ID:** ${photo.id}
    **Dimensions:** ${photo.width}x${photo.height}
    **Color:** ${photo.avg_color}
    **Alt:** ${photo.alt || 'No description'}
    **Link:** ${photo.url}
    ![Preview](${photo.src.medium})`;
    
      return [
        { type: 'text', text },
        { type: 'resource_link', uri: photo.src.medium, name: 'Preview', mimeType: 'image/jpeg' },
      ];
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint and idempotentHint true. The description adds that results are 3-5 and require attribution, providing useful behavioral context beyond annotations without contradiction.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loading the primary purpose, with no unnecessary words. Every sentence adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has 7 parameters and no output schema. The description covers 5 of 7 parameters (omitting per_page and force_refresh) and mentions return count but not structure. For a search tool with many filters, the description is partially complete but misses some parameter context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description names filter categories (orientation, size, color, locale) but does not detail value formats or enums, despite 0% schema coverage. The schema provides enums for orientation and size, but the description could be more helpful by noting accepted values or constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool verb ('Search') and resource ('stock photos') and distinguishes from siblings by specifying photo search. It also notes return count and attribution, providing a precise purpose.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description lists optional filters and mentions mandatory attribution, giving usage hints. However, it does not explicitly state when to use this tool versus alternatives like pexels_get_details or pexels_search_videos, though sibling names imply differentiation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/afshinator/mcp-server-pexels'

If you have feedback or need assistance with the MCP directory API, please join our Discord server