Pular para o conteúdo principal

How to use the MCP servers (the SSE URL)

Model Context Protocol (MCP) servers are a powerful feature in Cursor that enables enhanced AI capabilities through specialized servers. This guide will walk you through understanding and utilizing MCP servers with Server-Sent Events (SSE) URLs to extend Cursor's functionality.

Introduction to MCP Servers and SSE

MCP (Model Context Protocol) servers act as specialized middleware between Cursor and various AI models or services. They provide additional context, tools, and capabilities that enhance Cursor's AI features. Server-Sent Events (SSE) is a technology that allows servers to push updates to clients over HTTP connections, enabling real-time communication.

What are MCP Servers?

MCP servers are specialized servers that implement the Model Context Protocol, allowing Cursor to:

  • Access additional tools and resources
  • Connect to external APIs and services
  • Process and transform data before sending it to AI models
  • Extend Cursor's capabilities with custom functionality

Why Use SSE URLs?

SSE (Server-Sent Events) URLs provide a standardized way to establish connections between Cursor and MCP servers, offering:

  • Real-time updates and streaming responses
  • Efficient one-way communication from server to client
  • Automatic reconnection handling
  • Compatibility with standard HTTP infrastructure

Understanding SSE URL Structure

An SSE URL for MCP servers typically follows this structure:

http(s)://<hostname>:<port>/sse?token=<auth_token>

Components explained:

  • Protocol: Either http:// or https:// (secure, recommended)
  • Hostname: Server address (e.g., localhost, mcp.example.com)
  • Port: The port number the MCP server is listening on (e.g., 3000)
  • Path: Usually /sse for Server-Sent Events endpoint
  • Token: Authentication token for secure access

Configuration Steps

Setting up and using MCP servers with SSE URLs involves several steps:

1. Install Required Dependencies

First, ensure you have the necessary dependencies installed:

npm install @modelcontextprotocol/sdk

2. Create MCP Server Configuration

Create a configuration file for your MCP server. This can be placed in Cursor's configuration directory:

{
"mcpServers": {
"example-server": {
"command": "node",
"args": ["/path/to/your/mcp-server.js"],
"env": {
"API_KEY": "your-api-key-here",
"OTHER_ENV_VAR": "value"
},
"disabled": false,
"autoApprove": ["tool1", "tool2"]
}
}
}

3. Set Up SSE Connection

In your MCP server implementation, set up the SSE endpoint:

import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());

app.get('/sse', (req, res) => {
// Validate token
const token = req.query.token;
if (!validateToken(token)) {
return res.status(401).send('Unauthorized');
}

// Set headers for SSE
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');

// Send initial connection message
res.write('event: connected\ndata: {"status": "connected"}\n\n');

// Handle client disconnect
req.on('close', () => {
console.log('Client disconnected');
});

// Set up periodic messages or response to events
// ...
});

app.listen(3000, () => {
console.log('MCP Server listening on port 3000');
});

4. Configure Cursor to Use Your MCP Server

Add your MCP server configuration to Cursor's settings:

  1. Open Cursor
  2. Go to Settings (⚙️)
  3. Search for "MCP"
  4. Add your server configuration
  5. Save changes

Usage Examples

Here are some practical examples of using MCP servers with SSE URLs:

Example 1: Basic Tool Implementation

// In your MCP server implementation
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'weather_lookup',
description: 'Get current weather for a location',
inputSchema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name or zip code'
}
},
required: ['location']
}
}
]
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'weather_lookup') {
const location = request.params.arguments.location;
const weatherData = await fetchWeatherData(location);

return {
content: [
{
type: 'text',
text: JSON.stringify(weatherData, null, 2)
}
]
};
}
});

Example 2: Resource Implementation

server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [
{
uri: 'docs://api/reference',
name: 'API Reference Documentation',
mimeType: 'text/markdown',
description: 'Complete API reference for the project'
}
]
}));

server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri === 'docs://api/reference') {
return {
contents: [
{
uri: request.params.uri,
mimeType: 'text/markdown',
text: await fs.readFile('path/to/api-docs.md', 'utf-8')
}
]
};
}
});

Troubleshooting Common Issues

Connection Refused

Problem: Cursor cannot connect to the MCP server.

Solutions:

  • Verify the server is running
  • Check firewall settings
  • Ensure the port is correct and accessible
  • Validate the hostname resolves correctly

Authentication Failures

Problem: "Unauthorized" errors when connecting.

Solutions:

  • Check that the token is correctly configured
  • Verify token validation logic
  • Ensure environment variables are properly set

Server Crashes

Problem: MCP server crashes unexpectedly.

Solutions:

  • Implement proper error handling
  • Add logging to identify issues
  • Check for memory leaks
  • Validate input data before processing

Slow Responses

Problem: MCP server responses are slow.

Solutions:

  • Optimize server code
  • Implement caching where appropriate
  • Consider scaling resources
  • Check for blocking operations

Best Practices

Security

  • Always use HTTPS for production MCP servers
  • Implement proper authentication and authorization
  • Validate all inputs to prevent injection attacks
  • Limit exposed functionality to only what's necessary

Performance

  • Implement caching for frequently accessed resources
  • Use efficient data structures and algorithms
  • Consider streaming responses for large data
  • Monitor server performance and optimize bottlenecks

Reliability

  • Implement proper error handling
  • Add logging for debugging
  • Set up health checks
  • Implement automatic restarts for crashed servers

Development Workflow

  • Use a local development environment for testing
  • Implement versioning for your MCP servers
  • Document your server's capabilities and requirements
  • Create automated tests for your server functionality

Conclusion

MCP servers with SSE URLs provide a powerful way to extend Cursor's capabilities with custom functionality and external services. By following the configuration steps and best practices outlined in this guide, you can create robust, secure, and efficient MCP servers that enhance your development workflow.

Whether you're connecting to external APIs, implementing custom tools, or providing additional context to AI models, MCP servers offer a flexible and standardized approach to extending Cursor's functionality.

Additional Resources