add_track
Add a new track to a MIDI file and retrieve its information.
Instructions
Add a new track to midi file and return the new track info
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | Absoulate File Path to midi file |
Implementation Reference
- src/main.ts:316-332 (handler)Handler function that implements the add_track tool logic: loads a MIDI file, calls midi.addTrack() to add a new track, saves the file, and returns the new track info as JSON.
withErrorHandling(({ filePath }) => { // 读取文件 const midi = loadMidiFile(filePath) // 添加新轨道 const newTrack = midi.addTrack() // 保存文件 saveMidiFile(midi, filePath) return { content: [ { type: 'text', text: JSON.stringify(newTrack), }, ] } }) - src/main.ts:310-333 (registration)Registration of the 'add_track' tool via server.tool() with its name, description, and Zod schema for the filePath parameter.
server.tool( 'add_track', 'Add a new track to midi file and return the new track info', { filePath: z.string().describe('Absoulate File Path to midi file'), }, withErrorHandling(({ filePath }) => { // 读取文件 const midi = loadMidiFile(filePath) // 添加新轨道 const newTrack = midi.addTrack() // 保存文件 saveMidiFile(midi, filePath) return { content: [ { type: 'text', text: JSON.stringify(newTrack), }, ] } }) ) - src/main.ts:313-315 (schema)Input schema for the add_track tool: expects a single required string parameter 'filePath' describing the absolute path to the MIDI file.
{ filePath: z.string().describe('Absoulate File Path to midi file'), }, - src/utils/file-util.ts:5-9 (helper)Helper function loadMidiFile that reads a MIDI file from disk and creates a Midi instance from @tonejs/midi.
export function loadMidiFile(filePath: string) { const midiData = fs.readFileSync(filePath) const midi = new Midi(midiData) return midi } - src/utils/file-util.ts:11-15 (helper)Helper function saveMidiFile that converts the Midi instance back to an ArrayBuffer and writes it to disk.
export function saveMidiFile(midi: any, filePath: string): void { const arrayBuffer = midi.toArray() // 将ArrayBuffer转换为Buffer并写入文件 fs.writeFileSync(filePath, Buffer.from(arrayBuffer)) }