MCP Server Template for Cursor IDE

MCP Server Template for Cursor IDE

Okay, here's a template and explanation for creating custom tools for Cursor IDE using the Model Context Protocol (MCP), allowing users to deploy their own MCP server to Heroku and connect it to Cursor IDE. This template focuses on providing a solid foundation and clear instructions. **I. Project Structure** ``` my-cursor-tool/ ├── server/ # MCP Server (Python/Flask) │ ├── app.py # Main Flask application │ ├── requirements.txt # Dependencies │ ├── Procfile # Heroku deployment instructions │ └── .env # Environment variables (API keys, etc.) ├── cursor-extension/ # Cursor IDE Extension (TypeScript) │ ├── package.json # Extension manifest │ ├── src/ │ │ └── extension.ts # Main extension logic │ └── tsconfig.json # TypeScript configuration ├── README.md # Instructions for setup and deployment └── LICENSE # (Optional) License ``` **II. `server/app.py` (MCP Server - Python/Flask)** ```python from flask import Flask, request, jsonify import os import json app = Flask(__name__) # Load environment variables (if any) # Example: OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") @app.route('/.well-known/model-context', methods=['GET']) def model_context_discovery(): """ Returns the Model Context Protocol discovery document. """ discovery_document = { "model_context_protocol_version": "0.1", "capabilities": { "execute": { "path": "/execute", "http_method": "POST", "input_schema": { "type": "object", "properties": { "query": {"type": "string", "description": "The user's query."}, "context": { "type": "object", "description": "Contextual information from the IDE.", "properties": { "selectedText": {"type": "string", "description": "The currently selected text in the editor."}, "languageId": {"type": "string", "description": "The language of the current file."}, "filepath": {"type": "string", "description": "The path to the current file."}, "activeEditorContent": {"type": "string", "description": "The entire content of the active editor."}, }, "required": ["selectedText", "languageId", "filepath", "activeEditorContent"] } }, "required": ["query", "context"] }, "output_schema": { "type": "object", "properties": { "result": {"type": "string", "description": "The result of the execution."} }, "required": ["result"] } } } } return jsonify(discovery_document) @app.route('/execute', methods=['POST']) def execute(): """ Executes the tool based on the user's query and context. """ try: data = request.get_json() query = data['query'] context = data['context'] # --- Your Tool Logic Here --- # Example: Use the query and context to generate a response. # This is where you integrate with your desired service (e.g., OpenAI, a database, etc.) selected_text = context['selectedText'] language_id = context['languageId'] filepath = context['filepath'] active_editor_content = context['activeEditorContent'] # Simple example: Echo the query and selected text. result = f"Query: {query}\nSelected Text: {selected_text}\nLanguage: {language_id}\nFilepath: {filepath}" # --- End of Tool Logic --- return jsonify({"result": result}) except Exception as e: print(f"Error: {e}") # Log the error for debugging return jsonify({"error": str(e)}), 500 # Return an error response if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) # Heroku uses the PORT environment variable app.run(debug=True, host='0.0.0.0', port=port) ``` **III. `server/requirements.txt`** ``` Flask python-dotenv # For local development (optional) ``` **IV. `server/Procfile`** ``` web: gunicorn app:app --log-file - --log-level debug ``` **V. `server/.env` (Optional - for local development)** ``` # Example: # OPENAI_API_KEY=your_openai_api_key ``` **VI. `cursor-extension/package.json`** ```json { "name": "my-cursor-tool", "displayName": "My Cursor Tool", "description": "A custom tool for Cursor IDE.", "version": "0.0.1", "engines": { "vscode": "^1.75.0" // Or the minimum supported version of VS Code/Cursor }, "categories": [ "Other" ], "activationEvents": [ "*" // Activate on all events (adjust as needed) ], "main": "./dist/extension.js", "contributes": { "modelContextProviders": [ { "name": "my-tool", "displayName": "My Tool", "description": "Connects to my custom tool server.", "url": "YOUR_HEROKU_APP_URL" // <--- REPLACE THIS WITH YOUR HEROKU APP URL } ] }, "scripts": { "vscode:prepublish": "npm run compile", "compile": "tsc -p ./", "watch": "tsc -watch -p ./", "pretest": "npm run compile && npm run lint", "lint": "eslint src --ext ts", "test": "node ./out/test/runTest.js" }, "devDependencies": { "@types/vscode": "^1.75.0", // Or the appropriate version "@types/glob": "^8.0.1", "@types/mocha": "^10.0.1", "@types/node": "16.x", "@vscode/test-electron": "^2.2.0", "eslint": "^8.30.0", "@typescript-eslint/eslint-plugin": "^5.45.0", "@typescript-eslint/parser": "^5.45.0", "glob": "^8.1.0", "mocha": "^10.1.1", "typescript": "^4.9.4" } } ``` **VII. `cursor-extension/src/extension.ts`** ```typescript import * as vscode from 'vscode'; export function activate(context: vscode.ExtensionContext) { console.log('Congratulations, your extension "my-cursor-tool" is now active!'); // No specific activation logic needed here, as the Model Context Provider // is declared in package.json and handled by Cursor. } export function deactivate() {} ``` **VIII. `cursor-extension/tsconfig.json`** ```json { "compilerOptions": { "module": "commonjs", "target": "es2020", "lib": [ "es2020" ], "sourceMap": true, "rootDir": "src", "outDir": "dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node" }, "exclude": [ "node_modules", ".vscode-test" ] } ``` **IX. `README.md` (Crucial Instructions)** ```markdown # My Cursor Tool This is a custom tool for Cursor IDE that connects to a server deployed on Heroku using the Model Context Protocol (MCP). ## Prerequisites * **Heroku Account:** You'll need a Heroku account to deploy the server. * **Heroku CLI:** Install the Heroku Command Line Interface (CLI). See [https://devcenter.heroku.com/articles/heroku-cli](https://devcenter.heroku.com/articles/heroku-cli) * **Cursor IDE:** Install Cursor IDE. * **Node.js and npm:** Required for building the Cursor extension. * **Python 3.x:** Required for running the server locally (optional). ## Deployment to Heroku 1. **Login to Heroku:** ```bash heroku login ``` 2. **Create a Heroku App:** ```bash heroku create my-cursor-tool-server # Replace with a unique name ``` 3. **Navigate to the `server` directory:** ```bash cd server ``` 4. **Initialize a Git repository (if you haven't already):** ```bash git init git add . git commit -m "Initial commit" ``` 5. **Push the code to Heroku:** ```bash heroku git:remote -a my-cursor-tool-server # Replace with your app name git push heroku main ``` 6. **Set Environment Variables (if needed):** If your tool requires API keys or other sensitive information, set them as environment variables in Heroku: ```bash heroku config:set OPENAI_API_KEY=your_openai_api_key ``` 7. **Check the Heroku Logs:** After deployment, check the Heroku logs for any errors: ```bash heroku logs --tail ``` ## Installing the Cursor Extension 1. **Navigate to the `cursor-extension` directory:** ```bash cd ../cursor-extension ``` 2. **Install Dependencies:** ```bash npm install ``` 3. **Compile the Extension:** ```bash npm run compile ``` 4. **Open Cursor IDE.** 5. **Open the `cursor-extension` directory in Cursor IDE.** (File -> Open Folder...) 6. **Run the Extension:** * Press `F5` to start the extension in debug mode. This will open a new Cursor window with your extension loaded. ## Connecting the Extension to Your Heroku Server 1. **Get Your Heroku App URL:** Find the URL of your deployed Heroku app. It's usually in the format `https://my-cursor-tool-server.herokuapp.com`. You can find it on the Heroku dashboard for your app. 2. **Update `package.json`:** In the `cursor-extension/package.json` file, replace `YOUR_HEROKU_APP_URL` with the actual URL of your Heroku app in the `contributes.modelContextProviders.url` field. **Make sure to include the `https://` prefix.** ```json "contributes": { "modelContextProviders": [ { "name": "my-tool", "displayName": "My Tool", "description": "Connects to my custom tool server.", "url": "https://my-cursor-tool-server.herokuapp.com" // <--- REPLACE THIS } ] } ``` 3. **Reload the Extension:** After updating `package.json`, you'll need to reload the extension in Cursor IDE. If you're running in debug mode (F5), stop the debugger and run it again. If you installed the extension, you may need to uninstall and reinstall it. ## Using the Tool in Cursor IDE 1. **Open a file in Cursor IDE.** 2. **Select some text.** 3. **Type `@my-tool` followed by your query.** (Replace `my-tool` with the `name` you defined in `package.json`.) 4. **Press Enter.** 5. **The result from your Heroku server should appear in the chat window.** ## Troubleshooting * **Check Heroku Logs:** Use `heroku logs --tail` to see any errors on the server side. * **Check the Cursor IDE Developer Console:** Open the developer console in the Cursor IDE window (Help -> Toggle Developer Tools) to see any errors from the extension. * **Verify the URL:** Double-check that the URL in `package.json` is correct and includes `https://`. * **CORS Issues:** If you encounter CORS (Cross-Origin Resource Sharing) errors, you may need to configure CORS on your Flask server. (This is less likely with Heroku, but possible). You can use the `flask-cors` library. ## License [Your License Here (Optional)] ``` **X. Key Improvements and Explanations** * **Clear Project Structure:** Organized into `server` and `cursor-extension` directories for clarity. * **Complete `app.py`:** Includes the `/model-context` discovery endpoint and a basic `/execute` endpoint. The `/execute` endpoint now receives and prints the context data. Error handling is included. * **`Procfile` for Heroku:** Specifies how to run the Flask app on Heroku. * **Detailed `README.md`:** Provides step-by-step instructions for deployment, installation, and usage. Includes troubleshooting tips. This is the *most important* part for user-friendliness. * **Environment Variables:** Demonstrates how to use environment variables for API keys (important for security). * **Error Handling:** The server includes basic error handling to catch exceptions and return appropriate error responses to Cursor. * **CORS Note:** Adds a note about CORS issues and how to address them if they arise. * **`extension.ts`:** Kept minimal, as the core logic is handled by the MCP. * **Up-to-date Dependencies:** Uses more recent versions of dependencies. * **Heroku CLI Instructions:** Provides specific Heroku CLI commands. * **Debugging Tips:** Includes instructions for checking Heroku logs and the Cursor IDE developer console. * **Explicit URL Instructions:** Emphasizes the importance of the correct Heroku app URL in `package.json`. * **Example Tool Logic:** Provides a simple example of how to access the query and context data within the `/execute` endpoint. * **Gunicorn:** Uses Gunicorn, a production-ready WSGI server, in the `Procfile`. **XI. How to Use This Template** 1. **Clone the Template:** Copy the file structure and code into your own project. 2. **Implement Your Tool Logic:** Modify the `server/app.py` file to implement the core logic of your tool within the `/execute` endpoint. This is where you'll integrate with your desired services (e.g., OpenAI, a database, etc.). 3. **Deploy to Heroku:** Follow the instructions in the `README.md` file to deploy the server to Heroku. 4. **Install the Cursor Extension:** Follow the instructions in the `README.md` file to install the Cursor extension. 5. **Connect the Extension:** Update the `package.json` file with your Heroku app URL. 6. **Test Your Tool:** Use the tool in Cursor IDE by typing `@my-tool` followed by your query. **XII. Important Considerations** * **Security:** Be very careful about handling sensitive data (API keys, user credentials, etc.). Use environment variables and avoid hardcoding secrets in your code. * **Scalability:** For more complex tools, consider using a more scalable architecture for your server (e.g., using a database, message queue, etc.). * **Error Handling:** Implement robust error handling in your server to gracefully handle unexpected errors. * **Rate Limiting:** If you're using an external API, be mindful of rate limits and implement appropriate rate limiting in your server. * **User Experience:** Design your tool to be easy to use and provide helpful feedback to the user. * **Asynchronous Operations:** For long-running tasks, consider using asynchronous operations (e.g., using Celery or similar) to avoid blocking the Flask server. This template provides a solid starting point for creating custom tools for Cursor IDE using the Model Context Protocol. Remember to adapt the code and instructions to your specific needs. Good luck!

开发者工具
云平台
虚拟化
Python
访问服务器

Tools

mcp_fetch

Fetches a website and returns its content

mood

Ask the server about its mood - it's always happy!

README

用于 Cursor IDE 的 MCP 服务器模板

一个使用模型上下文协议 (MCP) 为 Cursor IDE 创建自定义工具的简单模板。从此模板创建您自己的存储库,修改工具,并将它们连接到您的 Cursor IDE。

服务器心情响应

快速开始

  1. 点击 "Deploy to Heroku" 按钮

    部署到 Heroku

  2. 部署后,配置 Cursor:

    • 打开 Cursor 设置 → 功能
    • 添加新的 MCP 服务器
    • 使用您的 Heroku URL,并加上 /sse 路径 (例如,https://<your-app-name>.herokuapp.com/sse)
  3. 在 Cursor 中测试您的代理的心情:

    • 询问您的代理 "Please ask about our server mood and let me know how it is." (请询问我们服务器的心情,并告诉我它的状态。)
    • 服务器将回复一条欢快的信息和一个心 ❤️

其他设置方法

您可以通过三种方式运行服务器:使用 Docker、传统的 Python 设置或直接在 Cursor IDE 中运行。

Docker 设置

该项目包含 Docker 支持,方便部署:

  1. 初始设置:
# 克隆存储库
git clone https://github.com/kirill-markin/weaviate-mcp-server.git
cd weaviate-mcp-server

# 创建环境变量文件
cp .env.example .env
  1. 使用 Docker Compose 构建和运行:
# 构建并启动服务器
docker compose up --build -d

# 查看日志
docker compose logs -f

# 检查服务器状态
docker compose ps

# 停止服务器
docker compose down
  1. 服务器将在以下位置可用:

    • SSE 端点: http://localhost:8000/sse
  2. 快速测试:

# 测试服务器端点
curl -i http://localhost:8000/sse
  1. 连接到 Cursor IDE:
    • 打开 Cursor 设置 → 功能
    • 添加新的 MCP 服务器
    • 类型: 选择 "sse"
    • URL: 输入 http://localhost:8000/sse

传统设置

首先,安装 uv 包管理器:

# 在 macOS 上安装 uv
brew install uv
# 或者通过 pip 安装 (任何操作系统)
pip install uv

使用 stdio (默认) 或 SSE 传输启动服务器:

# 安装包含开发依赖项的包
uv pip install -e ".[dev]"

# 使用 stdio 传输 (默认)
uv run mcp-simple-tool

# 使用自定义端口上的 SSE 传输
uv run mcp-simple-tool --transport sse --port 8000

# 运行测试
uv run pytest -v

安装完成后,您可以将服务器直接连接到 Cursor IDE:

  1. 在 Cursor 中右键单击 cursor-run-mcp-server.sh 文件
  2. 选择 "Copy Path" 以复制绝对路径
  3. 打开 Cursor 设置 (齿轮图标)
  4. 导航到 "Features" 选项卡
  5. 向下滚动到 "MCP Servers"
  6. 点击 "Add new MCP server"
  7. 填写表格:
    • Name: 选择任何名称 (例如,"my-mcp-server-1")
    • Type: 选择 "stdio" (不是 "sse",因为我们在本地运行服务器)
    • Command: 粘贴您之前复制的 cursor-run-mcp-server.sh 的绝对路径。例如:/Users/kirillmarkin/weaviate-mcp-server/cursor-run-mcp-server.sh

环境变量

可用的环境变量 (可以在 .env 中设置):

  • MCP_SERVER_PORT (默认: 8000) - 服务器运行的端口
  • MCP_SERVER_HOST (默认: 0.0.0.0) - 服务器绑定的主机
  • DEBUG (默认: false) - 启用调试模式
  • MCP_USER_AGENT - 用于网站获取的自定义 User-Agent

其他选项

通过 Smithery 安装

smithery badge

要通过 Smithery 为 Claude Desktop 自动安装用于 Cursor IDE 的 MCP 服务器模板:

npx -y @smithery/cli install @kirill-markin/example-mcp-server --client claude

Glama 服务器评论

<a href="https://glama.ai/mcp/servers/jgisqn8zco"><img width="380" height="200" src="https://glama.ai/mcp/servers/jgisqn8zco/badge" alt="Server Template for Cursor IDE MCP server" /></a>

推荐服务器

Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Claude Code MCP

Claude Code MCP

一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。

精选
本地
JavaScript
@kazuph/mcp-taskmanager

@kazuph/mcp-taskmanager

用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。

精选
本地
JavaScript
MCP Package Docs Server

MCP Package Docs Server

促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。

精选
本地
TypeScript
mermaid-mcp-server

mermaid-mcp-server

一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。

精选
JavaScript
Jira-Context-MCP

Jira-Context-MCP

MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。

精选
TypeScript
Tavily MCP Server

Tavily MCP Server

使用 Tavily 的搜索 API 提供 AI 驱动的网络搜索功能,使 LLM 能够执行复杂的网络搜索、获得问题的直接答案以及搜索最近的新闻文章。

精选
Python
Linear MCP Server

Linear MCP Server

一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

精选
JavaScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

精选
Python
MCP Server Template for Cursor IDE