INITIAL_MCP_PROMPT.mdโข19.5 kB
# Linux MCP Server Builder Prompt
## INITIAL CLARIFICATIONS
Before generating the MCP server, please provide:
1. **Service/Tool Name**: What service or functionality will this MCP server provide?
2. **API Documentation**: If this integrates with an API, please provide the documentation URL
3. **Required Features**: List the specific features/tools you want implemented
4. **Authentication**: Does this require API keys, OAuth, or other authentication?
5. **Data Sources**: Will this access files, databases, APIs, or other data sources?
Build an MCP server that provides AI models with secure control over remote Linux servers and browser automation capabilities. The server must run as a background service (TypeScript or Python API) and connect to remote Linux servers via SSH without requiring any software installation on target systems.
Implement the following 16 required MVP tools:
**Command Execution Tools:**
1. `execute_command` - Run single terminal commands securely via SSH
2. `execute_script` - Execute bash scripts with command-line arguments
3. `create_bash_script` - Create and deploy new bash scripts to remote servers
**File System Tools:**
4. `list_directory` - List directory contents with detailed information
**System Monitoring Tools:**
5. `get_system_info` - Get comprehensive system information (CPU, memory, disk usage)
**Browser Automation Tools:**
6. `puppeteer_navigate` - Navigate browser to specified URLs
7. `puppeteer_screenshot` - Capture screenshots of web pages
8. `puppeteer_click` - Click on web page elements
9. `puppeteer_hover` - Hover over web page elements
10. `puppeteer_fill` - Fill form input fields
11. `puppeteer_select` - Select options from dropdown menus
12. `puppeteer_evaluate` - Execute JavaScript in browser context
13. `puppeteer_get_console_logs` - Access browser console output
14. `puppeteer_get_screenshot` - Retrieve current browser screenshot
15. `puppeteer_get_network_details` - Monitor network requests and responses
**MCP Resources:**
16. Browser console logs, screenshots, and network data as MCP resources
The server should handle SSH authentication (keys/passwords), command execution with timeouts, secure parameter validation, and browser automation using Puppeteer. Create it for system administration and web automation in development/testing environments.
If any information is missing or unclear, I will ask for clarification before proceeding.
---
# INSTRUCTIONS FOR THE LLM
## YOUR ROLE
You are an expert MCP (Model Context Protocol) server developer. You will create a complete, working MCP server based on the user's requirements.
## CLARIFICATION PROCESS
Before generating the server, ensure you have:
1. **Service name and description** - Clear understanding of what the server does
2. **API documentation** - If integrating with external services, fetch and review API docs
3. **Tool requirements** - Specific list of tools/functions needed
4. **Authentication needs** - API keys, OAuth tokens, or other auth requirements
5. **Output preferences** - Any specific formatting or response requirements
If any critical information is missing, ASK THE USER for clarification before proceeding.
## YOUR OUTPUT STRUCTURE
You must organize your response in TWO distinct sections:
### SECTION 1: FILES TO CREATE
Generate EXACTLY these 5 files with complete content that the user can copy and save.
**DO NOT** create duplicate files or variations. Each file should appear ONCE with its complete content.
### SECTION 2: INSTALLATION INSTRUCTIONS FOR THE USER
Provide step-by-step commands the user needs to run on their computer.
Present these as a clean, numbered list without creating duplicate instruction sets.
## CRITICAL RULES FOR CODE GENERATION
1. **NO `@mcp.prompt()` decorators** - They break Claude Desktop
2. **NO `prompt` parameter to FastMCP()** - It breaks Claude Desktop
3. **NO type hints from typing module** - No `Optional`, `Union`, `List[str]`, etc.
4. **NO complex parameter types** - Use `param: str = ""` not `param: str = None`
5. **SINGLE-LINE DOCSTRINGS ONLY** - Multi-line docstrings cause gateway panic errors
6. **DEFAULT TO EMPTY STRINGS** - Use `param: str = ""` never `param: str = None`
7. **ALWAYS return strings from tools** - All tools must return formatted strings
8. **ALWAYS run as background service** - The server must run as a background TypeScript or Python service (NOT Docker)
9. **ALWAYS log to stderr** - Use the logging configuration provided
10. **ALWAYS handle errors gracefully** - Return user-friendly error messages
---
# SECTION 1: FILES TO CREATE
## File 1: requirements.txt
```
mcp[cli]>=1.2.0
paramiko>=3.4.0
pyppeteer>=1.0.2
psutil>=5.9.0
```
## File 2: requirements.txt
```
mcp[cli]>=1.2.0
httpx
# Add any other required libraries based on the user's needs
```
## File 3: README.md
```python
#!/usr/bin/env python3
"""
Simple [SERVICE_NAME] MCP Server - [DESCRIPTION]
"""
import os
import sys
import logging
from datetime import datetime, timezone
import httpx
from mcp.server.fastmcp import FastMCP
# Configure logging to stderr
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
stream=sys.stderr
)
logger = logging.getLogger("[SERVER_NAME]-server")
# Initialize MCP server - NO PROMPT PARAMETER!
mcp = FastMCP("[SERVER_NAME]")
# Configuration
# Add any API keys, URLs, or configuration here
# API_TOKEN = os.environ.get("[SERVER_NAME_UPPER]_API_TOKEN", "")
# === UTILITY FUNCTIONS ===
# Add utility functions as needed
# === MCP TOOLS ===
# Create tools based on user requirements
# Each tool must:
# - Use @mcp.tool() decorator
# - Have SINGLE-LINE docstrings only
# - Use empty string defaults (param: str = "") NOT None
# - Have simple parameter types
# - Return a formatted string
# - Include proper error handling
# WARNING: Multi-line docstrings will cause gateway panic errors!
@mcp.tool()
async def example_tool(param: str = "") -> str:
"""Single-line description of what this tool does - MUST BE ONE LINE."""
logger.info(f"Executing example_tool with {param}")
try:
# Implementation here
result = "example"
return f"โ
Success: {result}"
except Exception as e:
logger.error(f"Error: {e}")
return f"โ Error: {str(e)}"
# === SERVER STARTUP ===
if __name__ == "__main__":
logger.info("Starting [SERVICE_NAME] MCP server...")
# Add any startup checks
# if not API_TOKEN:
# logger.warning("[SERVER_NAME_UPPER]_API_TOKEN not set")
try:
mcp.run(transport='stdio')
except Exception as e:
logger.error(f"Server error: {e}", exc_info=True)
sys.exit(1)
```
## File 4: readme.txt
Create a comprehensive readme with all sections filled in based on the implementation.
## File 5: CLAUDE.md
Create a CLAUDE.md file with implementation details and guidelines.
---
# SECTION 2: INSTALLATION INSTRUCTIONS FOR THE USER
After creating the files above, provide these instructions for the user to run:
## Step 1: Save the Files
```bash
# Create project directory
mkdir [SERVER_NAME]-mcp-server
cd [SERVER_NAME]-mcp-server
# Save all 5 files in this directory
```
## Step 2: Build Docker Image
```bash
docker build -t [SERVER_NAME]-mcp-server .
```
## Step 3: Set Up Secrets (if needed)
```bash
# Only include if the server needs API keys or secrets
docker mcp secret set [SECRET_NAME]="your-secret-value"
# Verify secrets
docker mcp secret list
```
## Step 4: Create Custom Catalog
```bash
# Create catalogs directory if it doesn't exist
mkdir -p ~/.docker/mcp/catalogs
# Create or edit custom.yaml
nano ~/.docker/mcp/catalogs/custom.yaml
```
Add this entry to custom.yaml:
```yaml
version: 2
name: custom
displayName: Custom MCP Servers
registry:
[SERVER_NAME]:
description: "[DESCRIPTION]"
title: "[SERVICE_NAME]"
type: server
dateAdded: "[CURRENT_DATE]" # Format: 2025-01-01T00:00:00Z
image: [SERVER_NAME]-mcp-server:latest
ref: ""
readme: ""
toolsUrl: ""
source: ""
upstream: ""
icon: ""
tools:
- name: [tool_name_1]
- name: [tool_name_2]
# List all tools
secrets:
- name: [SECRET_NAME]
env: [ENV_VAR_NAME]
example: [EXAMPLE_VALUE]
# Only include if using secrets
metadata:
category: [Choose: productivity|monitoring|automation|integration]
tags:
- [relevant_tag_1]
- [relevant_tag_2]
license: MIT
owner: local
```
## Step 5: Update Registry
```bash
# Edit registry file
nano ~/.docker/mcp/registry.yaml
```
Add this entry under the existing `registry:` key:
```yaml
registry:
# ... existing servers ...
[SERVER_NAME]:
ref: ""
```
**IMPORTANT**: The entry must be under the `registry:` key, not at the root level.
## Step 6: Configure Claude Desktop
Find your Claude Desktop config file:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
Edit the file and add your custom catalog to the args array:
```json
{
"mcpServers": {
"mcp-toolkit-gateway": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v", "/var/run/docker.sock:/var/run/docker.sock",
"-v", "[YOUR_HOME]/.docker/mcp:/mcp",
"docker/mcp-gateway",
"--catalog=/mcp/catalogs/docker-mcp.yaml",
"--catalog=/mcp/catalogs/custom.yaml",
"--config=/mcp/config.yaml",
"--registry=/mcp/registry.yaml",
"--tools-config=/mcp/tools.yaml",
"--transport=stdio"
]
}
}
}
```
**NOTE**: JSON does not support comments. The custom.yaml catalog line should be added without any comment.
Replace `[YOUR_HOME]` with:
- **macOS**: `/Users/your_username`
- **Windows**: `C:\\Users\\your_username` (use double backslashes)
- **Linux**: `/home/your_username`
## Step 7: Restart Claude Desktop
1. Quit Claude Desktop completely
2. Start Claude Desktop again
3. Your new tools should appear!
## Step 8: Test Your Server
```bash
# Verify it appears in the list
docker mcp server list
# If you don't see your server, check logs:
docker logs [container_name]
```
---
# IMPLEMENTATION PATTERNS FOR THE LLM
## CORRECT Tool Implementation:
```python
@mcp.tool()
async def fetch_data(endpoint: str = "", limit: str = "10") -> str:
"""Fetch data from API endpoint with optional limit."""
# Check for empty strings, not just truthiness
if not endpoint.strip():
return "โ Error: Endpoint is required"
try:
# Convert string parameters as needed
limit_int = int(limit) if limit.strip() else 10
# Implementation
return f"โ
Fetched {limit_int} items"
except ValueError:
return f"โ Error: Invalid limit value: {limit}"
except Exception as e:
return f"โ Error: {str(e)}"
```
## For API Integration:
```python
async with httpx.AsyncClient() as client:
try:
response = await client.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
# Process and format data
return f"โ
Result: {formatted_data}"
except httpx.HTTPStatusError as e:
return f"โ API Error: {e.response.status_code}"
except Exception as e:
return f"โ Error: {str(e)}"
```
## For System Commands:
```python
import subprocess
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=10,
shell=True # Only if needed
)
if result.returncode == 0:
return f"โ
Output:\n{result.stdout}"
else:
return f"โ Error:\n{result.stderr}"
except subprocess.TimeoutExpired:
return "โฑ๏ธ Command timed out"
```
## For File Operations:
```python
try:
with open(filename, 'r') as f:
content = f.read()
return f"โ
File content:\n{content}"
except FileNotFoundError:
return f"โ File not found: {filename}"
except Exception as e:
return f"โ Error reading file: {str(e)}"
```
## OUTPUT FORMATTING GUIDELINES
Use emojis for visual clarity:
- โ
Success operations
- โ Errors or failures
- โฑ๏ธ Time-related information
- ๐ Data or statistics
- ๐ Search or lookup operations
- โก Actions or commands
- ๐ Security-related information
- ๐ File operations
- ๐ Network operations
- โ ๏ธ Warnings
Format multi-line output clearly:
```python
return f"""๐ Results:
- Field 1: {value1}
- Field 2: {value2}
- Field 3: {value3}
Summary: {summary}"""
```
## COMPLETE README.TXT TEMPLATE
```markdown
# [SERVICE_NAME] MCP Server
A Model Context Protocol (MCP) server that [DESCRIPTION].
## Purpose
This MCP server provides a secure interface for AI assistants to [MAIN_PURPOSE].
## Features
### Current Implementation
- **`[tool_name_1]`** - [What it does]
- **`[tool_name_2]`** - [What it does]
[LIST ALL TOOLS]
## Prerequisites
- Docker Desktop with MCP Toolkit enabled
- Docker MCP CLI plugin (`docker mcp` command)
[ADD ANY SERVICE-SPECIFIC REQUIREMENTS]
## Installation
See the step-by-step instructions provided with the files.
## Usage Examples
In Claude Desktop, you can ask:
- "[Natural language example 1]"
- "[Natural language example 2]"
[PROVIDE EXAMPLES FOR EACH TOOL]
## Architecture
```
Claude Desktop โ MCP Gateway โ [SERVICE_NAME] MCP Server โ [SERVICE/API]
โ
Docker Desktop Secrets
([SECRET_NAMES])
```
## Development
### Local Testing
```bash
# Set environment variables for testing
export [SECRET_NAME]="test-value"
# Run directly
python [SERVER_NAME]_server.py
# Test MCP protocol
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | python [SERVER_NAME]_server.py
```
### Adding New Tools
1. Add the function to `[SERVER_NAME]_server.py`
2. Decorate with `@mcp.tool()`
3. Update the catalog entry with the new tool name
4. Rebuild the Docker image
## Troubleshooting
### Tools Not Appearing
- Verify Docker image built successfully
- Check catalog and registry files
- Ensure Claude Desktop config includes custom catalog
- Restart Claude Desktop
### Authentication Errors
- Verify secrets with `docker mcp secret list`
- Ensure secret names match in code and catalog
## Security Considerations
- All secrets stored in Docker Desktop secrets
- Never hardcode credentials
- Running as non-root user
- Sensitive data never logged
## License
MIT License
```
## FINAL GENERATION CHECKLIST FOR THE LLM
Before presenting your response, verify:
- [ ] Created all 5 files with proper naming
- [ ] No @mcp.prompt() decorators used
- [ ] No prompt parameter in FastMCP()
- [ ] No complex type hints
- [ ] ALL tool docstrings are SINGLE-LINE only
- [ ] ALL parameters default to empty strings ("") not None
- [ ] All tools return strings
- [ ] Check for empty strings with .strip() not just truthiness
- [ ] Error handling in every tool
- [ ] Clear separation between files and user instructions
- [ ] All placeholders replaced with actual values
- [ ] Usage examples provided
- [ ] Security handled via Docker secrets
- [ ] Catalog includes version: 2, name, displayName, and registry wrapper
- [ ] Registry entries are under registry: key with ref: ""
- [ ] Date format is ISO 8601 (YYYY-MM-DDTHH:MM:SSZ)
- [ ] Claude config JSON has no comments
- [ ] Each file appears exactly once
- [ ] Instructions are clear and numbered