Here's a simple MCP server implementation in Python that restricts subprocess execution to uv run * commands and supports tool listing:
from typing import Any
import asyncio
import subprocess
from mcp.server.fastmcp import FastMCP
# Initialize MCP server
mcp = FastMCP("uv-runner")
@mcp.tool(
name="run_uv_command",
description="Execute uv run commands with validation",
parameters={
"command": {"type": "string", "description": "Command to execute (must start with 'uv run')"}
}
)
async def run_uv_command(command: str) -> dict[str, Any]:
"""Execute uv run commands with validation"""
# Validate command format
if not command.startswith("uv run "):
return {"error": "Invalid command - must start with 'uv run'"}
# Split command into parts
parts = command.split()
if len(parts) < 3: # Minimum: uv run [script]
return {"error": "Invalid command format"}
# Execute subprocess
try:
proc = await asyncio.create_subprocess_exec(
*parts,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
return {
"stdout": stdout.decode().strip(),
"stderr": stderr.decode().strip(),
"exit_code": proc.returncode
}
except Exception as e:
return {"error": f"Execution failed: {str(e)}"}
# Start server
if __name__ == "__main__":
mcp.run()
Key Features [[1]][[3]][[5]]:
-
Command Validation
- Only allows commands starting with
uv run
- Minimum command format:
uv run [script]
-
Tool Metadata
- Automatic tool registration via FastMCP
- Exposes tool name, description, and parameters
- Supports MCP's tool listing protocol
-
Subprocess Handling
- Uses asyncio subprocess for async execution
- Captures both stdout and stderr
- Returns structured output with exit code
Usage [[3]][[6]]:
-
Install dependencies:
uv add "mcp[cli]" asyncio
-
Run server:
uv run server.py
-
Connect to MCP client (e.g., Claude Desktop):
- Add server configuration to
claude_desktop_config.json
- Restart Claude Desktop
- Invoke tool via LLM prompt:
run_uv_command("uv run my_script")
Security Considerations [[5]]:
- Command validation prevents arbitrary execution
- No file system access beyond uv commands
- Error handling prevents information leakage
- Requires explicit user consent for tool execution
This implementation follows MCP's core principles of secure tool execution and context sharing while maintaining compatibility with existing MCP clients[[1]][[5]][[7]].