agentleFS
skywinderskywinder/osm-edit-mcp/.cursor/rules/mcp-development.mdc

osm-edit-mcp / rules

Cursor rule4 starsChanged 3 months agoMITView on GitHub

  • Reads credentials

The file

Show its rules and text

We split this mcp-development.mdc into the rules it gives an agent

18 rules. About 0 are common, 17 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈17

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Write descriptions from AI assistant's perspective

    line 26
  2. Distinctive:

    Use Pydantic models for complex parameters

    line 31
  3. Distinctive:

    Check token validity before each API operation

    line 58
  4. Distinctive:

    Search within bounding box

    line 76
  5. Distinctive:

    Use the review-first GPX proposal workflow in the safe profile

    line 80
  6. Distinctive:

    Keep raw element tools restricted to expert mode on the development API

    line 82
  7. Very specific:

    Create .env privately with install -m 600 .env.example .env

    line 119
  8. Distinctive:

    Safety First: Always confirm destructive operations

    line 161
  9. Distinctive:

    Use Dev Environment: Test with dev.openstreetmap.org

    line 162
  10. Distinctive:

    Validate Input: Check coordinates, tags, and references

    line 163
  11. Distinctive:

    Secure Credentials: Use keyring, never commit secrets

    line 166
  12. Distinctive:

    Never test write operations on production OSM without explicit user consent

    line 172
  13. Distinctive:

    Don't store OAuth tokens in plaintext files

    line 173
  14. Distinctive:

    Avoid creating changesets without proper metadata

    line 174
  15. Distinctive:

    Don't upload incomplete or invalid geometric data

    line 175
  16. Distinctive:

    Never ignore OSM API error responses

    line 176
  17. Distinctive:

    Don't bypass coordinate validation

    line 177
  18. Distinctive:

    Avoid hardcoding API endpoints in tool implementations

    line 178

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
mcp-development.mdc
---
description:
globs:
alwaysApply: true
---
# MCP Development Patterns and Best Practices

## Model Context Protocol (MCP) Implementation

### Server Architecture
The MCP server in [src/osm_edit_mcp/server.py](mdc:src/osm_edit_mcp/server.py) follows FastMCP patterns:

```python
from mcp.server.fastmcp import FastMCP
app = FastMCP("osm-edit-mcp")

@app.tool()
async def tool_name(param: str) -> str:
    """Tool description for AI assistant."""
    # Implementation
```

### Tool Design Principles

#### 1. Clear Tool Descriptions
- Write descriptions from AI assistant's perspective
- Include parameter explanations and expected outputs
- Mention any prerequisites (authentication, changesets, etc.)

#### 2. Type Safety
- Use Pydantic models for complex parameters
- Implement proper type hints for all parameters
- Validate input data before processing

#### 3. Error Handling Pattern
```python
try:
    # OSM API operation
    result = await osm_client.operation()
    return {"success": True, "data": result}
except OSMAPIError as e:
    return {"success": False, "error": str(e)}
```

## Authentication Flow

### OAuth 2.0 Implementation
Based on [.env.example](mdc:.env.example) configuration:

1. **Initial Setup**: User configures OAuth credentials
2. **Token Request**: Server requests authorization URL
3. **User Authorization**: User approves application
4. **Token Exchange**: Server exchanges code for access token
5. **Token Storage**: Securely store in keyring
6. **Token Rotation**: Reauthorize an expired token without overwriting a valid token before validation

### Authentication State Management
- Check token validity before each API operation
- Implement graceful degradation for unauthenticated requests
- Provide clear error messages for authentication failures

## OSM API Integration

### Base URL Configuration
```python
# Development (safe for testing)
OSM_API_BASE_URL = "https://api06.dev.openstreetmap.org"

# Production (requires extreme caution)
OSM_API_BASE_URL = "https://api.openstreetmap.org"
```

### Request Patterns
1. **Read Operations**: Safe, no confirmation needed
   - Get node/way/relation by ID
   - Search within bounding box
   - Get changeset information

2. **Write Operations**: ⚠️ REQUIRE EXACT PROPOSAL CONFIRMATION
   - Use the review-first GPX proposal workflow in the safe profile
   - Bind production confirmation to the exact proposal digest
   - Keep raw element tools restricted to expert mode on the development API

### Rate Limiting
- Maximum 10,000 API calls per hour per IP
- Implement exponential backoff for rate limit errors
- Cache read responses when appropriate

## Configuration Management

### Environment Variables ([.env.example](mdc:.env.example))
```bash
OSM_USE_DEV_API=true
OSM_DEV_CLIENT_ID=your_oauth_client_id
OSM_DEV_CLIENT_SECRET=your_oauth_client_secret
OSM_DEV_REDIRECT_URI=https://localhost:8080/callback
OSM_DEV_API_BASE=https://api06.dev.openstreetmap.org/api/0.6
OSM_WRITE_PROFILE=safe
LOG_LEVEL=INFO
```

### Dependencies ([pyproject.toml](mdc:pyproject.toml))
Key packages:
- `mcp>=1.10,<2` - MCP server framework
- `httpx` - Async HTTP client
- `authlib` - OAuth 2.0 implementation
- `keyring` - Secure credential storage
- `pydantic` - Data validation

## Development Workflow

### 1. Setup Development Environment
```bash
# Install the exact locked development environment
uv sync --locked --extra dev
```

### 2. Configuration
- Create `.env` privately with `install -m 600 .env.example .env`
- Set up OAuth application on OSM
- Configure development API endpoint

### 3. Testing Strategy
- Unit tests for data validation
- Integration tests with dev.openstreetmap.org
- Mock OSM API responses for offline testing
- Test authentication flows

### 4. MCP Client Testing
```bash
# Run MCP server from the locked environment
uv run --locked osm-edit-mcp

# Connect with MCP client
# Test tool discovery and execution
```

## Logging and Debugging

### Structured Logging
```python
import logging

logger = logging.getLogger(__name__)

@app.tool()
async def create_node(lat: float, lon: float, tags: dict):
    logger.info("Creating node", extra={
        "lat": lat, "lon": lon, "tags": tags
    })
    # Implementation
```

### Debug Information
- Log all OSM API requests (excluding auth tokens)
- Include changeset IDs in operation logs
- Track tool usage and performance metrics

## Best Practices Summary

1. **Safety First**: Always confirm destructive operations
2. **Use Dev Environment**: Test with dev.openstreetmap.org
3. **Validate Input**: Check coordinates, tags, and references
4. **Handle Errors**: Graceful degradation and clear error messages
5. **Document Tools**: Clear descriptions for AI assistant usage
6. **Secure Credentials**: Use keyring, never commit secrets
7. **Rate Limiting**: Respect OSM API limits
8. **Test Thoroughly**: Unit, integration, and end-to-end testing

## Common Pitfalls to Avoid

- Never test write operations on production OSM without explicit user consent
- Don't store OAuth tokens in plaintext files
- Avoid creating changesets without proper metadata
- Don't upload incomplete or invalid geometric data
- Never ignore OSM API error responses
- Don't bypass coordinate validation
- Avoid hardcoding API endpoints in tool implementations

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.