@nowline/mcp 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts CHANGED
@@ -16,11 +16,15 @@ import {
16
16
  } from '@modelcontextprotocol/ext-apps/server';
17
17
  import { McpServer } from '@modelcontextprotocol/server';
18
18
  import type { SurfaceOptions } from '@nowline/config';
19
- import { type NowlineFile, parseNowlineJson, printNowlineFile } from '@nowline/core';
19
+ import {
20
+ type IncludePolicy,
21
+ type NowlineFile,
22
+ parseNowlineJson,
23
+ printNowlineFile,
24
+ } from '@nowline/core';
20
25
  import {
21
26
  acceptStagedRoadmap,
22
27
  type ExportFormat,
23
- exportDocument,
24
28
  exportStaged,
25
29
  type HostEnv,
26
30
  IncludeResolveError,
@@ -44,7 +48,6 @@ import {
44
48
  LAYOUT_INSIGHT_HINT,
45
49
  layoutInsightsFromStage,
46
50
  type McpInsight,
47
- PathOutsideRootError,
48
51
  REVIEW_MAX_WIDTH,
49
52
  routedResolveDiagnosticsToMcp,
50
53
  stageMcpRoadmap,
@@ -58,7 +61,17 @@ import {
58
61
  REFERENCE_MAN_PAGE,
59
62
  } from './generated/resources.js';
60
63
  import { PREVIEW_HTML } from './generated/ui-bundle.js';
64
+ import { MCP_VERSION } from './generated/version.js';
61
65
  import { type McpResolvedOptions, resolveMcpOptions } from './options.js';
66
+ import {
67
+ type GuardedPath,
68
+ guardPath,
69
+ includePolicyFor,
70
+ isWithin,
71
+ NOWLINE_EXTENSIONS,
72
+ OUTPUT_EXTENSIONS,
73
+ realPathAllowingMissing,
74
+ } from './path-guard.js';
62
75
  import { registerPrompts } from './prompts.js';
63
76
  import { REFERENCE_CHEATSHEET } from './reference-cheatsheet.js';
64
77
  import { SCHEMA_VOCABULARY } from './schema-vocab.js';
@@ -79,7 +92,7 @@ import {
79
92
  UpdateOutputSchema,
80
93
  ValidateOutputSchema,
81
94
  } from './schemas.js';
82
- import { createWorkspaceRoots, isInsideRoots, type WorkspaceRoots } from './workspace-roots.js';
95
+ import { createWorkspaceRoots, type WorkspaceRoots } from './workspace-roots.js';
83
96
 
84
97
  // ---- MCP Apps UI (in-chat live preview) -------------------------------------
85
98
  //
@@ -173,30 +186,32 @@ function mutatingTool(title: string, opts: { destructiveHint: boolean; idempoten
173
186
  };
174
187
  }
175
188
 
176
- // ---- Server factory ---------------------------------------------------------
177
-
178
- function resolveAndGuard(filePath: string, roots: WorkspaceRoots): string {
179
- const abs = path.resolve(roots.primary, filePath);
180
- if (!isInsideRoots(abs, roots)) {
181
- throw new PathOutsideRootError(filePath, roots.allowed.join(', '));
182
- }
183
- return abs;
184
- }
185
-
186
189
  // ---- Node HostEnv for export ------------------------------------------------
187
190
 
188
- function createNodeHostEnv(sourcePath: string): HostEnv {
189
- const assetRoot = path.resolve(path.dirname(sourcePath));
191
+ /**
192
+ * The kernel's file access for a roadmap read from `target`. The include
193
+ * policy already confines includes to `target.root`; `readSource` checks
194
+ * again so no staging path (a kernel call that takes no policy) reads past
195
+ * it. Assets resolve against the roadmap's directory and must stay in it,
196
+ * symlinks resolved.
197
+ */
198
+ function createNodeHostEnv(target: GuardedPath): HostEnv {
199
+ const assetRoot = path.dirname(target.real);
190
200
  return {
191
201
  async readSource(p: string): Promise<string> {
192
- return fs.readFile(p, 'utf-8');
202
+ const real = await fs.realpath(p);
203
+ if (!isWithin(target.root, real) || !real.endsWith('.nowline')) {
204
+ throw new Error(`Include ${p} is outside the allowed root ${target.root}`);
205
+ }
206
+ return fs.readFile(real, 'utf-8');
193
207
  },
194
208
  async readAsset(ref: string): Promise<Uint8Array> {
195
209
  const abs = path.resolve(assetRoot, ref);
196
- if (!abs.startsWith(assetRoot + path.sep) && abs !== assetRoot) {
210
+ const real = isWithin(assetRoot, abs) ? await fs.realpath(abs) : abs;
211
+ if (!isWithin(assetRoot, real)) {
197
212
  throw new Error(`Asset ${ref} escapes asset-root ${assetRoot}`);
198
213
  }
199
- const bytes = await fs.readFile(abs);
214
+ const bytes = await fs.readFile(real);
200
215
  return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
201
216
  },
202
217
  async loadWasm(): Promise<ArrayBuffer> {
@@ -222,17 +237,30 @@ function findExample(name: string): ExampleFile | undefined {
222
237
  return EXAMPLES.find((e) => e.name === withExt || e.name === name);
223
238
  }
224
239
 
240
+ /**
241
+ * The roadmap a tool works on: inline `source`, or the `.nowline` file at
242
+ * `path`. `filePath` is the path diagnostics report; `target` is where the
243
+ * kernel reads includes and assets from. Inline source sits in the primary
244
+ * root.
245
+ */
225
246
  async function sourceAndPath(
226
247
  args: { source?: string; path?: string },
227
248
  roots: WorkspaceRoots,
228
- ): Promise<{ source: string; filePath: string }> {
249
+ ): Promise<{ source: string; filePath: string; target: GuardedPath }> {
229
250
  if (args.source !== undefined && args.path === undefined) {
230
- return { source: args.source, filePath: path.join(roots.primary, 'unnamed.nowline') };
251
+ const root = await realPathAllowingMissing(roots.primary);
252
+ const target = {
253
+ abs: path.join(roots.primary, 'unnamed.nowline'),
254
+ real: path.join(root, 'unnamed.nowline'),
255
+ root,
256
+ displayRoot: roots.primary,
257
+ };
258
+ return { source: args.source, filePath: target.abs, target };
231
259
  }
232
260
  if (args.path !== undefined) {
233
- const abs = resolveAndGuard(args.path, roots);
234
- const source = args.source ?? (await fs.readFile(abs, 'utf-8'));
235
- return { source, filePath: abs };
261
+ const target = await guardPath(args.path, roots, NOWLINE_EXTENSIONS);
262
+ const source = args.source ?? (await fs.readFile(target.real, 'utf-8'));
263
+ return { source, filePath: target.abs, target };
236
264
  }
237
265
  throw new InputRequiredError('At least one of `source` or `path` is required.');
238
266
  }
@@ -249,7 +277,7 @@ export interface McpServerOptions {
249
277
  rootConfigured?: boolean;
250
278
  /** Server name shown in the MCP client. Defaults to 'nowline'. */
251
279
  name?: string;
252
- /** Server version. Defaults to package version. */
280
+ /** Server version. Defaults to the @nowline/mcp package version. */
253
281
  version?: string;
254
282
  }
255
283
 
@@ -258,7 +286,7 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
258
286
  const server = new McpServer(
259
287
  {
260
288
  name: opts.name ?? 'nowline',
261
- version: opts.version ?? '0.6.0',
289
+ version: opts.version ?? MCP_VERSION,
262
290
  icons: [...NOWLINE_MCP_ICONS],
263
291
  },
264
292
  {
@@ -422,7 +450,10 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
422
450
  async (args) => {
423
451
  try {
424
452
  const { options } = resolveMcpOptions(args);
425
- const { source, filePath } = await sourceAndPath(args, await workspaceRoots());
453
+ const { source, filePath, target } = await sourceAndPath(
454
+ args,
455
+ await workspaceRoots(),
456
+ );
426
457
  const doc = await buildDocument(source);
427
458
  const diagnostics = collectMcpDiagnostics(doc, filePath);
428
459
  // One stage: the routed (wave-rule) include diagnostics join
@@ -435,12 +466,13 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
435
466
  doc,
436
467
  source,
437
468
  {
438
- sourcePath: filePath,
469
+ sourcePath: target.abs,
439
470
  today: options.today,
440
471
  locale: 'en-US',
441
472
  theme: 'light',
442
473
  },
443
- createNodeHostEnv(filePath),
474
+ createNodeHostEnv(target),
475
+ includePolicyFor(target),
444
476
  );
445
477
  diagnostics.push(...stageRoutedDiagnostics(stage));
446
478
  if (stage.kind === 'staged') insights = layoutInsightsFromStage(stage);
@@ -482,8 +514,12 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
482
514
  },
483
515
  async (args) => {
484
516
  try {
485
- const abs = resolveAndGuard(args.path, await workspaceRoots());
486
- const source = await fs.readFile(abs, 'utf-8');
517
+ const { abs, real } = await guardPath(
518
+ args.path,
519
+ await workspaceRoots(),
520
+ NOWLINE_EXTENSIONS,
521
+ );
522
+ const source = await fs.readFile(real, 'utf-8');
487
523
  const structured = { path: abs, source };
488
524
  return {
489
525
  content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],
@@ -516,11 +552,15 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
516
552
  },
517
553
  async (args) => {
518
554
  try {
519
- const abs = resolveAndGuard(args.path, await workspaceRoots());
555
+ const { abs, real } = await guardPath(
556
+ args.path,
557
+ await workspaceRoots(),
558
+ NOWLINE_EXTENSIONS,
559
+ );
520
560
  const blocked = await diagnosticsErrorBlock(args.source, abs);
521
561
  if (!blocked.ok) return blocked.response;
522
- await fs.mkdir(path.dirname(abs), { recursive: true });
523
- await fs.writeFile(abs, args.source, 'utf-8');
562
+ await fs.mkdir(path.dirname(real), { recursive: true });
563
+ await fs.writeFile(real, args.source, 'utf-8');
524
564
  const structured = { ok: true, path: abs };
525
565
  return {
526
566
  content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],
@@ -554,10 +594,14 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
554
594
  },
555
595
  async (args) => {
556
596
  try {
557
- const abs = resolveAndGuard(args.path, await workspaceRoots());
597
+ const { abs, real } = await guardPath(
598
+ args.path,
599
+ await workspaceRoots(),
600
+ NOWLINE_EXTENSIONS,
601
+ );
558
602
  const blocked = await diagnosticsErrorBlock(args.source, abs);
559
603
  if (!blocked.ok) return blocked.response;
560
- await fs.writeFile(abs, args.source, 'utf-8');
604
+ await fs.writeFile(real, args.source, 'utf-8');
561
605
  const structured = { ok: true, path: abs };
562
606
  return {
563
607
  content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],
@@ -585,7 +629,13 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
585
629
  },
586
630
  async (args) => {
587
631
  try {
588
- const abs = resolveAndGuard(args.path, await workspaceRoots());
632
+ // The link itself is removed when `path` is a symlink; the guard
633
+ // still requires its target to be a `.nowline` file in a root.
634
+ const { abs } = await guardPath(
635
+ args.path,
636
+ await workspaceRoots(),
637
+ NOWLINE_EXTENSIONS,
638
+ );
589
639
  await fs.unlink(abs);
590
640
  const structured = { path: abs };
591
641
  return {
@@ -622,7 +672,9 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
622
672
  async (args) => {
623
673
  try {
624
674
  const roots = await workspaceRoots();
625
- const dir = args.directory ? resolveAndGuard(args.directory, roots) : roots.primary;
675
+ const dir = args.directory
676
+ ? (await guardPath(args.directory, roots)).abs
677
+ : roots.primary;
626
678
  const recursive = args.recursive ?? false;
627
679
  const paths = await listNowlineFiles(dir, recursive);
628
680
  const structured = { paths };
@@ -717,8 +769,9 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
717
769
  const { theme, options } = resolved;
718
770
  let source: string;
719
771
  let filePath: string;
772
+ let target: GuardedPath;
720
773
  try {
721
- ({ source, filePath } = await sourceAndPath(args, await workspaceRoots()));
774
+ ({ source, filePath, target } = await sourceAndPath(args, await workspaceRoots()));
722
775
  } catch (err) {
723
776
  return handleToolError(err, args.path);
724
777
  }
@@ -729,7 +782,7 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
729
782
  const format: ExportFormat = args.format ?? 'svg';
730
783
  const today = options.today;
731
784
  const inputs: RenderInputs = {
732
- sourcePath: filePath,
785
+ sourcePath: target.abs,
733
786
  today,
734
787
  locale: 'en-US',
735
788
  theme: options.theme,
@@ -737,7 +790,7 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
737
790
  nonWorking: options.nonWorking,
738
791
  pngScale: args.scale,
739
792
  };
740
- const host = createNodeHostEnv(filePath);
793
+ const host = createNodeHostEnv(target);
741
794
  // Explicit true/false wins; undefined follows the host's capabilities.
742
795
  const appActive = args.preview ?? clientSupportsAppsUi(server);
743
796
  // Skip the full render when the bytes won't be used: apps host with
@@ -748,7 +801,13 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
748
801
  inputs.fonts = { sans: result.sans, mono: result.mono };
749
802
  }
750
803
  // One stage serves the render, the insights and the include check.
751
- const stage = await stageMcpRoadmap(blocked.doc, source, inputs, host);
804
+ const stage = await stageMcpRoadmap(
805
+ blocked.doc,
806
+ source,
807
+ inputs,
808
+ host,
809
+ includePolicyFor(target),
810
+ );
752
811
  if (stage.kind === 'invalid') {
753
812
  return diagnosticsErrorResponse(
754
813
  filePath,
@@ -789,6 +848,7 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
789
848
  bytes,
790
849
  inputs,
791
850
  host,
851
+ includePolicyFor(target),
792
852
  )
793
853
  : [];
794
854
 
@@ -798,9 +858,14 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
798
858
 
799
859
  if (args.output) {
800
860
  try {
801
- const outAbs = resolveAndGuard(args.output, await workspaceRoots());
802
- await fs.mkdir(path.dirname(outAbs), { recursive: true });
803
- await fs.writeFile(outAbs, bytes);
861
+ const out = await guardPath(
862
+ args.output,
863
+ await workspaceRoots(),
864
+ OUTPUT_EXTENSIONS,
865
+ );
866
+ const outAbs = out.abs;
867
+ await fs.mkdir(path.dirname(out.real), { recursive: true });
868
+ await fs.writeFile(out.real, bytes);
804
869
  const structured = {
805
870
  format,
806
871
  path: outAbs,
@@ -951,8 +1016,9 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
951
1016
  }
952
1017
  let source: string;
953
1018
  let filePath: string;
1019
+ let target: GuardedPath;
954
1020
  try {
955
- ({ source, filePath } = await sourceAndPath(args, await workspaceRoots()));
1021
+ ({ source, filePath, target } = await sourceAndPath(args, await workspaceRoots()));
956
1022
  } catch (err) {
957
1023
  return handleToolError(err, args.path);
958
1024
  }
@@ -962,7 +1028,7 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
962
1028
 
963
1029
  const format: ExportFormat = args.format as NonRenderFormat;
964
1030
  const inputs: RenderInputs = {
965
- sourcePath: filePath,
1031
+ sourcePath: target.abs,
966
1032
  today: options.today,
967
1033
  locale: 'en-US',
968
1034
  theme: options.theme,
@@ -977,11 +1043,17 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
977
1043
  const result = await resolveFonts({ headless: true });
978
1044
  inputs.fonts = { sans: result.sans, mono: result.mono };
979
1045
  }
980
- const host = createNodeHostEnv(filePath);
1046
+ const host = createNodeHostEnv(target);
981
1047
  let bytes: Uint8Array;
982
1048
  try {
983
1049
  const staged = acceptStagedRoadmap(
984
- await stageMcpRoadmap(blocked.doc, source, inputs, host),
1050
+ await stageMcpRoadmap(
1051
+ blocked.doc,
1052
+ source,
1053
+ inputs,
1054
+ host,
1055
+ includePolicyFor(target),
1056
+ ),
985
1057
  inputs,
986
1058
  );
987
1059
  bytes = await exportStaged(staged, format, inputs, host);
@@ -1051,10 +1123,10 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
1051
1123
  let writtenPath: string | undefined;
1052
1124
  if (doWrite) {
1053
1125
  try {
1054
- const outAbs = resolveAndGuard(outTarget, roots);
1055
- await fs.mkdir(path.dirname(outAbs), { recursive: true });
1056
- await fs.writeFile(outAbs, bytes);
1057
- writtenPath = outAbs;
1126
+ const out = await guardPath(outTarget, roots, OUTPUT_EXTENSIONS);
1127
+ await fs.mkdir(path.dirname(out.real), { recursive: true });
1128
+ await fs.writeFile(out.real, bytes);
1129
+ writtenPath = out.abs;
1058
1130
  } catch (err) {
1059
1131
  return handleToolError(err, args.output ?? outTarget);
1060
1132
  }
@@ -1179,22 +1251,29 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
1179
1251
  async (args) => {
1180
1252
  try {
1181
1253
  if (args.to === 'json') {
1182
- const { source, filePath } = await sourceAndPath(args, await workspaceRoots());
1183
- const host = createNodeHostEnv(filePath);
1254
+ const { source, target } = await sourceAndPath(args, await workspaceRoots());
1255
+ const host = createNodeHostEnv(target);
1184
1256
  // The JSON AST does not depend on today's date, so convert
1185
1257
  // takes no `now`; the kernel still wants a concrete one.
1186
1258
  const { options } = resolveMcpOptions({});
1187
- const jsonBytes = await exportDocument(
1188
- source,
1189
- 'json',
1190
- {
1191
- sourcePath: filePath,
1192
- today: options.today,
1193
- locale: 'en-US',
1194
- theme: 'light',
1195
- },
1196
- host,
1259
+ const jsonInputs: RenderInputs = {
1260
+ sourcePath: target.abs,
1261
+ today: options.today,
1262
+ locale: 'en-US',
1263
+ theme: 'light',
1264
+ };
1265
+ const doc = await buildDocument(source);
1266
+ const staged = acceptStagedRoadmap(
1267
+ await stageMcpRoadmap(
1268
+ doc,
1269
+ source,
1270
+ jsonInputs,
1271
+ host,
1272
+ includePolicyFor(target),
1273
+ ),
1274
+ jsonInputs,
1197
1275
  );
1276
+ const jsonBytes = await exportStaged(staged, 'json', jsonInputs, host);
1198
1277
  const result = new TextDecoder('utf-8').decode(jsonBytes);
1199
1278
  const structured = { to: 'json' as const, result };
1200
1279
  return {
@@ -1208,7 +1287,7 @@ export function createMcpServer(opts: McpServerOptions = {}): McpServer {
1208
1287
  args.source ??
1209
1288
  (args.path
1210
1289
  ? await fs.readFile(
1211
- resolveAndGuard(args.path, await workspaceRoots()),
1290
+ (await guardPath(args.path, await workspaceRoots(), ['.json'])).real,
1212
1291
  'utf-8',
1213
1292
  )
1214
1293
  : null);
@@ -1529,6 +1608,7 @@ async function buildReviewContentBlocks(
1529
1608
  artifactBytes: Uint8Array,
1530
1609
  inputs: RenderInputs,
1531
1610
  host: HostEnv,
1611
+ includePolicy: IncludePolicy,
1532
1612
  ): Promise<ContentBlock[]> {
1533
1613
  const blocks: ContentBlock[] = [
1534
1614
  {
@@ -1557,7 +1637,7 @@ async function buildReviewContentBlocks(
1557
1637
  // A narrower review width is a different layout, so it stages again
1558
1638
  // (the parsed document is reused).
1559
1639
  const reviewStage = acceptStagedRoadmap(
1560
- await stageMcpRoadmap(doc, source, reviewInputs, host),
1640
+ await stageMcpRoadmap(doc, source, reviewInputs, host, includePolicy),
1561
1641
  reviewInputs,
1562
1642
  );
1563
1643
  inspectionBytes = await exportStaged(reviewStage, 'png', reviewInputs, host);
package/src/start.ts ADDED
@@ -0,0 +1,101 @@
1
+ // The one way to start the Nowline MCP server, shared by `npx @nowline/mcp`
2
+ // and `nowline --mcp`. Both entry points only parse their own flags and call
3
+ // startMcpServer, so `--root`, `--port` and the reported version mean the same
4
+ // thing in each (r1.f15: the CLI once built its own server without
5
+ // `rootConfigured`, so binary exports came back inline instead of saved).
6
+ //
7
+ // Spec: specs/mcp.md.
8
+
9
+ import { createServer } from 'node:http';
10
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
11
+ import { MCP_VERSION } from './generated/version.js';
12
+ import { createMcpHttpHandler } from './http.js';
13
+ import { expandRootPath } from './root-path.js';
14
+ import { createMcpServer, type McpServerOptions } from './server.js';
15
+
16
+ export interface StartMcpServerOptions {
17
+ /**
18
+ * `--root` as the user typed it. Expanded with {@link expandRootPath}; an
19
+ * empty or blank value counts as absent (client roots, else cwd).
20
+ */
21
+ root?: string;
22
+ /** `--port` as the user typed it. Absent: stdio. Present: Streamable HTTP on 127.0.0.1. */
23
+ port?: string;
24
+ /** `serverInfo.version`. Defaults to the @nowline/mcp package version. */
25
+ version?: string;
26
+ /** Called once the HTTP listener is up. Defaults to a line on stderr. */
27
+ onListening?: (url: string) => void;
28
+ }
29
+
30
+ /** A `--port` value that isn't an integer from 1 to 65535. */
31
+ export class InvalidPortError extends Error {
32
+ constructor(public readonly value: string) {
33
+ super(`--port must be a number between 1 and 65535 (got ${value}).`);
34
+ this.name = 'InvalidPortError';
35
+ }
36
+ }
37
+
38
+ /** Parses `--port`, throwing {@link InvalidPortError} unless it is a whole number from 1 to 65535. */
39
+ export function parsePort(raw: string): number {
40
+ const trimmed = raw.trim();
41
+ const port = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;
42
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
43
+ throw new InvalidPortError(raw);
44
+ }
45
+ return port;
46
+ }
47
+
48
+ /** The {@link createMcpServer} options for a given `--root` and version. */
49
+ export function mcpServerOptions(root: string | undefined, version?: string): McpServerOptions {
50
+ // Expand mcpb tokens (${HOME}, ~, env vars) so a literal default from the
51
+ // .mcpb directory picker resolves to a real path.
52
+ const allowedRoot = expandRootPath(root);
53
+ return {
54
+ allowedRoot,
55
+ rootConfigured: allowedRoot !== undefined,
56
+ version: version ?? MCP_VERSION,
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Starts the server and resolves when it stops: for stdio, when the client
62
+ * closes stdin; for HTTP, after SIGINT or SIGTERM closes the listener.
63
+ * Rejects with {@link InvalidPortError} before binding anything when `port` is bad.
64
+ */
65
+ export async function startMcpServer(opts: StartMcpServerOptions = {}): Promise<void> {
66
+ const port = opts.port === undefined ? undefined : parsePort(opts.port);
67
+ const serverOptions = mcpServerOptions(opts.root, opts.version);
68
+
69
+ if (port === undefined) {
70
+ const transport = new StdioServerTransport();
71
+ const closed = new Promise<void>((resolve) => {
72
+ // Set before connect: the SDK wraps an existing onclose rather than replacing it.
73
+ transport.onclose = resolve;
74
+ });
75
+ await createMcpServer(serverOptions).connect(transport);
76
+ await closed;
77
+ return;
78
+ }
79
+
80
+ // Stateless Streamable HTTP: one server per request (see http.ts).
81
+ const httpServer = createServer(createMcpHttpHandler(() => createMcpServer(serverOptions)));
82
+ const onListening =
83
+ opts.onListening ??
84
+ ((url: string) =>
85
+ process.stderr.write(`nowline-mcp: Streamable HTTP listening on ${url}\n`));
86
+
87
+ await new Promise<void>((resolve, reject) => {
88
+ const stop = () => httpServer.close();
89
+ httpServer.once('error', reject);
90
+ httpServer.once('close', () => {
91
+ process.off('SIGINT', stop);
92
+ process.off('SIGTERM', stop);
93
+ resolve();
94
+ });
95
+ httpServer.listen(port, '127.0.0.1', () => {
96
+ process.on('SIGINT', stop);
97
+ process.on('SIGTERM', stop);
98
+ onListening(`http://127.0.0.1:${port}`);
99
+ });
100
+ });
101
+ }