judith.ibanez commited on
Commit Β·
bec2d56
1
Parent(s): 3697654
test
Browse filesFiles changed (5)
- Dockerfile+15-4
- claude_desktop_config.jsonAdded+9
- requirements.txt+2-1
- simple_mcp_server.pyAdded+200
- start.shAdded+13
29 unmodified lines3031323334353637383940414243444529 unmodified linesRUN rm Audiveris-5.6.1-ubuntu24.04-x86_64.deb## Install Gradio MCPRUN apt-get install --fix-missing -y python3 python3-pip || apt-get install -y -f# TODO: use a python virtual environmentRUN pip install --break-system-packages gradio[mcp]## CleanRUN apt-get clean## Copy MCP server and execute itCOPY app.py /app/app.pyWORKDIR /appCMD ["python3", "app.py"]29 unmodified lines30313233343536373839404142434445464748495051525354555629 unmodified linesRUN rm Audiveris-5.6.1-ubuntu24.04-x86_64.deb## Install Python and dependenciesRUN apt-get install --fix-missing -y python3 python3-pip || apt-get install -y -f# TODO: use a python virtual environmentRUN pip install --break-system-packages gradio[mcp] mcp## CleanRUN apt-get clean## Copy application filesCOPY app.py /app/app.pyCOPY simple_mcp_server.py /app/simple_mcp_server.pyCOPY claude_desktop_config.json /app/claude_desktop_config.jsonCOPY requirements.txt /app/requirements.txtCOPY start.sh /app/start.shWORKDIR /app# Create output directory for processed filesRUN mkdir -p /tmp/output# Make start script executableRUN chmod +x start.sh# Default to Gradio interface, but allow MCP server with argumentCMD ["./start.sh"]
123456789{ "mcpServers": { "audiveris-music-recognition": { "command": "python3", "args": ["simple_mcp_server.py"], "cwd": "/app" } }} 123gradio>=4.0.0requeststyping-extensions1234gradio>=4.0.0requeststyping-extensionsmcp
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200#!/usr/bin/env python3"""Simple MCP Server for Music RecognitionBased on patterns from https://llmindset.co.uk/posts/2025/01/mcp-files-resources-part1/"""
import asyncioimport jsonimport osimport subprocessimport tempfilefrom typing import Any, Listfrom mcp.server import Serverfrom mcp.server.models import InitializationOptionsimport mcp.server.stdioimport mcp.types as types
# Initialize the MCP serverserver = Server("audiveris-music-recognition")
def process_music_score(file_path: str) -> dict: """Process a music score PDF using Audiveris""" audiveris = "/opt/audiveris/bin/Audiveris" output_dir = "/tmp/output" # Ensure output directory exists os.makedirs(output_dir, exist_ok=True) file_name = os.path.basename(file_path) musicxml_name = os.path.splitext(file_name)[0] + ".mxl" output_file = os.path.join(output_dir, musicxml_name)
cmd = [audiveris, "-batch", "-export", "-output", output_dir, file_path] try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) if result.returncode == 0 and os.path.exists(output_file): # Read the MusicXML content (limit size as per MCP spec) with open(output_file, 'r', encoding='utf-8') as f: content = f.read() # Limit to ~800KB to stay under 1MB limit if len(content.encode('utf-8')) > 800000: content = content[:800000] + "\n... [Content truncated due to size limit]" return { "success": True, "output_file": output_file, "musicxml_content": content, "message": f"Successfully converted {file_name} to MusicXML" } else: return { "success": False, "error": f"Audiveris failed: {result.stderr}", "message": f"Failed to convert {file_name}" } except subprocess.TimeoutExpired: return { "success": False, "error": "Processing timeout", "message": f"Conversion of {file_name} timed out" } except Exception as e: return { "success": False, "error": str(e), "message": f"Error processing {file_name}" }
@server.list_resources()async def handle_list_resources() -> List[types.Resource]: """List available resources - in this case, processed music files""" resources = [] output_dir = "/tmp/output" if os.path.exists(output_dir): for file in os.listdir(output_dir): if file.endswith('.mxl'): file_path = os.path.join(output_dir, file) resources.append(types.Resource( uri=f"file://{file_path}", name=f"MusicXML: {file}", description=f"Processed music score: {file}", mimeType="application/vnd.recordare.musicxml" )) return resources
@server.read_resource()async def handle_read_resource(uri: str) -> str: """Read a resource (MusicXML file)""" if not uri.startswith("file://"): raise ValueError(f"Unsupported URI scheme: {uri}") file_path = uri[7:] # Remove "file://" prefix if not os.path.exists(file_path): raise FileNotFoundError(f"File not found: {file_path}") with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Ensure we stay under 1MB limit if len(content.encode('utf-8')) > 1000000: content = content[:900000] + "\n... [Content truncated due to size limit]" return content
@server.list_tools()async def handle_list_tools() -> List[types.Tool]: """List available tools""" return [ types.Tool( name="convert_music_score", description="Convert a PDF music score to MusicXML format using Audiveris OCR", inputSchema={ "type": "object", "properties": { "file_path": { "type": "string", "description": "Path to the PDF file to convert" } }, "required": ["file_path"] } ), types.Tool( name="list_processed_scores", description="List all processed music scores available as resources", inputSchema={ "type": "object", "properties": {}, "additionalProperties": False } ) ]
@server.call_tool()async def handle_call_tool(name: str, arguments: dict[str, Any] | None) -> List[types.TextContent]: """Handle tool calls""" if name == "convert_music_score": if not arguments or "file_path" not in arguments: raise ValueError("Missing required argument: file_path") file_path = arguments["file_path"] if not os.path.exists(file_path): return [types.TextContent( type="text", text=f"Error: File not found: {file_path}" )] result = process_music_score(file_path) if result["success"]: # Return a summary, not the full content (that's available as a resource) response_text = f"""β
{result['message']}
π Output file: {result['output_file']}π MusicXML file is now available as a resource
The converted MusicXML content is available through the MCP resources. You can access it by listing resources and reading the specific MusicXML file.""" else: response_text = f"β {result['message']}\n\nError: {result['error']}" return [types.TextContent(type="text", text=response_text)] elif name == "list_processed_scores": resources = await handle_list_resources() if not resources: response_text = "No processed music scores found." else: response_text = "π Available processed music scores:\n\n" for resource in resources: response_text += f"β’ {resource.name}\n URI: {resource.uri}\n Description: {resource.description}\n\n" return [types.TextContent(type="text", text=response_text)] else: raise ValueError(f"Unknown tool: {name}")
async def main(): """Run the MCP server""" async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="audiveris-music-recognition", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=None, experimental_capabilities=None, ), ), )
if __name__ == "__main__": asyncio.run(main()) 12345678910111213#!/bin/bash
# Create output directorymkdir -p /tmp/output
# Check if we should run MCP server or Gradio interfaceif [ "$1" = "mcp" ]; then echo "Starting MCP Server..." python3 simple_mcp_server.pyelse echo "Starting Gradio Interface..." python3 app.pyfi Dockerfile+15-4
claude_desktop_config.jsonAdded+9
requirements.txt+2-1
simple_mcp_server.pyAdded+200
start.shAdded+13