Visual Asset Retrieval and Icon Synthesis Tool
This specialized software interfaces with multiple external image repositories, such as Unsplash and Pexels, to fulfill user requests for high-quality visual data. Similar to the core function of a web search engine providing relevant hyperlinks and summaries, this tool retrieves specific image assets or synthesizes novel icons based on textual prompts, significantly aiding project visualization.
Author

yanjunz
Quick Info
Actions
Tags
Introduction
This utility facilitates the retrieval of visual resources and the creation of custom icons, supporting integration within the Cursor Model Control Protocol (MCP) environment. As a specialized application, it mirrors the broader concept of web search, where users seek specific information—here, visual media—delivered via an automated system. It provides capabilities for locating, fetching, and programmatically generating project imagery.
System Operation Flow
This tool operates under the MCP framework to extend Cursor IDE's capabilities with image services. The general interaction sequence involves:
User Input (in Cursor) → Model Query → Model Invokes MCP Tool → Tool Processes Request → Result Returned → Model Displays Output
For example, a request like asking the model to "locate five astronomical images" triggers this MCP service to execute the search and present the results, allowing subsequent requests for downloading or icon synthesis.
Key Capabilities
- Accessing several distinct image data sources, including Unsplash, Pexels, and Pixabay.
- Producing custom graphical assets leveraging AI synthesis, reportedly utilizing Together AI capabilities.
- Offering a streamlined interface for programmatic interaction.
- Incorporating robust mechanisms for handling operational failures.
- Allowing customization of where files are stored and what names they receive.
- Providing options to modify the dimensions of retrieved visuals.
Prerequisite Environment Setup
1. Python Environment
Required software includes Python version 3.10 or newer. You can obtain the installer from the official Python website. Managing different versions using a utility like pyenv is often recommended for development stability:
# Installing pyenv on macOS
brew install pyenv
# Installing a specific Python version
pyenv install 3.13.2
pyenv global 3.13.2
2. Python Package Management with uv
The rapid package manager named uv should be installed first:
# Installing uv on macOS
brew install uv
# Alternative installation via pip
pip install uv
3. Visual Resource API Credentials
Access to external image libraries requires specific secret keys obtained through developer registration processes for each provider:
Unsplash API Key
- Navigate to the Unsplash Developers portal.
- Complete the registration or login procedure.
- Generate a new application entry.
- Secure your unique Access Key.
Pexels API Key
- Go to the Pexels API documentation page.
- Register or log into your account.
- Submit a request to obtain an API key.
Pixabay API Key
- Consult the Pixabay API documentation.
- Sign up or authenticate.
- Retrieve the required API key for access.
Together AI API Key
- Access the Together AI API Keys management area.
- Authenticate your user session.
- Create and save a new API secret.
4. Cursor IDE
Ensure you have installed the Cursor IDE application. Verify that the integrated Python environment within Cursor is correctly configured to utilize the necessary tool dependencies.
Installation and Configuration
- Obtain the project repository files via cloning:
git clone https://github.com/yanjunz/mcp_search_images.git
- Install the required software dependencies:
python3 -m pip install fastmcp requests
If certificate validation errors occur during installation, you may need to use the following command to bypass strict host checking:
python3 -m pip install fastmcp requests --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade --force-reinstall --no-cache-dir
- Inputting API Secret Values:
Begin by duplicating the template file to create your active configuration file:
# Copy the template to create the main configuration file
cp config.json.template config.json
# Open the file using your preferred editor, such as nano
nano config.json
Modify the parameters within config.json to include your retrieved API credentials. The structure should resemble this example:
{
"api": {
"unsplash_access_key": "Your Unsplash Access Key Here",
"pexels_api_key": "Your Pexels API Key Here",
"pixabay_api_key": "Your Pixabay API Key Here",
"together_api_key": "Your Together API Key Here",
"timeout": 30,
"max_retries": 3,
"retry_delay": 5
},
// ...additional settings...
}
Security Note: It is imperative that the file containing your secret API keys,
config.json, is excluded from any version control system commits. The provided.gitignorefile is set to ignore this file automatically, while the template remains tracked.
Service Execution Methods
Method One: Direct Python Execution
This approach is the most straightforward way to initiate the service:
python3.11 main.py
Upon a successful launch, the console output will confirm service availability and list the registered tools:
启动图片搜索服务 - 端口: 5173
提供的工具: search_images, download_image, generate_icon
INFO: Started server process [xxxxx]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:5173 (Press CTRL+C to quit)
Method Two: Utilizing the fastmcp Command
If the fastmcp package is installed, you can manage the service execution using its integrated commands:
- Running in development mode (enabling debugging features):
fastmcp dev main.py
- Executing in a production-ready configuration:
fastmcp run main.py
- Should the default port (5173) be occupied by another process, specify an alternative port for operation:
PORT=5174 fastmcp dev main.py
Method Three: Execution via uv Manager
When utilizing uv for environment management, you can execute the service as follows:
uv run --with fastmcp fastmcp run main.py
Or, for development execution:
uv run --with fastmcp fastmcp dev main.py
Cursor and MCP Communication Fundamentals
Understanding the interaction protocol is crucial for troubleshooting connectivity issues. This outlines the standard data flow between Cursor and the running MCP service:
- MCP Service Initialization Sequence:
- Executing
python3.11 main.pyinitiates the application and sets up the necessary Server-Sent Events (SSE) listener. - The application commences listening for incoming requests on the designated port (5173 by default).
- The service registers the callable functions:
search_images,download_image, andgenerate_icon. -
For connections utilizing the ServerLink connection method, the service must correctly handle SSE requests directed at the
/ssepathway. -
Cursor Connection Protocol:
- When the MCP tool is added within Cursor's settings interface, the IDE attempts to establish a persistent connection with the provided service URL.
- Cursor transmits an initial handshake request to confirm the service's operational status.
- The running service must reply with a standardized MCP response that accurately enumerates all available integrated tools.
-
A successful connection registers this newly configured tool within Cursor's list of available functionalities.
-
Connectivity Diagnosis Steps:
- Confirming active service listening: Execute
lsof -i :5173in the terminal. - Verifying network accessibility: Attempt a request using
curl http://localhost:5173. - Validating MCP protocol implementation: Check the service startup logs for confirmation of tool registration.
-
Addressing security restrictions: Local services can sometimes be blocked by local firewall configurations.
-
Comprehensive Verification Procedure: ```bash # 1. Terminate any currently active instances of the service pkill -f "python.*main.py"
# 2. Start the service in the foreground to monitor real-time logs python3.11 main.py
# 3. In a separate terminal session, test basic HTTP connectivity curl http://localhost:5173
# 4. Test the specific endpoint required for ServerLink communication curl http://localhost:5173/sse
# 5. Add the MCP tool within Cursor and attempt an initial command execution ```
If connection attempts continue to fail after following these diagnostic steps, investigate potential incompatibilities in the Python version or verify that all necessary dependencies were installed without errors. Reinstalling the required packages occasionally resolves unforeseen dependency conflicts:
python3.11 -m pip uninstall fastmcp mcp uvicorn starlette -y
python3.11 -m pip install fastmcp mcp uvicorn starlette
Instructional Guide
Operation Within the Cursor IDE
-
Guarantee Service Operation:
bash # Launch the service directly using the Python interpreter python3.11 main.pyThe successful startup message will look similar to this:启动图片搜索服务 - 端口: 5173 提供的工具: search_images, download_image, generate_icon INFO: Started server process [xxxxx] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:5173 (Press CTRL+C to quit) -
Registering the MCP Service in Cursor:
- Open the Cursor IDE application.
- Access the main settings by clicking the gear icon in the bottom-left corner.
- Navigate to the 'AI & Copilot' configuration subsection.
- Locate the 'MCP Tools' area and select the option to 'Add MCP Tool'.
- Input the necessary details:
- Name: 图片搜索服务
- Type: SSE (Server-Sent Events)
- URL: http://localhost:5173
- Finalize by clicking 'Save'.
Alternative Configuration Path: * Certain Cursor iterations might mandate the ServerLink configuration format: - Name: 图片搜索服务 - Type: sse - ServerLink: http://localhost:5173/sse - Click 'Save' to confirm.
Troubleshooting 'Fail to create client': If this error appears, review these common points: 1. Verify service activity (use
lsof -i :5173to check port listening status). 2. Test connectivity by accessinghttp://localhost:5173in a standard web browser. 3. Ensure the URL structure is precise, avoiding extra forward slashes or spaces. 4. For ServerLink mode, confirm that the correct endpoint path,/sse, is used. 5. Attempt adding the tool again after stopping and restarting the service. 6. In some cases, restarting the Cursor IDE itself clears prior connection state caches.
- Commencing Tool Utilization:
- Ensure the service is actively running in the background.
- Engage the conversational interface within Cursor (e.g., with Claude).
- The large language model should automatically detect and invoke the registered tool.
-
If automatic detection fails, explicitly instruct the model: "Please utilize the image retrieval service to find assets."
-
On-Demand Resource Sourcing:
- While developing code, if visual assets are needed, describe the requirement directly to the model.
- Example instruction: "Assist me by finding icons suitable for a standard login button interface."
-
The model will query the MCP service, display search results, and permit subsequent actions like downloading or generating custom icons.
-
Locating Saved Graphics:
- By default, downloaded graphics are placed within an
iconssubdirectory created at the root of your project folder. - You can verify the contents of this directory using this command:
bash ls -la icons
Use Case Examples
Retrieving Imagery
Provide directives to the model describing the desired visual content:
Initiate a search for imagery tagged with the term "technology"
or, specify sources and quantity for greater control:
Please source five pictures concerning "artificial intelligence" from the Unsplash catalog.
Fetching Specific Files
After the model presents search results, you can command a download operation for a particular item:
Download the second listed picture and save it using the filename tech-icon.png
Or, specify a precise destination and label:
Transfer the third image result to the directory /Users/username/Desktop/, naming the file ai-image.jpg
Synthesizing Icons
Define necessary stylistic elements when requesting a newly created graphic:
Generate one icon with a blue, technological aesthetic, naming the output blue-tech.png
Or, include detailed graphical specifications:
Create a flat-design representation of an email symbol, using a red border, white background, and dimensioned precisely at 256x256 pixels, saving it as email-icon.png
Illustrative Interaction Sequence
Refer to the document located at [examples/dialog_example.md] for a practical demonstration of conversation flow when using Claude or similar models to search for and generate graphics.
Integration into Development Workflows
- Initial Asset Generation for Projects:
- When establishing a new design language, batch-create multiple requisite icons simultaneously.
-
For instance: "Generate a complete set comprising icons for home, settings, user profile, and notifications."
-
On-Demand Resource Acquisition During Coding:
- Seamlessly search for necessary visual elements at any point during code composition.
-
Example: "I am developing a meteorological application and require several graphics related to weather conditions."
-
Custom Icon Refinement in Project Finalization:
- Standardize icons across the application to match established aesthetic guidelines.
- Example: "Produce a group of social media sharing icons that align perfectly with my application's current visual theme."
Recommended Operational Practices
- Keyword Specificity: Employ precise and unambiguous search terms to yield more accurate retrieval results.
- Source Selection: Choose the appropriate image repository based on the content type sought (e.g., Unsplash for environmental shots, Pixabay for commercial graphics).
- Structured Naming Conventions: Assign filenames systematically, such as using patterns like
theme-assetname-resolution.ext. - Batch Processing: Request multiple related items in a single instruction rather than executing separate calls for each one.
- Contextual Integration: Include relevant code context in prompts; this helps the model interpret user intent more accurately.
Error Resolution Procedures
Cursor MCP Connection Failures
If the process of adding the MCP service in Cursor results in a "Fail to create client" notification, systematically attempt these remediation steps:
-
Verify Service Status:
bash # Confirm if the service process is actively listening lsof -i :5173 # If no process is listed, initiate the service execution python3.11 main.py -
Test Connectivity with cURL:
bash # Use cURL to test the basic HTTP interface responsiveness curl -v http://localhost:5173 -
Adjusting Connection Parameters:
- Confirm that the 'SSE' connection protocol type has been correctly selected.
- Substitute 'localhost' with the loopback IP address:
http://127.0.0.1:5173. - Ensure the URL is clean: use
http://localhost:5173instead ofhttp://localhost:5173/. - Experiment with the ServerLink configuration: Set Type to 'sse' and the ServerLink value to
http://localhost:5173/sse. - Some versions of the IDE might enforce strict URL formatting; testing both standard and ServerLink formats is recommended.
- If issues persist, restart the MCP service and then attempt adding the tool again.
-
In intermittent cases, restarting the Cursor IDE itself can clear outdated connection data.
-
Component Restarts:
- Stop and restart the MCP tool service.
- Initiate a full restart of the Cursor IDE application.
-
If operating on macOS, inspect system firewall settings to ensure local connections are permitted.
-
Log Analysis:
- Closely examine the service console output generated during the initial startup phase.
-
Watch for any new log entries that appear on the server side when Cursor attempts to establish a connection.
-
Port Relocation:
- Modify the configured port within the service source code (e.g., changing it to 5174) and then relaunch the service:
python uvicorn.run(sse_app, host="0.0.0.0", port=5174)
Other Recurring Issues
If you encounter problems beyond connection errors, verify these foundational elements:
- The service process is actively running.
- The file system paths designated for saving are accessible and valid.
- Directory permissions allow write access to target locations.
- Network communication channels are unobstructed.
- All required API secrets are correctly entered and active.
- The Python execution environment is properly configured.
- The uv package manager is correctly installed.
- All necessary dependencies are fully resolved.
Collaboration
Suggestions for improvements, bug reports, and feature enhancements are welcomed via issues and pull requests submitted to the repository.
Licensing
This project is distributed under the terms of the MIT License.
Related Topics
- Web Search Engine Architecture: Understanding how vast collections of data are indexed and queried, similar to how this tool accesses image databases.
- Server-Sent Events (SSE): The protocol used for real-time, unidirectional communication between the service and the client IDE.
- Model Control Protocol (MCP): The specific framework enabling IDEs like Cursor to extend their functionality with external services.
- API Key Management: Secure handling and usage of proprietary access credentials for third-party services.
- Distributed Computing: The underlying concept where processing tasks, like searching global image indexes, are spread across many locations.
Extra Details
Content removed during refactoring primarily consisted of verbose explanations of the initial connection sequence and detailed troubleshooting steps for port conflicts. The essential value retained involves emphasizing that this system acts as a targeted search facilitator. Like global web search engines, which offer diverse results (text, video, images), this MCP tool focuses the search domain specifically onto high-quality visual assets and on-demand graphic synthesis, providing a structure that aids in building richer user interfaces rapidly. The underlying mechanism relies on continuous data fetching, analogous to how search engines maintain constantly updated indexes via web crawlers.
Conclusion
This utility transforms standard query inputs into specific visual outputs, bridging the gap between conceptual needs and project implementation assets. By automating the process of locating and creating images, it significantly enhances the efficiency of development within the MCP ecosystem, streamlining the visual enhancement aspects often requiring external resource acquisition typical in web development contexts.
