-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebugMCPServer.ts
More file actions
1189 lines (1090 loc) · 65.1 KB
/
Copy pathdebugMCPServer.ts
File metadata and controls
1189 lines (1090 loc) · 65.1 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
// Copyright (c) Microsoft Corporation.
// Copyright 2026 Arm Limited and contributors
import { z } from 'zod';
import * as path from 'path';
import * as fs from 'fs';
import * as http from 'http';
import express from 'express';
import {
DebuggingExecutor,
ConfigurationManager,
DebuggingHandler,
IDebuggingHandler
} from '.';
import { HardwareTimeouts, SERVER_VERSION } from './debuggingExecutor';
import { logger } from './utils/logger';
import { serialHandler } from './serialHandler';
import { SerialOpName } from './core/opTable';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
import { randomUUID } from 'node:crypto';
/** The server must never be reachable off-box — it flashes and erases hardware without auth. */
const LOOPBACK_BIND_ADDRESS = '127.0.0.1';
const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
/**
* True when an HTTP Host header (hostname with optional port) refers to the
* loopback interface. A missing Host header is rejected — every legitimate
* HTTP/1.1 client sends one.
*/
export function isLoopbackHostHeader(host: unknown): boolean {
if (typeof host !== 'string' || host.length === 0) {
return false;
}
// Strip the port: "[::1]:3001" → "[::1]", "localhost:3001" → "localhost".
const hostname = host.startsWith('[')
? host.replace(/^(\[[^\]]*\]).*$/, '$1')
: host.replace(/:\d+$/, '');
return LOOPBACK_HOSTNAMES.has(hostname.toLowerCase());
}
/**
* True when an Origin header value is a loopback origin (or a non-web value
* like "null" is absent — browsers send Origin on cross-site POSTs, so a
* present non-loopback Origin means a foreign web page is calling us).
*/
export function isLoopbackOrigin(origin: string): boolean {
try {
return LOOPBACK_HOSTNAMES.has(new URL(origin).hostname.toLowerCase());
} catch {
return false;
}
}
/**
* The configured port is already served, so another window is the router.
* Routine, not a failure — every window after the first hits this.
*/
export class PortInUseError extends Error {
constructor(public readonly port: number) {
super(`Port ${port} is already in use by another CMSIS Developer Assistant window`);
this.name = 'PortInUseError';
}
}
/**
* How a session reaches the serial backends. Indirected through an op name
* rather than calling the singleton, because in the multi-window setup the
* board's USB-serial port is owned by the window that has the board — not by
* whichever window happens to be running the router.
*/
export type SerialDispatch = (op: SerialOpName, args?: unknown) => Promise<string>;
/** The pair of handlers one MCP session talks to. */
export interface SessionHandlers {
debug: IDebuggingHandler;
serial: SerialDispatch;
}
/**
* True when this session's handler forwards to other windows.
*
* A structural check rather than `instanceof RoutingDebuggingHandler`: importing
* the router here would make debugMCPServer depend on the routing layer even in
* the single-window build, and these two methods are exactly the contract the
* routing tools need.
*/
function isRoutingHandler(
handler: IDebuggingHandler,
): handler is IDebuggingHandler & {
listDebugWindows(): string;
selectDebugWindow(args: { pid?: number; workspaceFolder?: string }): string;
} {
const h = handler as unknown as Record<string, unknown>;
return typeof h.listDebugWindows === 'function' && typeof h.selectDebugWindow === 'function';
}
/** Single-window dispatch: straight to the local serial handler singleton. */
export const localSerialDispatch: SerialDispatch = (op, args) => {
const target = serialHandler as unknown as Record<string, unknown>;
const method = target[op];
if (typeof method !== 'function') {
return Promise.reject(new Error(`Serial op ${op} is not implemented`));
}
return Promise.resolve((method as (a?: unknown) => Promise<string>).call(serialHandler, args));
};
/**
* Main MCP server class that exposes debugging functionality as tools and resources.
* Uses the official @modelcontextprotocol/sdk with SSE transport over express.
*/
export class DebugMCPServer {
private httpServer: http.Server | null = null;
private port: number;
private actualPort: number | null = null;
private initialized: boolean = false;
/**
* Per-MCP-session handler factory. A fresh handler per session is what lets
* each agent session keep its own routing target (which VS Code window owns
* the board) once the routing handler is wired in.
*/
private handlerFactory: () => SessionHandlers;
/**
* Live Streamable-HTTP transports keyed by MCP session id. A transport is
* created on `initialize` and reused for that session's POSTs, its GET SSE
* stream, and its DELETE teardown.
*/
private transports: Record<string, StreamableHTTPServerTransport> = {};
constructor(
port: number,
timeoutInSeconds: number,
hardwareTimeouts?: Partial<HardwareTimeouts>,
handlerFactory?: () => SessionHandlers,
) {
if (handlerFactory) {
this.handlerFactory = handlerFactory;
} else {
// Single-window default: debug in this very window, and drive the
// serial backends directly rather than over a control server.
const executor = new DebuggingExecutor(hardwareTimeouts);
const configManager = new ConfigurationManager();
const handler = new DebuggingHandler(executor, configManager, timeoutInSeconds);
this.handlerFactory = () => ({ debug: handler, serial: localSerialDispatch });
}
this.port = port;
}
/**
* Initialize the MCP server. No shared McpServer is constructed — one is
* built per session, in the POST /mcp handler.
*/
async initialize() {
this.initialized = true;
}
/**
* Build a fresh McpServer for one MCP session and register every tool +
* resource on it.
*
* Per *session*, not per request and not shared. The original shared
* instance was closed and reconnected on every request, so a concurrent
* call stripped the other's transport and its response went nowhere —
* that is what made `get_threads` hang after the third call. A
* session-scoped server never closes mid-flight, so that bug stays fixed
* while GET /mcp still has a real stream to attach to.
*/
private createMcpServer(): McpServer {
const mcpServer = new McpServer({
name: 'cmsis-developer-assistant',
version: SERVER_VERSION,
});
const handlers = this.handlerFactory();
this.setupTools(mcpServer, handlers.debug, handlers.serial);
this.setupResources(mcpServer);
return mcpServer;
}
/**
* Register every tool on `mcpServer`, routed through `debuggingHandler`.
*
* The handler is a parameter rather than an instance field because each
* MCP session gets its own — in the multi-window setup that handler
* carries the session's routing target.
*/
private setupTools(
mcpServer: McpServer,
debuggingHandler: IDebuggingHandler,
serial: SerialDispatch,
) {
const TIMEOUT_DESC = 'Optional per-call timeout in milliseconds (capped to 60 000). Overrides the default for this single tool call. Use it when you can estimate the work and want a tighter or looser bound.';
// Get debug instructions tool (for clients that don't support MCP resources like GitHub Copilot)
mcpServer.registerTool('get_debug_instructions', {
description: 'Get the debugging guide with step-by-step instructions for effective debugging. ' +
'Returns comprehensive guidance including breakpoint strategies, root cause analysis framework, ' +
'and best practices. Call this before starting a debug session.',
}, async () => {
const content = await this.loadMarkdownFile('agent-resources/debug_instructions.md');
return { content: [{ type: 'text' as const, text: content }] };
});
// Start debugging tool
mcpServer.registerTool('start_debugging', {
description: 'Start a debug session via the standard VS Code debug pipeline (uses launch.json + the debug tab).' +
'\n\n⚠️ FOR CMSIS / CORTEX-M PROJECTS: prefer `cmsis_action` with `action="load_and_debug"` ' +
'(same as clicking *Debug* in the CMSIS Solution panel — builds if needed, flashes, then attaches). ' +
'`start_debugging` skips the flash step and is the wrong tool for embedded targets that need ' +
'fresh firmware on the chip.' +
'\n\nUSE start_debugging FOR:' +
'\n• Non-CMSIS projects (Python, Java, JavaScript/TypeScript, C#, Go, Rust, …)' +
'\n• Attaching to an already-flashed CMSIS target where you specifically do NOT want to ' +
'reprogram (use `cmsis_action attach` instead if you want the CMSIS panel\'s attach behavior)' +
'\n\nUSE THIS WHEN debugging a code-side bug (wrong values, null/undefined, unexpected behavior, ' +
'failing tests).' +
'\n\n⚠️ CRITICAL: Before using this tool, first call get_debug_instructions or read ' +
'cmsis-developer-assistant://docs/debug_instructions resource!',
inputSchema: {
fileFullPath: z.string().optional().describe('Full path to the source code file to debug. Optional when configurationName is provided (e.g. for embedded/CMSIS gdbtarget configs).'),
workingDirectory: z.string().describe('Working directory for the debug session'),
testName: z.string().optional().describe(
'Name of a specific test name to debug. ' +
'Only provide this when debugging a single test method. ' +
'Leave empty to debug the entire file or test class.'
),
configurationName: z.string().optional().describe(
'Name of a specific debug configuration from launch.json to use. ' +
'For embedded/CMSIS debugging, provide the configuration name (e.g. "CMSIS Debugger: pyOCD"). ' +
'Leave empty to be prompted to select a configuration interactively.'
),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { fileFullPath?: string; workingDirectory: string; testName?: string; configurationName?: string; timeoutMs?: number }) => {
const result = await debuggingHandler.handleStartDebugging(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Stop debugging tool
mcpServer.registerTool('stop_debugging', {
description: 'Stop the current debug session',
}, async () => {
const result = await debuggingHandler.handleStopDebugging();
return { content: [{ type: 'text' as const, text: result }] };
});
// Step over tool
mcpServer.registerTool('step_over', {
description: 'Execute the current line of code without diving into it.',
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleStepOver(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Step into tool
mcpServer.registerTool('step_into', {
description: 'Dive into the current line of code.',
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleStepInto(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Step out tool
mcpServer.registerTool('step_out', {
description: 'Step out of the current function',
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleStepOut(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Pause tool — halts a running target without ending the session.
mcpServer.registerTool('pause_execution', {
description: 'Pause a running target so inspection tools (variables, memory, registers, ' +
'call stack) become valid. No-op if the target is already stopped. Returns the new ' +
'debug state on success, or a structured error if the probe is unresponsive.',
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handlePause(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Continue execution tool
mcpServer.registerTool('continue_execution', {
description: 'Resume program execution until the next breakpoint is hit or the program completes.',
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleContinue(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Wait-for-stop tool — blocks until the target next stops, without
// issuing any execution command itself.
mcpServer.registerTool('wait_for_stop', {
description: 'Block until the target next stops (breakpoint, fault, step-complete, pause) and return the stop ' +
'reason plus the current debug state, or a structured timeout. Use after continue_execution returned while ' +
'the target was still running, after issuing execution through evaluate_expression ("-exec continue"), or to ' +
'catch the first breakpoint of a free-running session — this replaces blind sleeping. Returns immediately ' +
'with the recorded reason if the target is already stopped. Issues no execution commands itself.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleWaitForStop(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Restart debugging tool
mcpServer.registerTool('restart_debugging', {
description: 'Restart the debug session from the beginning with the same configuration.',
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleRestart(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Reset tool — resets the target inside the live session, verified.
mcpServer.registerTool('reset', {
description: 'Reset the target via GDB monitor commands (pyOCD / J-Link) and VERIFY the reset actually took ' +
'effect — the PC is compared against the reset vector read from the vector table, and the result says ' +
'honestly when the target did NOT appear to reset (silent non-resets are common on attach configurations). ' +
'Unlike restart_debugging, the debug session and its breakpoints survive. A running target is halted ' +
'first. method: auto (system → core → hardware escalation, default), system (SYSRESETREQ), core ' +
'(VECTRESET), hardware (nSRST — requires the reset line wired from probe to target). halt=true (default) ' +
'leaves the target stopped at the reset vector; halt=false resumes after verification.',
annotations: { readOnlyHint: false, destructiveHint: true },
inputSchema: {
method: z.enum(['auto', 'system', 'core', 'hardware']).optional()
.describe("Reset method. 'auto' (default) escalates system → core → hardware until one verifies."),
halt: z.boolean().optional()
.describe('Leave the target halted at the reset vector (default true). false resumes after verification.'),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { method?: 'auto' | 'system' | 'core' | 'hardware'; halt?: boolean; timeoutMs?: number }) => {
const result = await debuggingHandler.handleReset(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Add breakpoint tool
mcpServer.registerTool('add_breakpoint', {
description: 'Set a breakpoint to pause execution at a critical line of code. Essential for debugging: pause before potential errors, examine state at decision points, or verify code paths. ' +
'On Cortex-M the number of simultaneously bound breakpoints is limited by the FPB unit (commonly 6 on Cortex-M4/M7, 4 on Cortex-M0+) — clear ones you no longer need.',
inputSchema: {
fileFullPath: z.string().describe('Full path to the file'),
line: z.number().int().min(1).optional().describe('Line number (1-based) where the breakpoint should be set. Preferred.'),
condition: z.string().optional().describe(
'Optional condition expression in target-language syntax, e.g. "i == 100" or "p != 0". ' +
'Applied as GDB\'s native `if` clause, so the CPU is only halted when it holds — important in hot loops.',
),
lineContent: z.string().optional().describe(
'DEPRECATED: substring of the line to break on. Sets a breakpoint on EVERY line containing this text, ' +
'which in C routinely matches dozens of lines. Pass `line` instead. Only used when `line` is omitted.',
),
},
}, async (args: { fileFullPath: string; line?: number; condition?: string; lineContent?: string }) => {
const result = await debuggingHandler.handleAddBreakpoint(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Add logpoint tool
mcpServer.registerTool('add_logpoint', {
description: 'Add a logpoint: a breakpoint that prints a message and resumes instead of pausing. Useful for tracing values across many iterations. ' +
'Embed expressions in curly braces to interpolate runtime values, e.g. "adc={sample} state={fsm}". ' +
'GDB needs an explicit printf conversion per value: {expr} defaults to %d, use {expr:%s} / {expr:%f} / {expr:%p} to override; {{ and }} are literal braces. ' +
'NOTE for Cortex-M: this is NOT free — the core halts on each hit while GDB formats and prints, then resumes. ' +
'In an ISR or a hot loop it distorts timing badly; prefer read_cycle_counter or a firmware RAM buffer read back with read_memory.',
inputSchema: {
fileFullPath: z.string().describe('Full path to the file'),
line: z.number().int().min(1).describe('Line number (1-based) where the logpoint should be set'),
logMessage: z.string().describe('Message to log. Wrap expressions in {curly braces} to interpolate runtime values.'),
condition: z.string().optional().describe('Optional condition expression; the message is only logged when it evaluates true.'),
},
}, async (args: { fileFullPath: string; line: number; logMessage: string; condition?: string }) => {
const result = await debuggingHandler.handleAddLogpoint(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Remove breakpoint tool
mcpServer.registerTool('remove_breakpoint', {
description: 'Remove a breakpoint that is no longer needed.',
inputSchema: {
fileFullPath: z.string().describe('Full path to the file'),
line: z.number().describe('Line number (1-based)'),
},
}, async (args: { fileFullPath: string; line: number }) => {
const result = await debuggingHandler.handleRemoveBreakpoint(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Clear all breakpoints tool
mcpServer.registerTool('clear_all_breakpoints', {
description: 'Clear all breakpoints at once. Use this after verifying the root cause to clean up before moving on to the next task.',
}, async () => {
const result = await debuggingHandler.handleClearAllBreakpoints();
return { content: [{ type: 'text' as const, text: result }] };
});
// List breakpoints tool
mcpServer.registerTool('list_breakpoints', {
description: 'View all currently set breakpoints across all files.',
}, async () => {
const result = await debuggingHandler.handleListBreakpoints();
return { content: [{ type: 'text' as const, text: result }] };
});
// List variable names tool (discovery without reading any values)
mcpServer.registerTool('list_variable_names', {
description: 'List the names and types of variables visible at the current execution point, without reading their values. ' +
'Use this to discover what exists, then pull only what you need with get_variables_values — on a slow probe that is the difference between one round trip and thirty.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
scope: z.enum(['local', 'global', 'all']).optional().describe("Variable scope: 'local', 'global', or 'all'"),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { scope?: 'local' | 'global' | 'all'; timeoutMs?: number }) => {
const result = await debuggingHandler.handleListVariableNames(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Get variables tool
mcpServer.registerTool('get_variables_values', {
description: 'Inspect variable values at the current execution point. This is your window into program state - see what data looks like at runtime, verify assumptions, identify unexpected values, and understand why code behaves as it does. ' +
'Omit variableNames to dump the whole scope (usually fine on embedded targets, where frames are small); pass variableNames to read only what you need.',
inputSchema: {
scope: z.enum(['local', 'global', 'all']).optional().describe("Variable scope: 'local', 'global', or 'all'"),
variableNames: z.array(z.string()).min(1).max(50).optional().describe(
'Optional filter: read only these variables, e.g. ["adc_raw", "state"]. ' +
'Names that match nothing are reported back. Omit to return everything in scope.',
),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { scope?: 'local' | 'global' | 'all'; variableNames?: string[]; timeoutMs?: number }) => {
const result = await debuggingHandler.handleGetVariables(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Evaluate expression tool
mcpServer.registerTool('evaluate_expression', {
description: 'Powerful runtime expression evaluator: Test hypotheses, check computed values, call methods, or inspect object properties in the live debug context. Goes beyond simple variable inspection - evaluate any valid expression in the target language.',
inputSchema: {
expression: z.string().describe('Expression to evaluate in the current programming language context'),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { expression: string; timeoutMs?: number }) => {
const result = await debuggingHandler.handleEvaluateExpression(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// ========== Embedded / Cortex-M Tools ==========
// Read memory tool
mcpServer.registerTool('read_memory', {
description: 'Read a range of bytes from the target\'s memory. ' +
'Use this for inspecting SRAM, Flash, peripheral registers, or the stack. ' +
'Returns hex dump and/or ASCII representation.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
address: z.string().describe("Memory address as hex string, e.g. '0x20000000'"),
length: z.number().int().min(1).max(4096).describe('Number of bytes to read (1-4096)'),
format: z.enum(['hex', 'ascii', 'both']).default('both').describe('Output format'),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { address: string; length: number; format?: 'hex' | 'ascii' | 'both'; timeoutMs?: number }) => {
const result = await debuggingHandler.handleReadMemory(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Read core registers tool
mcpServer.registerTool('read_core_registers', {
description: 'Read Cortex-M core registers: R0-R12, SP, LR, PC, xPSR, MSP, PSP, CONTROL, FAULTMASK, BASEPRI, PRIMASK. ' +
'Essential for analyzing crash state, stack pointers, and processor mode.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleReadCoreRegisters(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// DWT cycle counter tool — cycle-accurate timing on the target.
mcpServer.registerTool('read_cycle_counter', {
description: 'Read the DWT cycle counter (CYCCNT) for cycle-accurate timing between two points on the ' +
'target: read here, continue_execution / wait_for_stop to the end point, read again, subtract (mod 2^32). ' +
'The 32-bit counter wraps (~10.7 s @ 400 MHz) and stops while the core is halted and during WFE sleep — ' +
'it counts ACTIVE cycles only. Enables DWT trace (DEMCR.TRCENA) and CYCCNT on first use — a one-time, ' +
'benign debug-unit state change. Reports when the core has no cycle counter.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleReadCycleCounter(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Read peripheral register tool
mcpServer.registerTool('read_peripheral_register', {
description: 'Read named peripheral registers using SVD data from the Peripheral Inspector extension. ' +
'Provide a peripheral name (e.g. "GPIOA", "UART0", "SPI1") and optionally a register name. ' +
'If the Peripheral Inspector is not available, provides guidance on using read_memory instead.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
peripheral: z.string().describe("Peripheral name, e.g. 'GPIOA', 'UART0', 'RCC'"),
register: z.string().optional().describe("Register name, e.g. 'ODR', 'CR1'. If omitted, lists all registers in the peripheral."),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { peripheral: string; register?: string; timeoutMs?: number }) => {
const result = await debuggingHandler.handleReadPeripheralRegister(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Get fault info tool
mcpServer.registerTool('get_fault_info', {
description: 'Read and decode Cortex-M fault status registers (CFSR, HFSR, BFAR, MMFAR, DFSR, AFSR). ' +
'Call this when the target hits a HardFault, BusFault, MemManage, or UsageFault. ' +
'Returns a human-readable analysis of which fault bits are set and what they mean.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleGetFaultInfo(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Get device info tool
mcpServer.registerTool('get_device_info', {
description: 'Return information about the connected debug target: session name, debug type, program path, ' +
'GDB path, GDB server, port, and CMSIS config details.',
annotations: { readOnlyHint: true, destructiveHint: false },
}, async () => {
const result = await debuggingHandler.handleGetDeviceInfo();
return { content: [{ type: 'text' as const, text: result }] };
});
// Check target connection tool
mcpServer.registerTool('check_target_connection', {
description: 'Probe the hardware debug connection with a short-timeout DAP ping. ' +
'Use this when other tool calls start timing out or returning "unavailable" ' +
'to determine whether the probe/GDB server is alive and whether the target ' +
'is stopped (so DAP reads are valid). Never hangs — uses an internal short timeout.',
annotations: { readOnlyHint: true, destructiveHint: false },
}, async () => {
const result = await debuggingHandler.handleCheckTargetConnection();
return { content: [{ type: 'text' as const, text: result }] };
});
// Get call stack tool
mcpServer.registerTool('get_call_stack', {
description: 'Return the full call stack (function names, source, line, frameId) for the active thread, ' +
'or a specific thread when threadId is provided. Use the returned frameId values with ' +
'get_frame_variables to inspect variables of caller frames without changing the active frame.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
threadId: z.number().int().optional().describe('Optional DAP thread id (from get_threads). Defaults to the active thread.'),
levels: z.number().int().min(1).max(200).optional().describe('Maximum frames to return (default 50).'),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { threadId?: number; levels?: number; timeoutMs?: number }) => {
const result = await debuggingHandler.handleGetCallStack(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Get threads / RTOS tasks tool
mcpServer.registerTool('get_threads', {
description: 'List DAP threads reported by the debug adapter. With an RTOS-aware GDB server ' +
'(pyOCD --rtos, J-Link RTOS plugin) each FreeRTOS / RTX / ThreadX task appears as a thread, ' +
'matching the xRTOS viewer task list. Returns the thread id, name and top frame; pair with ' +
'get_call_stack(threadId=...) to inspect any task\'s call stack.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: { timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC) },
}, async (args: { timeoutMs?: number }) => {
const result = await debuggingHandler.handleGetThreads(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Get frame variables tool
mcpServer.registerTool('get_frame_variables', {
description: 'Inspect variables of a specific stack frame by its frameId (obtained from get_call_stack). ' +
'Lets you walk up the call stack and examine caller-frame state without changing the ' +
'editor\'s active frame.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
frameId: z.number().int().describe('DAP frame id, as returned by get_call_stack.'),
scope: z.enum(['local', 'global', 'all']).optional().describe("Variable scope: 'local', 'global', or 'all'"),
variableNames: z.array(z.string()).min(1).max(50).optional().describe(
'Optional filter: read only these variables. Omit to return everything in the frame.',
),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC),
},
}, async (args: { frameId: number; scope?: 'local' | 'global' | 'all'; variableNames?: string[]; timeoutMs?: number }) => {
const result = await debuggingHandler.handleGetFrameVariables(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// ========== Serial — dual backend ==========
//
// Two backends, one tool surface:
// • OWNED: serialController opens a port via `serialport` (we own it).
// • BRIDGE: serialMonitorBridge taps the MS Serial Monitor extension
// API at runtime — uses whatever the public API exposes today
// (port enum), and auto-lights up data subscription if MS adds it.
//
// OS reality: only one process can read a tty in non-exclusive mode.
// If the user has an MS Serial Monitor session open on the same path,
// the OWNED backend will fail to open. Use serial_subscribe_monitor
// in that case (zero conflict — taps via API, not the kernel).
mcpServer.registerTool('serial_list_ports', {
description: 'List available serial ports. Tries the MS Serial Monitor API first (friendly names), ' +
'falls back to the bundled serialport library.',
annotations: { readOnlyHint: true, destructiveHint: false },
}, async () => {
const result = await serial('handleListPorts');
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_open', {
description: 'Open an OWNED serial port. The MCP server holds the connection and buffers RX. ' +
'Use only when no MS Serial Monitor UI session is active on the same path — the OS allows ' +
'one reader per tty. Defaults: 115200 baud, 8N1, no flow control.',
inputSchema: {
path: z.string().describe("Device path, e.g. '/dev/tty.usbmodemABCD' on macOS or 'COM3' on Windows"),
baudRate: z.number().int().optional().describe('Baud rate (default 115200)'),
dataBits: z.union([z.literal(5), z.literal(6), z.literal(7), z.literal(8)]).optional(),
parity: z.enum(['none', 'even', 'odd', 'mark', 'space']).optional(),
stopBits: z.union([z.literal(1), z.literal(1.5), z.literal(2)]).optional(),
rtscts: z.boolean().optional().describe('RTS/CTS hardware flow control (default false)'),
},
}, async (args: { path: string; baudRate?: number; dataBits?: 5 | 6 | 7 | 8; parity?: 'none' | 'even' | 'odd' | 'mark' | 'space'; stopBits?: 1 | 1.5 | 2; rtscts?: boolean }) => {
const result = await serial('handleOpen', args);
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_close', {
description: 'Close the OWNED serial port (does not affect the MS Serial Monitor UI).',
}, async () => {
const result = await serial('handleClose');
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_status', {
description: 'Report state of both backends: owned port (open / buffer size) and Serial Monitor ' +
'bridge (extension installed / activated / data-subscription available / subscribed). ' +
'Includes the discovered API keys so you can see what MS exposes in the installed build.',
annotations: { readOnlyHint: true, destructiveHint: false },
}, async () => {
const result = await serial('handleStatus');
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_write', {
description: 'Write to the OWNED serial port. Encoding utf8 (default) or hex.',
inputSchema: {
data: z.string().describe("Payload. For encoding='hex' use a hex string like '0a 1b 2c'."),
encoding: z.enum(['utf8', 'hex']).optional(),
appendNewline: z.boolean().optional().describe("Append '\\n' to utf8 payloads (default false)"),
},
}, async (args: { data: string; encoding?: 'utf8' | 'hex'; appendNewline?: boolean }) => {
const result = await serial('handleWrite', args);
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_read', {
description: 'Read buffered RX bytes from either backend. ' +
"Set from='owned' (default) for the MCP-owned port, from='monitor' for bytes captured " +
'via the Serial Monitor bridge subscription. consume=true (default) drains the buffer; ' +
'consume=false peeks. waitMs blocks up to that many ms when buffer is empty.',
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
maxBytes: z.number().int().min(1).optional(),
waitMs: z.number().int().min(0).max(60000).optional(),
consume: z.boolean().optional(),
format: z.enum(['utf8', 'hex', 'both']).optional(),
from: z.enum(['owned', 'monitor']).optional().describe("Backend to read from (default 'owned')"),
},
}, async (args: { maxBytes?: number; waitMs?: number; consume?: boolean; format?: 'utf8' | 'hex' | 'both'; from?: 'owned' | 'monitor' }) => {
const result = await serial('handleRead', args);
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_clear_buffer', {
description: "Discard buffered RX without reading. from='owned' (default) or 'monitor'.",
inputSchema: {
from: z.enum(['owned', 'monitor']).optional(),
},
}, async (args: { from?: 'owned' | 'monitor' }) => {
const result = await serial('handleClearBuffer', args);
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_subscribe_monitor', {
description: 'Subscribe to the MS Serial Monitor extension\'s public data event so the agent can ' +
'read bytes the *user\'s* UI session receives — no port fight, no closing the panel. ' +
'Probes ext.exports for any of: onDidReceiveData / onDataReceived / onData / onSerialData / ' +
'onDidReadData / subscribeData. If the installed Serial Monitor build does not expose a data ' +
'event yet, returns a clear error and you should fall back to serial_open (owned port). ' +
"After subscribing, read with serial_read from='monitor'.",
}, async () => {
const result = await serial('handleSubscribeMonitor');
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_unsubscribe_monitor', {
description: 'Stop the Serial Monitor data subscription (the user\'s UI session is unaffected).',
}, async () => {
const result = await serial('handleUnsubscribeMonitor');
return { content: [{ type: 'text' as const, text: result }] };
});
mcpServer.registerTool('serial_open_monitor', {
description: 'Focus the Microsoft Serial Monitor panel so the user can see / drive their existing ' +
'session. UI-only — does not open or read a port. Pair with serial_subscribe_monitor to also ' +
'feed bytes back to the agent.',
}, async () => {
const result = await serial('handleOpenInUi');
return { content: [{ type: 'text' as const, text: result }] };
});
// CMSIS Solution flash / debug control tool — wraps the CMSIS panel buttons.
mcpServer.registerTool('cmsis_action', {
description: '⭐ PREFERRED entry point for CMSIS / Cortex-M debugging. Drives the CMSIS Solution ' +
'extension — same as clicking the buttons in the CMSIS Solution panel. Operates on the ' +
'currently active csolution context (the one selected in the panel).\n\n' +
'For embedded debug, ALWAYS choose cmsis_action over start_debugging — start_debugging uses the ' +
'plain VS Code debug tab and skips the build / flash pipeline that CMSIS Solution orchestrates.\n\n' +
'build / load / erase / load_and_run WAIT for the cbuild/flash task to finish and return a ' +
'terminal ✅ success / ❌ failure with the task exit code. On failure, read the errors and fix ' +
'the source — do NOT poll for an output file or call get_session_status. load_and_debug / attach ' +
'return quickly and hand off to get_session_status polling.\n' +
'Actions:\n' +
' • build — build the active context. Returns the build result (exit code).\n' +
' • load — flash download to the target. Returns the flash result.\n' +
' • erase — erase target flash. Returns the result.\n' +
' • load_and_run — flash and run (no debug session). Returns the result.\n' +
' • load_and_debug — flash and start a debug session (the "Debug" button). Waits for the session to be ready.\n' +
' • attach — attach debugger to an already-flashed target (skips programming). Waits for the session to be ready.\n' +
' • detach — detach debugger\n' +
' • stop_run — stop a previous load_and_run',
inputSchema: {
action: z.enum([
'build', 'load', 'erase',
'load_and_run', 'load_and_debug',
'attach', 'detach', 'stop_run',
]).describe('Which CMSIS Solution action to invoke'),
timeoutMs: z.number().int().min(100).max(60_000).optional().describe(TIMEOUT_DESC + ' Applies to the session-readiness wait for load_and_debug / attach.'),
},
}, async (args: { action: 'build' | 'load' | 'erase' | 'load_and_run' | 'load_and_debug' | 'attach' | 'detach' | 'stop_run'; timeoutMs?: number }) => {
const result = await debuggingHandler.handleCmsisCommand(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Flash tool — programs the target via `pyocd load --cbuild-run` and
// returns bytes programmed / structured error synchronously.
mcpServer.registerTool('flash', {
description: 'Program the target flash via `pyocd load --cbuild-run` and return a synchronous result: ' +
'bytes programmed + rate on success, or the exit code with the pyOCD error/output tail on failure. ' +
'Programs ALL images listed under `output:` in the cbuild-run file (multi-core safe). ' +
'REFUSES while a debug session is active (programming under a live session wedges most probes) — ' +
'stop_debugging first, then flash, then cmsis_action attach or load_and_debug. ' +
'The cbuild-run file is auto-resolved from the active launch.json / out/ when cbuildRunFile is omitted. ' +
'Requires pyocd on PATH (pip install pyocd); cmsis_action load is the alternative that uses the CMSIS ' +
'extension\'s bundled flash pipeline.',
annotations: { readOnlyHint: false, destructiveHint: true },
inputSchema: {
cbuildRunFile: z.string().optional()
.describe('Path to the .cbuild-run.yml to program. Omit to auto-resolve from launch.json / out/.'),
timeoutMs: z.number().int().min(1_000).max(60_000).optional()
.describe(TIMEOUT_DESC + ' Flash defaults to the full 60 s budget.'),
},
}, async (args: { cbuildRunFile?: string; timeoutMs?: number }) => {
const result = await debuggingHandler.handleFlash(args);
return { content: [{ type: 'text' as const, text: result }] };
});
// Get session status tool
mcpServer.registerTool('get_session_status', {
description: 'Report the current debug-session state in one of five categories: ' +
'`no-session`, `initializing`, `running`, `stopped`, or `unresponsive`. ' +
'Use this whenever you are unsure whether a session is alive — e.g. after a tool ' +
'returned "Debug session is not ready", after a long continue_execution, or after ' +
'an apparent timeout. This tool never hangs and never throws: it always returns a ' +
'classification plus a hint about what to do next. Prefer this over guessing from ' +
'failed tool calls.',
annotations: { readOnlyHint: true, destructiveHint: false },
}, async () => {
const result = await debuggingHandler.handleGetSessionStatus();
return { content: [{ type: 'text' as const, text: result }] };
});
// ========== Multi-window routing ==========
//
// Only registered when this server is actually routing. In a
// single-window setup there is nothing to choose between, and offering
// the tools would just invite the agent to reason about a non-problem.
if (isRoutingHandler(debuggingHandler)) {
const router = debuggingHandler;
mcpServer.registerTool('list_debug_windows', {
description: 'List the VS Code windows this MCP server can drive, with their workspace folders, ' +
'whether each has an active debug session, and which one this session is currently targeting. ' +
'Use it when a tool reports an ambiguous target, or when you suspect you are driving the wrong board.',
annotations: { readOnlyHint: true, destructiveHint: false },
}, async () => {
return { content: [{ type: 'text' as const, text: router.listDebugWindows() }] };
});
mcpServer.registerTool('select_debug_window', {
description: 'Pin this session to one VS Code window, by process id or by a path inside its workspace. ' +
'Every subsequent tool call runs in that window. Needed when several windows are open and more ' +
'than one has a debug session, since the server refuses to guess which board you mean.',
inputSchema: {
pid: z.number().int().optional().describe('Process id of the window, as reported by list_debug_windows.'),
workspaceFolder: z.string().optional().describe('Any path inside the target window\'s workspace folder.'),
},
}, async (args: { pid?: number; workspaceFolder?: string }) => {
return { content: [{ type: 'text' as const, text: router.selectDebugWindow(args) }] };
});
}
}
/**
* Setup MCP resources for documentation
*/
private setupResources(mcpServer: McpServer) {
// Add MCP resources for debugging documentation
mcpServer.registerResource('Debugging Instructions Guide', 'cmsis-developer-assistant://docs/debug_instructions', {
description: 'Step-by-step instructions for debugging with CMSIS Developer Assistant',
mimeType: 'text/markdown',
}, async (uri: URL) => {
const content = await this.loadMarkdownFile('agent-resources/debug_instructions.md');
return {
contents: [{
uri: uri.href,
mimeType: 'text/markdown',
text: content,
}]
};
});
// Add language-specific resources
const languages = ['python', 'javascript', 'java', 'csharp'];
const languageTitles: Record<string, string> = {
'python': 'Python Debugging Tips',
'javascript': 'JavaScript Debugging Tips',
'java': 'Java Debugging Tips',
'csharp': 'C# Debugging Tips'
};
languages.forEach(language => {
mcpServer.registerResource(
languageTitles[language],
`cmsis-developer-assistant://docs/troubleshooting/${language}`,
{
description: `Debugging tips specific to ${language}`,
mimeType: 'text/markdown',
},
async (uri: URL) => {
const content = await this.loadMarkdownFile(`agent-resources/troubleshooting/${language}.md`);
return {
contents: [{
uri: uri.href,
mimeType: 'text/markdown',
text: content,
}]
};
}
);
});
// Add CMSIS embedded debugging guide resource
mcpServer.registerResource(
'CMSIS Embedded Debugging Guide',
'cmsis-developer-assistant://docs/cmsis-embedded-guide',
{
description: 'Comprehensive guide for debugging Cortex-M embedded targets using CMSIS tools, including fault analysis, peripheral inspection, and memory layout.',
mimeType: 'text/markdown',
},
async (uri: URL) => {
const content = await this.loadMarkdownFile('agent-resources/cmsis-embedded-guide.md');
return {
contents: [{
uri: uri.href,
mimeType: 'text/markdown',
text: content,
}]
};
}
);
// Add embedded troubleshooting resource
mcpServer.registerResource(
'Embedded Debugging Tips',
'cmsis-developer-assistant://docs/troubleshooting/embedded',
{
description: 'Troubleshooting tips for embedded Cortex-M debugging, HardFault analysis, and peripheral issues.',
mimeType: 'text/markdown',
},
async (uri: URL) => {
const content = await this.loadMarkdownFile('agent-resources/troubleshooting/embedded.md');
return {
contents: [{
uri: uri.href,
mimeType: 'text/markdown',
text: content,
}]
};
}
);
}
/**
* Load content from a Markdown file in the docs directory
*/
private async loadMarkdownFile(relativePath: string): Promise<string> {
try {
// Get the extension's installation directory
const extensionPath = __dirname; // This points to the compiled extension's directory
const docsPath = path.join(extensionPath, '..', 'docs', relativePath);
console.log(`Loading markdown file from: ${docsPath}`);
// Read the file content
const content = await fs.promises.readFile(docsPath, 'utf8');
console.log(`Successfully loaded ${relativePath}, content length: ${content.length}`);
return content;
} catch (error) {
console.error(`Failed to load ${relativePath}:`, error);
return `Error loading documentation from ${relativePath}: ${error}`;
}
}
/**
* Start the MCP server with Streamable HTTP transport
*/
async start(): Promise<void> {
try {
logger.info(`Starting CMSIS Developer Assistant server (preferred port ${this.port})...`);
const app = express();
// Defense-in-depth against DNS rebinding: the server is bound to
// the loopback interface (below), but a malicious web page can
// still reach 127.0.0.1 through the victim's browser by pointing
// its own DNS record at 127.0.0.1 — the browser then happily
// POSTs to "attacker.com" which resolves to this server. Such
// requests carry the attacker's Host/Origin, so reject anything
// that isn't loopback. Port-agnostic on purpose: the server may
// run on an OS-assigned fallback port.
app.use((req: any, res: any, next: any) => {
if (!isLoopbackHostHeader(req.headers.host)) {
res.status(403).json({ error: 'Forbidden: non-local Host header' });
return;
}
const origin = req.headers.origin;
if (typeof origin === 'string' && !isLoopbackOrigin(origin)) {
res.status(403).json({ error: 'Forbidden: non-local Origin' });
return;
}
next();
});
// Parse JSON body for incoming requests
app.use(express.json());
// POST /mcp — client→server JSON-RPC. An `initialize` request with
// no session id opens a session (transport + McpServer pair) and is
// remembered by the generated id; later requests carrying that
// `mcp-session-id` reuse the same transport.
//
// Stateful session mode, not stateless. Stateless
// (sessionIdGenerator: undefined) cannot serve the server→client
// SSE stream a client opens with GET /mcp right after initialize,
// and it has no session identity for the routing handler to hang a
// target window off. It is also not what fixed the old
// `get_threads`-hangs-after-three-calls bug: that was a *shared*
// McpServer being closed and reconnected per request. A
// session-scoped server is never closed mid-flight.
app.post('/mcp', async (req: any, res: any) => {
try {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
let transport: StreamableHTTPServerTransport;
if (sessionId && this.transports[sessionId]) {
transport = this.transports[sessionId];
} else if (!sessionId && isInitializeRequest(req.body)) {
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sid: string) => {
this.transports[sid] = transport;
logger.info(`MCP session initialized: ${sid}`);
},
});
transport.onclose = () => {
const sid = transport.sessionId;
if (sid && this.transports[sid]) {
delete this.transports[sid];
logger.info(`MCP session closed: ${sid}`);
}