forked from TwelveTake-Studios/reaper-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreaper_web_server.lua
More file actions
1545 lines (1338 loc) · 50.3 KB
/
Copy pathreaper_web_server.lua
File metadata and controls
1545 lines (1338 loc) · 50.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- REAPER Web Server - ReaScript HTTP API (Lua version)
--
-- This script runs inside REAPER and exposes an HTTP API for controlling REAPER.
-- Works with REAPER's built-in Lua support - no additional configuration needed.
--
-- Usage:
-- 1. Load this script in REAPER (Actions -> Show action list -> Load ReaScript)
-- 2. Run the script
-- 3. Server starts on localhost:9000
--
-- Author: TwelveTake Studios LLC
-- License: MIT
-- Website: https://twelvetake.com
local HOST = "127.0.0.1"
local PORT = 9000
local MAX_BODY = 1024 * 1024 -- 1 MiB request-body cap (memory-DoS guard)
-- Bearer token shared with the MCP server. Prefer REAPER_BRIDGE_TOKEN from the
-- environment (set the same value for both sides); otherwise generate one and
-- print it so it can be copied into the MCP server's environment. The listener
-- is loopback-only, so this is a defense-in-depth shared secret against other
-- local processes / the browser cross-origin vector.
local function generate_token()
math.randomseed(os.time() + math.floor((reaper.time_precise() or 0) * 1000000) % 2147483647)
local chars = "0123456789abcdef"
local t = {}
for i = 1, 48 do
local n = math.random(1, #chars)
t[i] = chars:sub(n, n)
end
return table.concat(t)
end
local AUTH_TOKEN = os.getenv("REAPER_BRIDGE_TOKEN")
local AUTH_TOKEN_GENERATED = false
if not AUTH_TOKEN or AUTH_TOKEN == "" then
AUTH_TOKEN = generate_token()
AUTH_TOKEN_GENERATED = true
end
-- True for requests that may proceed without a token: CORS preflight and the
-- read-only health check. Everything else must present the bearer token.
local function request_is_authorized(request)
local h = request.headers or {}
local provided = h["authorization"]
if provided then
provided = provided:gsub("^[Bb]earer%s+", "")
end
if not provided or provided == "" then
provided = h["x-bridge-token"]
end
return provided == AUTH_TOKEN
end
local socket = nil
local client = nil
local server_running = false
-- Try to load LuaSocket.
--
-- Stock LuaSocket builds cannot run inside REAPER. Two routes were tested on
-- macOS (REAPER arm64, embedded Lua 5.4) and both fail:
--
-- 1. A stock build (lunarmodules.github.io, luarocks) links socket/core.so
-- expecting the host process to export Lua's C symbols. The standalone
-- `lua` binary does; REAPER links Lua statically and exports nothing, so
-- the module never opens -- "symbol not found in flat namespace
-- '_luaL_addlstring'" -- even with the right Lua version and architecture
-- and the module on REAPER's cpath.
--
-- 2. Statically linking liblua into core.so resolves those symbols, but puts
-- a second Lua runtime in the process. Strings created by REAPER's Lua are
-- then misread by the embedded copy: short strings survive (a 30-byte send
-- returns 30) while long strings read as zero-length (a 300-byte send
-- returns 0, silently dropping the data). Every real HTTP response exceeds
-- Lua's 40-byte short-string limit, so responses vanish with no error.
--
-- The fix is a LuaSocket build that shares REAPER's own Lua runtime: see
-- luasocket-shim/ in this repo. REAPER's Lua symbols are present in the binary
-- with real addresses, just not exported, so the shim resolves them from the
-- host's Mach-O symbol table at module load and routes LuaSocket's C API calls
-- through them. One runtime, so the long-string corruption cannot occur.
--
-- Build and install it with luasocket-shim/build.sh, which places the modules
-- in <REAPER resource path>/Scripts/luasocket. Without that directory this
-- script falls back to REAPER's default search paths, finds nothing, and tells
-- you to use the file bridge.
local luasocket_dir = reaper.GetResourcePath() .. "/Scripts/luasocket"
package.path = luasocket_dir .. "/?.lua;" .. package.path
package.cpath = luasocket_dir .. "/?.so;" .. package.cpath
local status, socket_lib = pcall(require, "socket")
-- A shim that cannot resolve REAPER's symbols returns no module rather than
-- crashing the host, and a stale or half-copied install can load yet be
-- missing pieces. Either way the failure surfaces much later, as an opaque
-- "attempt to index" error, so check for the API actually used here.
if status and (type(socket_lib) ~= "table" or type(socket_lib.tcp) ~= "function") then
status = false
socket_lib = "loaded, but socket.tcp is missing (got " .. type(socket_lib) ..
") -- stale or partial install, or the shim could not resolve " ..
"REAPER's Lua symbols"
end
if not status then
reaper.ShowConsoleMsg("ERROR: LuaSocket not available to REAPER.\n")
reaper.ShowConsoleMsg("Reason: " .. tostring(socket_lib) .. "\n")
reaper.ShowConsoleMsg("\nExpected the shimmed build in:\n")
reaper.ShowConsoleMsg(" " .. luasocket_dir .. "\n")
reaper.ShowConsoleMsg("Build it with luasocket-shim/build.sh from the reaper-mcp repo.\n")
reaper.ShowConsoleMsg("\nOr use the file-based bridge instead (reaper_mcp_bridge.lua).\n")
reaper.ShowConsoleMsg("It needs no native module and is the default transport\n")
reaper.ShowConsoleMsg("used by the MCP server (REAPER_COMM_MODE=file).\n")
reaper.ShowConsoleMsg("\nNote: a stock LuaSocket will not work here. It either fails\n")
reaper.ShowConsoleMsg("to open (REAPER does not export Lua's C symbols) or, if built\n")
reaper.ShowConsoleMsg("with liblua linked in, opens but silently drops any response\n")
reaper.ShowConsoleMsg("longer than 40 bytes. See the comment above this message.\n")
return
end
socket = socket_lib
-- ============================================================================
-- Utility Functions
-- ============================================================================
local function db_to_linear(db)
if db <= -150 then return 0 end
return 10 ^ (db / 20)
end
local function linear_to_db(linear)
if linear <= 0 then return -150 end
-- math.log10 was removed in Lua 5.2; REAPER embeds 5.4, where math.log with
-- an explicit base 10 uses log10 internally, so precision is unchanged.
return 20 * math.log(linear, 10)
end
local function round(num, decimals)
local mult = 10 ^ (decimals or 0)
return math.floor(num * mult + 0.5) / mult
end
local function json_encode(obj)
-- Simple JSON encoder for our use case
if obj == nil then
return "null"
elseif type(obj) == "boolean" then
return obj and "true" or "false"
elseif type(obj) == "number" then
if obj ~= obj then return "null" end -- NaN
if obj == math.huge or obj == -math.huge then return "null" end
return tostring(obj)
elseif type(obj) == "string" then
-- Escape special characters
local escaped = obj:gsub('\\', '\\\\')
:gsub('"', '\\"')
:gsub('\n', '\\n')
:gsub('\r', '\\r')
:gsub('\t', '\\t')
return '"' .. escaped .. '"'
elseif type(obj) == "table" then
-- Check if array or object
local is_array = true
local max_index = 0
for k, v in pairs(obj) do
if type(k) ~= "number" or k < 1 or math.floor(k) ~= k then
is_array = false
break
end
if k > max_index then max_index = k end
end
if is_array and max_index > 0 then
-- Array
local parts = {}
for i = 1, max_index do
parts[i] = json_encode(obj[i])
end
return "[" .. table.concat(parts, ",") .. "]"
else
-- Object
local parts = {}
for k, v in pairs(obj) do
table.insert(parts, json_encode(tostring(k)) .. ":" .. json_encode(v))
end
return "{" .. table.concat(parts, ",") .. "}"
end
end
return "null"
end
-- Guards against adversarial input (deeply nested / oversized) on the hand-rolled
-- recursive decoder, which runs in-process inside REAPER.
local JSON_MAX_DEPTH = 64
local JSON_MAX_LEN = 1024 * 1024 -- 1 MiB per decoded value
local function json_decode(str, depth)
if not str or str == "" then return nil end
depth = depth or 0
if depth > JSON_MAX_DEPTH then return nil end
if #str > JSON_MAX_LEN then return nil end
str = str:gsub("^%s*(.-)%s*$", "%1")
if str == "null" then return nil
elseif str == "true" then return true
elseif str == "false" then return false
elseif str:match("^%-?%d+%.?%d*$") then return tonumber(str)
elseif str:match('^"(.*)"$') then
local s = str:match('^"(.*)"$')
s = s:gsub('\\n', '\n'):gsub('\\r', '\r'):gsub('\\"', '"'):gsub('\\\\', '\\')
return s
elseif str:match("^%[.*%]$") then
local arr = {}
local content = str:sub(2, -2)
if content:match("^%s*$") then return arr end
local i = 1
local pos = 1
local depth = 0
local in_string = false
local escape = false
local start = 1
while pos <= #content do
local char = content:sub(pos, pos)
if escape then
escape = false
elseif char == '\\' then
escape = true
elseif char == '"' then
in_string = not in_string
elseif not in_string then
if char == '[' or char == '{' then
depth = depth + 1
elseif char == ']' or char == '}' then
depth = depth - 1
elseif char == ',' and depth == 0 then
local value = content:sub(start, pos - 1)
arr[i] = json_decode(value:match("^%s*(.-)%s*$"), depth + 1)
i = i + 1
start = pos + 1
end
end
pos = pos + 1
end
if start <= #content then
local value = content:sub(start)
arr[i] = json_decode(value:match("^%s*(.-)%s*$"), depth + 1)
end
return arr
elseif str:match("^{.*}$") then
local obj = {}
local content = str:sub(2, -2)
local pos = 1
while pos <= #content do
local key_start = content:find('"', pos)
if not key_start then break end
local key_end = content:find('"', key_start + 1)
if not key_end then break end
local key = content:sub(key_start + 1, key_end - 1)
local colon = content:find(':', key_end + 1)
if not colon then break end
local value_start = colon + 1
while value_start <= #content and content:sub(value_start, value_start):match("%s") do
value_start = value_start + 1
end
local value_end = value_start
local depth = 0
local in_string = false
local escape = false
while value_end <= #content do
local char = content:sub(value_end, value_end)
if escape then
escape = false
elseif char == '\\' then
escape = true
elseif char == '"' then
in_string = not in_string
elseif not in_string then
if char == '[' or char == '{' then
depth = depth + 1
elseif char == ']' or char == '}' then
depth = depth - 1
elseif (char == ',' or char == '}') and depth == 0 then
break
end
end
value_end = value_end + 1
end
local value = content:sub(value_start, value_end - 1)
obj[key] = json_decode(value:match("^%s*(.-)%s*$"), depth + 1)
pos = value_end + 1
end
return obj
end
return nil
end
local function parse_request(request_text)
-- Split headers from body at the blank line, before tokenizing anything.
-- Iterating "[^\r\n]+" over the whole request skips empty lines, so the
-- blank line that ends the headers disappears and the body is never found:
-- every POST arrives with an empty body and its JSON is silently ignored.
local header_text, body = request_text:match("^(.-)\r?\n\r?\n(.*)$")
if not header_text then
header_text = request_text
body = ""
end
local lines = {}
for line in header_text:gmatch("[^\r\n]+") do
table.insert(lines, line)
end
if #lines == 0 then return nil end
-- Parse request line
local method, path = lines[1]:match("^(%w+)%s+([^%s]+)")
if not method then return nil end
-- Parse headers
local headers = {}
for i = 2, #lines do
local key, value = lines[i]:match("^([^:]+):%s*(.+)$")
if key then
headers[key:lower()] = value
end
end
return {
method = method,
path = path,
headers = headers,
body = body
}
end
-- Set by send_response, cleared before each request, so the error path can tell
-- whether a reply already went out.
local response_sent = false
local function send_response(client_socket, status_code, status_text, body)
response_sent = true
local response = string.format(
"HTTP/1.1 %d %s\r\n" ..
"Content-Type: application/json\r\n" ..
"Access-Control-Allow-Origin: http://localhost\r\n" ..
"Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\n" ..
"Access-Control-Allow-Headers: Content-Type, Authorization\r\n" ..
"Content-Length: %d\r\n" ..
"Connection: close\r\n" ..
"\r\n%s",
status_code, status_text, #body, body
)
client_socket:send(response)
end
local function send_json(client_socket, data, status_code)
status_code = status_code or 200
local status_text = status_code == 200 and "OK" or
status_code == 201 and "Created" or
status_code == 400 and "Bad Request" or
status_code == 401 and "Unauthorized" or
status_code == 404 and "Not Found" or
status_code == 413 and "Payload Too Large" or
status_code == 500 and "Internal Server Error" or "Error"
send_response(client_socket, status_code, status_text, json_encode(data))
end
local function send_error(client_socket, message, status_code, extra)
status_code = status_code or 400
local data = {error = message}
if extra then
for k, v in pairs(extra) do
data[k] = v
end
end
send_json(client_socket, data, status_code)
end
-- ============================================================================
-- Track Functions
-- ============================================================================
local function get_track(track_index)
if track_index == -1 then
return reaper.GetMasterTrack(0)
end
local track_count = reaper.CountTracks(0)
if track_index >= 0 and track_index < track_count then
return reaper.GetTrack(0, track_index)
end
return nil
end
local function get_track_info(track)
if not track then return nil end
local _, name = reaper.GetTrackName(track)
local volume = reaper.GetMediaTrackInfo_Value(track, "D_VOL")
local pan = reaper.GetMediaTrackInfo_Value(track, "D_PAN")
local mute = reaper.GetMediaTrackInfo_Value(track, "B_MUTE")
local solo = reaper.GetMediaTrackInfo_Value(track, "I_SOLO")
local track_num = reaper.GetMediaTrackInfo_Value(track, "IP_TRACKNUMBER")
-- IP_TRACKNUMBER is 1-based for regular tracks, -1 for the master track and
-- 0 when the track is not found. Only the 0 case was special-cased, so the
-- master fell through the 1-based conversion and reported index -2 -- while
-- every other part of this API, including the 404 hint, calls master -1.
local track_index
if track_num <= 0 then
track_index = -1
else
track_index = math.floor(track_num) - 1 -- Convert to 0-based
end
return {
index = track_index,
name = name,
volume_db = round(linear_to_db(volume), 2),
pan = round(pan, 2),
mute = mute == 1,
solo = solo > 0
}
end
local function get_fx_info(track, fx_index)
if not track then return nil end
local fx_count = reaper.TrackFX_GetCount(track)
if fx_index < 0 or fx_index >= fx_count then return nil end
local _, fx_name = reaper.TrackFX_GetFXName(track, fx_index, "")
local enabled = reaper.TrackFX_GetEnabled(track, fx_index)
return {
index = fx_index,
name = fx_name,
enabled = enabled
}
end
local function get_fx_params(track, fx_index)
if not track then return nil end
local fx_count = reaper.TrackFX_GetCount(track)
if fx_index < 0 or fx_index >= fx_count then return nil end
local param_count = reaper.TrackFX_GetNumParams(track, fx_index)
local params = {}
for i = 0, param_count - 1 do
local _, param_name = reaper.TrackFX_GetParamName(track, fx_index, i, "")
local value, minval, maxval = reaper.TrackFX_GetParam(track, fx_index, i)
table.insert(params, {
index = i,
name = param_name,
value = round(value, 4),
min = round(minval, 4),
max = round(maxval, 4)
})
end
return params
end
-- ============================================================================
-- Request Handlers
-- ============================================================================
local function handle_get(path, client_socket)
-- Health check
if path == "/ping" then
send_json(client_socket, {status = "ok", reaper = "connected"})
return
end
-- Track count
if path == "/tracks/count" then
send_json(client_socket, {count = reaper.CountTracks(0)})
return
end
-- Master track
if path == "/master" then
local track = get_track(-1)
local info = get_track_info(track)
if info then
send_json(client_socket, info)
else
send_error(client_socket, "Master track not found", 404)
end
return
end
-- Track info: /tracks/{index}
local track_index = path:match("^/tracks/(%-?%d+)$")
if track_index then
track_index = tonumber(track_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404, {
track_count = reaper.CountTracks(0),
hint = "Use -1 for master track, 0 to track_count-1 for regular tracks"
})
return
end
send_json(client_socket, get_track_info(track))
return
end
-- FX list: /tracks/{index}/fx
local track_index = path:match("^/tracks/(%-?%d+)/fx$")
if track_index then
track_index = tonumber(track_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404)
return
end
local fx_count = reaper.TrackFX_GetCount(track)
local fx_list = {}
for i = 0, fx_count - 1 do
table.insert(fx_list, get_fx_info(track, i))
end
send_json(client_socket, {track_index = track_index, fx = fx_list})
return
end
-- FX count: /tracks/{index}/fx/count
local track_index = path:match("^/tracks/(%-?%d+)/fx/count$")
if track_index then
track_index = tonumber(track_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404)
return
end
send_json(client_socket, {track_index = track_index, count = reaper.TrackFX_GetCount(track)})
return
end
-- FX info: /tracks/{index}/fx/{fx_index}
local track_index, fx_index = path:match("^/tracks/(%-?%d+)/fx/(%d+)$")
if track_index and fx_index then
track_index = tonumber(track_index)
fx_index = tonumber(fx_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404)
return
end
local fx_info = get_fx_info(track, fx_index)
if not fx_info then
send_error(client_socket, "FX " .. fx_index .. " not found", 404, {
fx_count = reaper.TrackFX_GetCount(track)
})
return
end
send_json(client_socket, fx_info)
return
end
-- FX params: /tracks/{index}/fx/{fx_index}/params
local track_index, fx_index = path:match("^/tracks/(%-?%d+)/fx/(%d+)/params$")
if track_index and fx_index then
track_index = tonumber(track_index)
fx_index = tonumber(fx_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404)
return
end
local params = get_fx_params(track, fx_index)
if not params then
send_error(client_socket, "FX " .. fx_index .. " not found", 404)
return
end
send_json(client_socket, {track_index = track_index, fx_index = fx_index, params = params})
return
end
-- Single FX param: /tracks/{index}/fx/{fx_index}/params/{param_index}
local track_index, fx_index, param_index = path:match("^/tracks/(%-?%d+)/fx/(%d+)/params/(%d+)$")
if track_index and fx_index and param_index then
track_index = tonumber(track_index)
fx_index = tonumber(fx_index)
param_index = tonumber(param_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404)
return
end
local _, param_name = reaper.TrackFX_GetParamName(track, fx_index, param_index, "")
local value, minval, maxval = reaper.TrackFX_GetParam(track, fx_index, param_index)
send_json(client_socket, {
track_index = track_index,
fx_index = fx_index,
param_index = param_index,
name = param_name,
value = round(value, 4),
min = round(minval, 4),
max = round(maxval, 4)
})
return
end
-- Transport
if path == "/transport" then
local play_state = reaper.GetPlayState()
local cursor_pos = reaper.GetCursorPosition()
send_json(client_socket, {
playing = (play_state & 1) == 1,
paused = (play_state & 2) == 2,
recording = (play_state & 4) == 4,
cursor_position = round(cursor_pos, 3)
})
return
end
-- Project
if path == "/project" then
-- Arity matters here: GetProjectName returns just the name, and
-- GetProjectTimeSignature2 returns exactly (bpm, bpi). Consuming a leading
-- retval that does not exist left project_name nil and bpi nil, and the
-- math.floor(bpi) below then threw on every request to this endpoint.
local project_path = reaper.GetProjectPath("")
local project_name = reaper.GetProjectName(0, "")
local tempo = reaper.Master_GetTempo()
local _, bpi = reaper.GetProjectTimeSignature2(0)
send_json(client_socket, {
path = project_path,
name = project_name,
tempo = round(tempo, 2),
time_signature = {
beats_per_measure = math.floor(bpi),
note_value = 4
}
})
return
end
-- Sends: /tracks/{index}/sends
local track_index = path:match("^/tracks/(%-?%d+)/sends$")
if track_index then
track_index = tonumber(track_index)
local track = get_track(track_index)
if not track then
send_error(client_socket, "Track " .. track_index .. " not found", 404)
return
end
local num_sends = reaper.GetTrackNumSends(track, 0)
local sends = {}
for i = 0, num_sends - 1 do
local vol = reaper.GetTrackSendInfo_Value(track, 0, i, "D_VOL")
local mute = reaper.GetTrackSendInfo_Value(track, 0, i, "B_MUTE")
table.insert(sends, {
index = i,
volume_db = round(linear_to_db(vol), 2),
mute = mute == 1
})
end
send_json(client_socket, {track_index = track_index, sends = sends})
return
end
send_error(client_socket, "Unknown endpoint: " .. path, 404)
end
-- ============================================================================
-- Function Call Handler (for MCP server)
-- ============================================================================
local function handle_function_call(func_name, args)
-- Get track helper with proper indexing
local function get_track_by_index(idx)
if idx == -1 then
return reaper.GetMasterTrack(0)
end
local count = reaper.CountTracks(0)
if idx >= 0 and idx < count then
return reaper.GetTrack(0, idx)
end
return nil
end
-- Track Operations
if func_name == "CountTracks" then
return {ok = true, ret = reaper.CountTracks(0)}
elseif func_name == "GetTrackInfo" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
return {ok = true, ret = get_track_info(track)}
elseif func_name == "GetTrackFXList" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local fx_count = reaper.TrackFX_GetCount(track)
local fx_list = {}
for i = 0, fx_count - 1 do
local _, fx_name = reaper.TrackFX_GetFXName(track, i, "")
local enabled = reaper.TrackFX_GetEnabled(track, i)
table.insert(fx_list, {index = i, name = fx_name, enabled = enabled})
end
return {ok = true, track_index = args[1], fx = fx_list}
elseif func_name == "GetAllTracksInfo" then
local count = reaper.CountTracks(0)
local tracks = {}
for i = 0, count - 1 do
local track = reaper.GetTrack(0, i)
table.insert(tracks, get_track_info(track))
end
return {ok = true, tracks = tracks}
elseif func_name == "InsertTrackAtIndex" then
reaper.InsertTrackAtIndex(args[1], args[2])
return {ok = true}
elseif func_name == "DeleteTrack" then
local track = get_track_by_index(args[2])
if track then
reaper.DeleteTrack(track)
return {ok = true}
end
return {ok = false, error = "Track not found"}
elseif func_name == "GetSetMediaTrackInfo_String" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local retval, str = reaper.GetSetMediaTrackInfo_String(track, args[2], args[3], args[4])
return {ok = true, ret = retval, value = str}
elseif func_name == "SetMediaTrackInfo_Value" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local ret = reaper.SetMediaTrackInfo_Value(track, args[2], args[3])
return {ok = true, ret = ret}
-- FX Operations
elseif func_name == "TrackFX_GetCount" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
return {ok = true, ret = reaper.TrackFX_GetCount(track)}
elseif func_name == "TrackFX_AddByName" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local fx_idx = reaper.TrackFX_AddByName(track, args[2], args[3], args[4])
return {ok = true, ret = fx_idx}
elseif func_name == "TrackFX_Delete" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
reaper.TrackFX_Delete(track, args[2])
return {ok = true}
elseif func_name == "TrackFX_GetFXName" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local retval, name = reaper.TrackFX_GetFXName(track, args[2], "")
return {ok = true, ret = retval, name = name}
elseif func_name == "TrackFX_GetEnabled" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
return {ok = true, ret = reaper.TrackFX_GetEnabled(track, args[2])}
elseif func_name == "TrackFX_SetEnabled" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
reaper.TrackFX_SetEnabled(track, args[2], args[3])
return {ok = true}
elseif func_name == "TrackFX_GetNumParams" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
return {ok = true, ret = reaper.TrackFX_GetNumParams(track, args[2])}
elseif func_name == "TrackFX_GetParamName" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local retval, name = reaper.TrackFX_GetParamName(track, args[2], args[3], "")
return {ok = true, ret = retval, name = name}
elseif func_name == "TrackFX_GetParam" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local val, minval, maxval = reaper.TrackFX_GetParam(track, args[2], args[3])
return {ok = true, value = round(val, 4), min = round(minval, 4), max = round(maxval, 4)}
elseif func_name == "TrackFX_SetParam" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local ret = reaper.TrackFX_SetParam(track, args[2], args[3], args[4])
return {ok = true, ret = ret}
-- Routing Operations
elseif func_name == "CreateTrackSend" then
local src = get_track_by_index(args[1])
local dest = get_track_by_index(args[2])
if not src then return {ok = false, error = "Source track not found"} end
if not dest then return {ok = false, error = "Destination track not found"} end
local idx = reaper.CreateTrackSend(src, dest)
return {ok = true, ret = idx}
elseif func_name == "RemoveTrackSend" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
reaper.RemoveTrackSend(track, args[2], args[3])
return {ok = true}
elseif func_name == "GetTrackNumSends" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
return {ok = true, ret = reaper.GetTrackNumSends(track, args[2])}
elseif func_name == "SetTrackSendInfo_Value" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local ret = reaper.SetTrackSendInfo_Value(track, args[2], args[3], args[4], args[5])
return {ok = true, ret = ret}
elseif func_name == "SetTrackSendUIVol" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
local ret = reaper.SetTrackSendUIVol(track, args[2], args[3], args[4])
return {ok = true, ret = ret}
-- Transport Operations
elseif func_name == "OnPlayButton" then
reaper.OnPlayButton()
return {ok = true}
elseif func_name == "OnStopButton" then
reaper.OnStopButton()
return {ok = true}
elseif func_name == "OnPauseButton" then
reaper.OnPauseButton()
return {ok = true}
elseif func_name == "OnRecordButton" then
reaper.OnRecordButton()
return {ok = true}
elseif func_name == "GetPlayState" then
local state = reaper.GetPlayState()
return {ok = true, ret = state, playing = (state & 1) == 1, paused = (state & 2) == 2, recording = (state & 4) == 4}
elseif func_name == "GetCursorPosition" then
return {ok = true, ret = reaper.GetCursorPosition()}
elseif func_name == "SetEditCurPos" then
reaper.SetEditCurPos(args[1], args[2], args[3])
return {ok = true}
elseif func_name == "GetPlayPosition" then
return {ok = true, ret = reaper.GetPlayPosition()}
elseif func_name == "GetSetRepeat" then
return {ok = true, ret = reaper.GetSetRepeat(args[1])}
-- Project Operations
elseif func_name == "Main_SaveProject" then
reaper.Main_SaveProject(args[1], args[2])
return {ok = true}
elseif func_name == "GetProjectPath" then
local retval, path = reaper.GetProjectPath("")
return {ok = true, ret = path}
elseif func_name == "GetProjectName" then
local retval, name = reaper.GetProjectName(0, "")
return {ok = true, ret = name}
elseif func_name == "Master_GetTempo" then
return {ok = true, ret = reaper.Master_GetTempo()}
elseif func_name == "SetCurrentBPM" then
reaper.SetCurrentBPM(args[1], args[2], args[3])
return {ok = true}
elseif func_name == "GetTimeSignature" then
local bpm, bpi = reaper.GetProjectTimeSignature2(0)
return {ok = true, bpm = bpm, bpi = bpi}
elseif func_name == "GetProjectLength" then
return {ok = true, ret = reaper.GetProjectLength(0)}
-- Markers and Regions
elseif func_name == "AddProjectMarker2" then
local idx = reaper.AddProjectMarker2(args[1], args[2], args[3], args[4], args[5], args[6], args[7])
return {ok = true, ret = idx}
elseif func_name == "DeleteProjectMarker" then
reaper.DeleteProjectMarker(args[1], args[2], args[3])
return {ok = true}
elseif func_name == "GetProjectMarkers" then
local markers = {}
local num_markers, num_regions = reaper.CountProjectMarkers(0)
for i = 0, num_markers + num_regions - 1 do
local retval, isrgn, pos, rgnend, name, markrgnindexnumber = reaper.EnumProjectMarkers(i)
if not isrgn then
table.insert(markers, {index = markrgnindexnumber, position = pos, name = name})
end
end
return {ok = true, markers = markers}
elseif func_name == "GetProjectRegions" then
local regions = {}
local num_markers, num_regions = reaper.CountProjectMarkers(0)
for i = 0, num_markers + num_regions - 1 do
local retval, isrgn, pos, rgnend, name, markrgnindexnumber = reaper.EnumProjectMarkers(i)
if isrgn then
table.insert(regions, {index = markrgnindexnumber, start = pos, ["end"] = rgnend, name = name})
end
end
return {ok = true, regions = regions}
elseif func_name == "GoToMarker" then
reaper.GoToMarker(args[1], args[2], args[3])
return {ok = true}
elseif func_name == "GoToRegion" then
reaper.GoToRegion(args[1], args[2], args[3])
return {ok = true}
-- Selection Operations
elseif func_name == "Main_OnCommand" then
reaper.Main_OnCommand(args[1], args[2])
return {ok = true}
elseif func_name == "SetTrackSelected" then
local track = get_track_by_index(args[1])
if not track then
return {ok = false, error = "Track not found"}
end
reaper.SetTrackSelected(track, args[2])