A MCP (Model Context Protocol) server that seamlessly integrates with Cursor's Background Agents API. This server enables LLMs to programmatically create, manage, and interact with Cursor's powerful background agents for autonomous code development.
🤖 Agent Management
- Create and manage background agents
- Monitor agent status and progress
- Add followup instructions to running agents
- Delete agents when no longer needed
📊 Repository & Model Access
- List accessible GitHub repositories
- Get available AI models for agents
- Retrieve API key information
💬 Communication & History
- Access agent conversation history
- Real-time status updates
- Comprehensive error handling
🛡️ Quality & Security
- Automated CI/CD with GitHub Actions
- Branch protection rules for main branch
- Pre-push hooks for local safety
- ESLint code quality checks
- Security vulnerability scanning
# Install globally
npm install -g cursor-agent-mcp
# Or use npx (no installation required)
npx cursor-agent-mcpAdd this to your MCP client configuration (e.g., Claude Desktop's claude_desktop_config.json):
{
"mcpServers": {
"cursor-background-agents": {
"command": "npx",
"args": ["cursor-agent-mcp@latest"],
"env": {
"CURSOR_API_KEY": "your_cursor_api_key_here",
"CURSOR_API_URL": "https://api.cursor.com"
}
}
}
}- Clone the repository
- Install dependencies:
npm install
This repository uses branch protection rules to ensure code quality and prevent direct pushes to the main branch.
-
Create a feature branch:
git checkout -b feature/your-feature-name
-
Make your changes and commit:
git add . git commit -m "Add your feature description"
-
Push your feature branch:
git push origin feature/your-feature-name
-
Create a Pull Request on GitHub
- ✅ Tests: All tests must pass
- ✅ Linting: Code must pass ESLint checks
- ✅ Security: Vulnerability scanning
- ✅ Integration: MCP client tests
A pre-push hook prevents accidental pushes to main and runs tests before any push.
git push --no-verify # Bypasses hooks (use with extreme caution)To integrate this MCP server with Cursor's Background Agents, follow these steps:
- Open Cursor IDE
- Go to Settings → Features → Background Agents
- Generate or copy your API key from the Background Agents section
- Keep this key secure - it provides full access to your Cursor account
Add this server to your MCP client configuration:
{
"mcpServers": {
"cursor-background-agents": {
"command": "npx",
"args": ["cursor-agent-mcp@latest"],
"env": {
"CURSOR_API_KEY": "your_cursor_api_key_here",
"CURSOR_API_URL": "https://api.cursor.com"
}
}
}
}For Claude Desktop, add to your claude_desktop_config.json:
{
"mcpServers": {
"cursor-background-agents": {
"command": "npx",
"args": ["cursor-agent-mcp@latest"],
"env": {
"CURSOR_API_KEY": "your_cursor_api_key_here",
"CURSOR_API_URL": "https://api.cursor.com"
}
}
}
}For Codex CLI, add to your ~/.codex/config.toml:
# IMPORTANT: the top-level key is `mcp_servers` rather than `mcpServers`.
[mcp_servers.cursor-background-agents]
command = "npx"
args = ["cursor-agent-mcp@latest"]
env = { "CURSOR_API_KEY" = "your_cursor_api_key_here", "CURSOR_API_URL" = "https://api.cursor.com" }Note: Codex CLI uses TOML format instead of JSON, and the configuration key is mcp_servers (with underscore) rather than mcpServers (camelCase).
For OpenAI Platform and ChatGPT integration, you can self-host this MCP server and make it accessible via the internet.
- Node.js 18+
- Your Cursor API key
- ngrok (for quick public access) or cloud hosting
-
Clone and setup:
git clone https://github.com/griffinwork40/cursor-agent-mcp.git cd cursor-agent-mcp npm install -
Configure your API key:
# Create .env file echo "CURSOR_API_KEY=your_cursor_api_key_here" > .env echo "PORT=3000" >> .env
-
Start the server:
npm start
-
Make it public with ngrok:
# In a new terminal ngrok http 3000 -
Get your public URL (e.g.,
https://abc123.ngrok-free.app)
In ChatGPT Settings → Connectors:
- Name:
cursor-agent-mcp - Description:
MCP server for Cursor Background Agents API - MCP Server URL:
https://your-ngrok-url.ngrok-free.app(base URL only) - Authentication: None (uses global API key from .env)
- Trust checkbox: ✅ Checked
✅ Working Configuration:
✅ URL: https://abc123.ngrok-free.app
✅ Auth: None
✅ Trust: Checked
❌ Common Mistakes:
❌ URL: https://abc123.ngrok-free.app/sse?token=... (don't use SSE endpoint)
❌ Auth: OAuth (OAuth is for advanced setups)
❌ Missing API key in .env
For OpenAI Platform integration:
- Server URL:
https://your-ngrok-url.ngrok-free.app - Authentication: None (server uses global API key)
- Available Tools: 13 Cursor agent management tools
API Endpoints Available:
POST /- Main MCP protocol endpointPOST /mcp- Alternative MCP endpointGET /sse- Server-Sent Events for real-time connectionsGET /health- Health checkGET /.well-known/oauth-authorization-server- OAuth discovery
With API Key Authentication (if you want per-request keys):
# ChatGPT can send API key in Authorization header
curl -X POST https://your-server.com/ \
-H "Authorization: Bearer key_your_cursor_api_key" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'With Token-based URLs (for sharing):
# Visit your server's /connect endpoint
curl https://your-server.com/connect
# Enter your API key to get a tokenized URLRailway (Recommended):
# Deploy to Railway
railway login
railway init
railway add
railway deployHeroku:
# Deploy to Heroku
heroku create your-cursor-agent-mcp
heroku config:set CURSOR_API_KEY=your_key_here
git push heroku mainAWS/DigitalOcean/etc.:
- Deploy as a standard Node.js app
- Set environment variables
- Ensure port 3000 (or your chosen port) is accessible
- Configure HTTPS for production use
For Production Deployment:
- Use HTTPS: Always use HTTPS in production
- Secure API Keys: Use environment variables, never commit keys
- Rate Limiting: Consider adding rate limiting for public endpoints
- Access Control: Optionally add IP whitelisting or authentication
- Monitoring: Set up logging and monitoring for production use
Optional Security Enhancements:
# Add MCP_SERVER_TOKEN for SSE endpoint protection
echo "MCP_SERVER_TOKEN=$(openssl rand -hex 32)" >> .envTest the connection:
# Health check
curl https://your-server.com/health
# Test MCP protocol
curl -X POST https://your-server.com/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
# Should return 13 Cursor agent toolsVerify in ChatGPT:
- Add the connector with base URL
- Look for 13 available tools in the tool picker
- Test with: "List my cursor agents" or "Create a cursor agent for my repo"
If you're running from source code, use this configuration instead:
{
"mcpServers": {
"cursor-background-agents": {
"command": "node",
"args": ["/path/to/cursor-agent-mcp/src/index.js"],
"env": {
"CURSOR_API_KEY": "your_cursor_api_key_here",
"CURSOR_API_URL": "https://api.cursor.com"
}
}
}
}Create a .env file in the project root:
# Required
CURSOR_API_KEY=your_cursor_api_key_here
# Optional
PORT=3000
CURSOR_API_URL=https://api.cursor.com# Start with auto-reload
npm run dev
# Run tests
npm test/mcp- MCP protocol endpoint for LLM interaction/health- Health check endpoint with uptime info
This server provides 13 powerful tools that enable LLMs to fully manage Cursor's Background Agents:
The createAgent tool features automatic PR creation:
- ✅ Default Enabled:
autoCreatePrdefaults totruefor all agents - 🎛️ Override: Explicitly set
autoCreatePr: falseto disable PR creation - 🛡️ Safe Defaults: Ensures pull requests are created by default
This ensures pull requests are automatically created when agents complete their work, providing a consistent workflow for code changes.
Purpose: High-level helper to create an agent using curated templates.
Templates: docAudit, typeCleanup, bugHunt
Example Input:
{
"template": "docAudit",
"params": { "docPaths": ["docs/**/*.md"], "guidelines": "Be concise." },
"model": "auto",
"source": { "repository": "https://github.com/user/repo", "ref": "main" },
"target": { "autoCreatePr": true, "branchName": "audit-docs" }
}Behavior: Validates inputs and composes createAgent with a rendered prompt.
Purpose: Create a new background agent to work on a repository Key Features:
- 📝 Support for text and image prompts
- 🎯 Custom model selection
- 🌿 Branch and PR configuration
- 🔔 Webhook notifications
- ⚙️ Auto-PR creation (defaults to true)
Example Input:
{
"prompt": {
"text": "Fix all TypeScript errors in the project and add proper type definitions"
},
"model": "default",
"source": {
"repository": "https://github.com/user/repo",
"ref": "main"
},
"target": {
"autoCreatePr": true,
"branchName": "fix/typescript-errors"
}
}Purpose: Retrieve all background agents for the authenticated user Features:
- 📄 Pagination support (1-100 agents per request)
- 📊 Agent status overview
- 📅 Creation date sorting
- 🔍 Cursor-based navigation
Purpose: Produce a quick dashboard with totals, recent activity, and in-progress timers Highlights:
- 📈 Counts agents per status after applying filters
- 🧭 Lists the five most recent matching agents
- ⏱️ Shows elapsed time for creating or running agents when available
- 🧩 Returns structured JSON in the response for downstream automation
Filters are applied before aggregation—use status or repository (substring match) to focus on specific pipelines without skewing totals.
Example Call:
const summary = await mcp.call('summarizeAgents', {
status: 'RUNNING',
repository: 'example/repo',
limit: 75,
});
console.log(summary.content[0].text);
// Access machine-readable aggregates
const dashboard = summary.content[1].json;Purpose: Retrieve detailed status and results of a specific agent Returns:
- 📊 Current status with emoji indicators
- 📝 Agent summary and progress
- 🌐 Direct links to view results
- 🌿 Branch and repository information
- 📅 Creation and update timestamps
Purpose: Permanently delete a background agent Features:
⚠️ Permanent deletion (cannot be undone)- 🛡️ Confirmation response
- 🗑️ Cleanup of associated resources
Purpose: Send additional instructions to a running agent Capabilities:
- 💬 Text instructions
- 🖼️ Image attachments
- 🔄 Real-time agent updates
- 📝 Conversation threading
Purpose: Create an agent and internally poll until it reaches a terminal status.
Returns: { finalStatus, agentId, elapsedMs, agent }
Configurable Options:
pollIntervalMs(default 2000)timeoutMs(default 600000)jitterRatio(default 0.1)
Example Input:
{
"prompt": { "text": "Refactor utils for readability and add tests" },
"source": { "repository": "https://github.com/user/repo", "ref": "main" },
"model": "auto",
"pollIntervalMs": 1500,
"timeoutMs": 900000
}Example Output:
{
"finalStatus": "FINISHED",
"agentId": "bc_abc123",
"elapsedMs": 84217,
"agent": { "id": "bc_abc123", "status": "FINISHED" }
}Purpose: Cancel a running createAndWait operation using its cancel token.
Features:
- 🛑 Cooperative cancellation of long-running operations
- 🔄 Safe termination without data loss
- ⏱️ Immediate response to cancellation requests
Example Input:
{
"cancelToken": "build-123"
}Purpose: Access the complete conversation history of an agent Features:
- 💬 Full message history
- 👤 User and assistant message types
- 📊 Message count statistics
- 🔍 Recent message preview
Purpose: Retrieve information about the current API key Returns:
- 🔑 API key name and creation date
- 👤 Associated user email
- 📊 Account status information
Purpose: Get list of recommended models for background agents Features:
- 🤖 All supported AI models
- 📋 Model recommendations
- 🎯 Optimized for different tasks
Purpose: List GitHub repositories accessible to the user Returns:
- 📁 Repository names and owners
- 🔗 Full repository URLs
- 📊 Access permissions
- 🌐 Direct GitHub links
Purpose: Provide structured usage information for LLMs and clients Features:
- 📘 Returns endpoints, auth methods, and protocol version
- 🧰 Lists all available tools with input schemas
- 🧾 Example
tools/listandtools/callpayloads - 🧩 Supports
formatargument:markdown(default) orjson
Example Input:
{ "format": "json" }Example Output: Human-readable markdown plus a second content item containing structured data.
Here are practical examples of how to use the Background Agents API through this MCP server:
// 1. First, check what repositories you have access to
const repos = await mcp.call('listRepositories');
console.log('Available repos:', repos.repositories);
// 2. Check available AI models
const models = await mcp.call('listModels');
console.log('Available models:', models.models);
// 3. Create a new background agent
const newAgent = await mcp.call('createAgent', {
prompt: {
text: `Please review this codebase and:
1. Fix any TypeScript errors
2. Add missing unit tests for core functions
3. Update documentation for new features
4. Optimize performance bottlenecks`
},
model: 'default',
source: {
repository: 'https://github.com/myuser/my-project',
ref: 'main'
},
target: {
autoCreatePr: true,
branchName: 'agent/code-improvements'
}
});
console.log('Created agent:', newAgent.agentId);
// 4. Monitor agent progress
const agentStatus = await mcp.call('getAgent', {
id: newAgent.agentId
});
console.log('Agent status:', agentStatus.status);
// 5. Add followup instructions if needed
if (agentStatus.status === 'RUNNING') {
await mcp.call('addFollowup', {
id: newAgent.agentId,
prompt: {
text: "Also please add ESLint configuration with strict rules"
}
});
}
// 6. View conversation history
const conversation = await mcp.call('getAgentConversation', {
id: newAgent.agentId
});
console.log('Messages:', conversation.messages.length);{
"prompt": {
"text": "There's a critical bug in the user authentication flow. Please investigate and fix the login issues reported in GitHub issues #123 and #124."
},
"model": "default",
"source": {
"repository": "https://github.com/company/webapp",
"ref": "main"
},
"target": {
"autoCreatePr": true,
"branchName": "hotfix/auth-login-bug"
}
}{
"prompt": {
"text": "Implement a new dark mode toggle feature with the following requirements:\n- System preference detection\n- Persistent user choice\n- Smooth transitions\n- Accessibility compliance"
},
"model": "default",
"source": {
"repository": "https://github.com/company/frontend",
"ref": "develop"
},
"target": {
"autoCreatePr": true,
"branchName": "feature/dark-mode-toggle"
}
}{
"prompt": {
"text": "Update all documentation files:\n- Add comprehensive API documentation\n- Create setup guides for new developers\n- Add code examples for all public methods\n- Update README with latest features"
},
"model": "default",
"source": {
"repository": "https://github.com/company/api-server"
},
"target": {
"autoCreatePr": true,
"branchName": "docs/comprehensive-update"
}
}{
"prompt": {
"text": "Improve test coverage by:\n- Adding unit tests for untested components\n- Creating integration tests for API endpoints\n- Adding E2E tests for critical user flows\n- Setting up test data factories"
},
"model": "default",
"source": {
"repository": "https://github.com/company/app"
},
"target": {
"autoCreatePr": true,
"branchName": "test/improve-coverage"
}
}// Get all your agents
const allAgents = await mcp.call('listAgents', { limit: 50 });
// Check each agent's status
for (const agent of allAgents.agents) {
const details = await mcp.call('getAgent', { id: agent.id });
console.log(`${agent.name}: ${details.status}`);
// Get conversation for running agents
if (details.status === 'RUNNING') {
const conversation = await mcp.call('getAgentConversation', {
id: agent.id
});
console.log(` Messages: ${conversation.messageCount}`);
}
}const { content } = await mcp.call('summarizeAgents', {
repository: 'company/app',
status: 'RUNNING',
});
// Human-readable overview in the first block
console.log(content[0].text);
// Structured aggregates for automation in the second block
const dashboard = content[1].json;
console.log(dashboard.statusCounts.RUNNING, 'agents in progress');const agents = await mcp.call('listAgents');
for (const agent of agents.agents) {
if (agent.status === 'FINISHED' || agent.status === 'ERROR') {
await mcp.call('deleteAgent', { id: agent.id });
console.log(`Deleted agent: ${agent.name}`);
}
}The server includes enterprise-grade error handling with:
- 🔐 Input Validation: All inputs validated using Zod schemas
- 📊 HTTP Status Mapping: Proper error codes mapped to HTTP status codes
- 📝 Detailed Messages: Informative error messages with context
- 🏗️ Structured Responses: Consistent error response format
- 📋 Comprehensive Logging: Full request/response logging for debugging
| Error Type | Status | Description |
|---|---|---|
ValidationError |
400 | ❌ Input validation failures |
AuthenticationError |
401 | 🔑 Invalid or missing API key |
AuthorizationError |
403 | 🚫 Insufficient permissions |
NotFoundError |
404 | 🔍 Resource not found |
ConflictError |
409 | ⚔️ Resource conflict |
RateLimitError |
429 | 🚦 Rate limit exceeded |
ApiError |
500 | ⚡ General API errors |
# Run comprehensive error handling tests
node test-error-handling.js
# Test with curl examples
bash test-curl-examples.shConfigure the server using environment variables:
| Variable | Default | Required | Description |
|---|---|---|---|
PORT |
3000 |
❌ | Server port number |
CURSOR_API_KEY |
- | ✅ | Your Cursor API key |
CURSOR_API_URL |
https://api.cursor.com |
❌ | Cursor API base URL |
# Production
npm start # 🏃 Start the server
# Development
npm run dev # 🔄 Start with auto-reload (nodemon)
npm test # 🧪 Run tests (Jest configured)
# Testing
node test-mcp-client.js # 🔧 Test MCP client
node test-error-handling.js # 🛡️ Test error handling
bash test-curl-examples.sh # 🌐 Test with curlThe server includes comprehensive observability:
- 📥 Request/Response Logging: Full HTTP request/response details
- 🔧 API Call Logging: Cursor API interaction logging
- 🚨 Error Logging: Detailed error logs with stack traces
- 💓 Health Monitoring: Health check endpoint with uptime info
- 📈 Performance Metrics: Request timing and success rates
Monitor server health:
curl http://localhost:3000/healthResponse:
{
"status": "ok",
"timestamp": "2025-01-23T10:30:00.000Z",
"version": "1.0.0",
"uptime": 3600.5
}FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY src/ ./src/
EXPOSE 3000
CMD ["npm", "start"]# Production environment
export NODE_ENV=production
export PORT=3000
export CURSOR_API_KEY=your_production_key
# Start server
npm start- Health checks at
/health - Structured logging for observability
- Graceful shutdown handling
- Process management ready
# Error: Invalid or missing API key
# Solution: Verify your CURSOR_API_KEY is correct
echo $CURSOR_API_KEY# Error: Connection refused
# Solution: Check if server is running
curl http://localhost:3000/health# Error: Tool 'createAgent' not found
# Solution: Verify MCP client configuration
npx cursor-agent-mcp --help# Enable debug logging
DEBUG=* npm start
# Or with environment variable
NODE_ENV=development npm start# Check server status
curl http://localhost:3000/health
# Expected response:
{
"status": "ok",
"timestamp": "2025-01-23T10:30:00.000Z",
"version": "1.0.5",
"uptime": 3600.5
}A: Open Cursor IDE → Settings → Features → Background Agents → Generate API Key
A: Yes! This server is compatible with any MCP client that supports HTTP transport.
A: createAgent returns immediately after creating the agent, while createAndWait polls until completion.
A: This depends on your Cursor subscription tier. Check your account limits in the Cursor dashboard.
A: Yes, use the deleteAgent tool to stop and remove a running agent.
A: The server never logs your API key, but the bundled CLI persists it to ~/.config/cursor-agent-mcp/config.json by default so it can reuse the credential. Use environment variables if you prefer not to write the key to disk and make sure the config file is stored on a trusted machine with appropriate filesystem permissions.
Complete API documentation for all MCP tools, including request/response schemas, error codes, and examples:
- 📖 API Reference - Comprehensive tool documentation
- 🔧 All 13 MCP Tools - Detailed parameter specifications
- 🚨 Error Handling - Complete error code reference
- 💡 Usage Examples - Practical implementation examples
- 📋 Changelog - Version history and release notes
Security best practices and configuration guidance:
- 🛡️ Security Documentation - Comprehensive security guide
- 🔑 Authentication Model - API key security and rotation
- 🔐 Production Deployment - Secure configuration examples
- 🚨 Incident Response - Security monitoring and response procedures
- 📝 Contributing Guide - How to contribute to this project
- 🧪 Testing Guide - Testing procedures and examples
- 📊 Changelog - Version history and updates
- 🐛 Issues - Report bugs or request features
- Make sure you restarted Claude Desktop completely
- Check that your API key is correct (no extra spaces or characters)
- Verify you have a Cursor subscription (free accounts won't work)
- Double-check your API key is valid
- Make sure you saved the config file properly
- Try restarting Claude Desktop again
- Make sure the file is named exactly
claude_desktop_config.json - Check you have permission to save files in that folder
- Try using a different text editor
- This usually means the system is downloading the required files
- Wait a few minutes and try again
- Make sure you have an internet connection
- Check that your input data matches the required schema
- Ensure all required fields are provided
- Verify your API key has the necessary permissions
- Verify your
CURSOR_API_KEYis set correctly in your environment - Check that the API key starts with
key_ - Ensure the API key hasn't expired
- GitHub Issues: Report bugs or request features
- Documentation: Check the API Reference for detailed tool documentation
- Testing: Use the testing guide to verify your setup
We welcome contributions! Please see our Contributing Guide for details on:
- Development Setup - How to get started with local development
- Code Standards - Coding style and conventions
- Testing Guidelines - How to write and run tests
- Pull Request Process - How to submit changes
- Issue Reporting - How to report bugs and request features
- Fork the repository on GitHub
- Clone your fork locally
- Install dependencies:
npm install - Create a feature branch:
git checkout -b feature/your-feature-name - Make your changes and test them
- Submit a pull request
For detailed information, see the Contributing Guide.
✅ Production Ready - Comprehensive error handling and validation
✅ Full Feature Coverage - All 13 Cursor Background Agent API endpoints
✅ Developer Friendly - Extensive documentation and examples
✅ Type Safe - Zod schema validation for all inputs
✅ Observable - Detailed logging and monitoring
✅ Tested - Comprehensive test suite included
✅ Maintained - Active development and support
🚀 Ready to supercharge your development workflow with AI-powered background agents!