Skip to main content
Glama

background.search

Search for background design patterns like gradients, glassmorphism, and SVG backgrounds using natural language queries. Filter by design type or web page ID to find suitable visual elements.

Instructions

BackgroundDesignをセマンティック検索します。グラデーション、グラスモーフィズム、SVG背景等の背景デザインパターンを自然言語で検索できます。designType(14種類)やwebPageIdでフィルタリング可能です。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes検索クエリ(自然言語、1-500文字)
limitNo取得件数(1-50、デフォルト: 10)
offsetNoオフセット(0以上、デフォルト: 0)
filtersNo検索フィルター
profile_idNo嗜好プロファイルID(検索結果のリランキングに使用) / Preference profile ID (used for search result reranking)

Implementation Reference

  • Implementation of the background.search MCP tool handler. It validates inputs, generates embeddings via a service, performs search (with optional hybrid support), and applies preference-based reranking.
    export async function backgroundSearchHandler(input: unknown): Promise<BackgroundSearchOutput> {
      const startTime = Date.now();
    
      if (isDevelopment()) {
        logger.info("[MCP Tool] background.search called", {
          query: (input as Record<string, unknown>)?.query,
        });
      }
    
      // 入力バリデーション
      let validated: BackgroundSearchInputType;
      try {
        validated = backgroundSearchInputSchema.parse(input);
      } catch (error) {
        if (error instanceof ZodError) {
          const errorMessage = error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");
    
          if (isDevelopment()) {
            logger.error("[MCP Tool] background.search validation error", {
              errors: error.errors,
            });
          }
    
          return {
            success: false,
            error: {
              code: BACKGROUND_MCP_ERROR_CODES.VALIDATION_ERROR,
              message: `Validation error: ${errorMessage}`,
            },
          };
        }
        throw error;
      }
    
      // サービスファクトリーチェック
      if (!backgroundSearchServiceFactory) {
        if (isDevelopment()) {
          logger.error("[MCP Tool] background.search service factory not set");
        }
    
        return {
          success: false,
          error: {
            code: BACKGROUND_MCP_ERROR_CODES.SERVICE_UNAVAILABLE,
            message: "Background search service is not available",
          },
        };
      }
    
      const service = backgroundSearchServiceFactory();
    
      try {
        // E5 モデル用 query: プレフィックスを付与
        const processedQuery = `query: ${validated.query}`;
    
        // Embedding 生成
        const queryEmbedding = await service.generateQueryEmbedding(processedQuery);
    
        // Embedding が null の場合は空結果を返す
        if (queryEmbedding === null) {
          if (isDevelopment()) {
            logger.warn(
              "[MCP Tool] background.search embedding not available, returning empty results"
            );
          }
    
          return {
            success: true,
            data: {
              results: [],
              total: 0,
              query: validated.query,
              searchTimeMs: Date.now() - startTime,
            },
          };
        }
    
        // 検索オプション構築
        const searchOptions: {
          limit: number;
          offset: number;
          filters?: {
            designType?: string;
            webPageId?: string;
          };
        } = {
          limit: validated.limit,
          offset: validated.offset,
        };
    
        // フィルターが存在する場合のみ追加
        if (validated.filters) {
          const filters: { designType?: string; webPageId?: string } = {};
          if (validated.filters.designType) {
            filters.designType = validated.filters.designType;
          }
          if (validated.filters.webPageId) {
            filters.webPageId = validated.filters.webPageId;
          }
          if (Object.keys(filters).length > 0) {
            searchOptions.filters = filters;
          }
        }
    
        // 検索実行(ハイブリッド検索優先)
        const searchResult = service.searchBackgroundDesignsHybrid
          ? await service.searchBackgroundDesignsHybrid(validated.query, queryEmbedding, searchOptions)
          : await service.searchBackgroundDesigns(queryEmbedding, searchOptions);
    
        // 結果マッピング
        let mappedResults: BackgroundSearchResultItem[] = searchResult.results.map((r) => ({
          id: r.id,
          designType: r.designType,
          cssValue: r.cssValue,
          similarity: r.similarity,
          source: {
            webPageId: r.webPageId,
          },
          name: r.name,
          selector: r.selector,
          colorInfo: r.colorInfo,
          textRepresentation: r.textRepresentation,
        }));
    
        const searchTimeMs = Date.now() - startTime;
    
        if (isDevelopment()) {
          logger.info("[MCP Tool] background.search completed", {
            query: validated.query,
            resultCount: mappedResults.length,
            total: searchResult.total,
            searchTimeMs,
          });
        }
    
        // 嗜好プロファイルによるリランキング / Preference profile reranking
        mappedResults = await applyPreferenceReranking(
          mappedResults,
          validated.profile_id,
          prismaClientFactory,
          "background",
          "background.search"
        );
    
        return {
          success: true,
          data: {
            results: mappedResults,
            total: searchResult.total,
            query: validated.query,
            searchTimeMs,
          },
        };
      } catch (error) {
        const errorInstance = error instanceof Error ? error : new Error(String(error));
        const errorCode = mapErrorToCode(errorInstance);
    
        if (isDevelopment()) {
          logger.error("[MCP Tool] background.search error", {
            code: errorCode,
            error: errorInstance.message,
          });
        }
    
        return {
          success: false,
          error: {
            code: errorCode,
            message: errorInstance.message,
          },
        };
      }
    }
  • Zod input schema for background.search tool.
     * background.search 入力スキーマ
     */
    export const backgroundSearchInputSchema = z.object({
      /** 検索クエリ(1-500文字) */
      query: z.string().min(1).max(500),
      /** 取得件数(1-50、デフォルト: 10) */
      limit: z.number().int().min(1).max(50).default(10),
      /** オフセット(0以上、デフォルト: 0) */
      offset: z.number().min(0).default(0),
      /** 検索フィルター */
      filters: backgroundSearchFiltersSchema,
      /**
       * 嗜好プロファイルID(検索結果のリランキングに使用)
       * Preference profile ID (used for search result reranking)
       */
      profile_id: z.string().uuid().optional(),
    });
    
    export type BackgroundSearchInput = z.infer<typeof backgroundSearchInputSchema>;
  • MCP tool registration/definition for background.search.
    export const backgroundSearchToolDefinition = {
      name: "background.search",
      description:
        "BackgroundDesignをセマンティック検索します。" +
        "グラデーション、グラスモーフィズム、SVG背景等の背景デザインパターンを自然言語で検索できます。" +
        "designType(14種類)やwebPageIdでフィルタリング可能です。",
      annotations: {
        title: "Background Search",
        readOnlyHint: true,
        idempotentHint: true,
        openWorldHint: false,
      },
      inputSchema: {
        type: "object" as const,
        properties: {
          query: {
            type: "string",
            description: "検索クエリ(自然言語、1-500文字)",
            minLength: 1,
            maxLength: 500,
          },
          limit: {
            type: "number",
            description: "取得件数(1-50、デフォルト: 10)",
            minimum: 1,
            maximum: 50,
            default: 10,
          },
          offset: {
            type: "number",
            description: "オフセット(0以上、デフォルト: 0)",
            minimum: 0,
            default: 0,
          },
          filters: {
            type: "object",
            description: "検索フィルター",
            properties: {
              designType: {
                type: "string",
                enum: [
                  "solid_color",
                  "linear_gradient",
                  "radial_gradient",
                  "conic_gradient",
                  "mesh_gradient",
                  "image_background",
                  "pattern_background",
                  "video_background",
                  "animated_gradient",
                  "glassmorphism",
                  "noise_texture",
                  "svg_background",
                  "multi_layer",
                  "unknown",
                ],
                description: "BackgroundDesignTypeでフィルター",
              },
              webPageId: {
                type: "string",
                format: "uuid",
                description: "WebページIDでフィルター",
              },
            },
          },
          // Preference reranking
          profile_id: {
            type: "string",
            format: "uuid",
            description:
              "嗜好プロファイルID(検索結果のリランキングに使用) / Preference profile ID (used for search result reranking)",
          },
        },
        required: ["query"],
      },
    };

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/TKMD/reftrix-mcp'

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