@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.
@@ -0,0 +1,5 @@
1
+ // GENERATED — do not edit. Re-run `pnpm --filter @nowline/mcp build` to regenerate.
2
+ // Source: packages/mcp/package.json "version".
3
+
4
+ /** The @nowline/mcp package version, reported as the MCP `serverInfo.version`. */
5
+ export const MCP_VERSION: string = "0.13.0";
package/src/http.ts CHANGED
@@ -5,15 +5,40 @@
5
5
  // own McpServer and transport. Sharing one pair across requests could deliver
6
6
  // one HTTP client's messages to another, and since
7
7
  // @modelcontextprotocol/server 2.3.0 the SDK throws on reuse.
8
+ //
9
+ // Binding 127.0.0.1 keeps other machines out but not a web page the user has
10
+ // open: by DNS rebinding, a page can send requests that reach this socket with
11
+ // its own name in Host and Origin. Stateless mode needs no `initialize`, so one
12
+ // such POST could call any tool. Every request is checked against the
13
+ // localhost names and the port this server listens on before the SDK sees it.
8
14
 
9
15
  import type { IncomingMessage, ServerResponse } from 'node:http';
10
16
  import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
11
- import type { McpServer } from '@modelcontextprotocol/server';
17
+ import {
18
+ localhostAllowedHostnames,
19
+ type McpServer,
20
+ validateHostHeader,
21
+ validateOriginHeader,
22
+ } from '@modelcontextprotocol/server';
23
+
24
+ const LOCALHOST_NAMES = localhostAllowedHostnames();
12
25
 
13
26
  export function createMcpHttpHandler(
14
27
  createServer: () => McpServer,
15
28
  ): (req: IncomingMessage, res: ServerResponse) => Promise<void> {
16
29
  return async (req, res) => {
30
+ const rejection = localRequestRejection(req);
31
+ if (rejection !== undefined) {
32
+ res.writeHead(403, { 'Content-Type': 'application/json' }).end(
33
+ JSON.stringify({
34
+ jsonrpc: '2.0',
35
+ error: { code: -32000, message: rejection },
36
+ id: null,
37
+ }),
38
+ );
39
+ return;
40
+ }
41
+
17
42
  const server = createServer();
18
43
  const transport = new NodeStreamableHTTPServerTransport({
19
44
  sessionIdGenerator: undefined,
@@ -26,3 +51,35 @@ export function createMcpHttpHandler(
26
51
  await transport.handleRequest(req, res);
27
52
  };
28
53
  }
54
+
55
+ /**
56
+ * Why the request must be refused, or `undefined` when it may proceed.
57
+ *
58
+ * Host must name localhost, 127.0.0.1 or [::1] with this server's port. Origin
59
+ * may be absent (MCP clients that aren't browsers don't send one); when present
60
+ * it must be `http://` on one of those names and the same port.
61
+ */
62
+ function localRequestRejection(req: IncomingMessage): string | undefined {
63
+ const port = String(req.socket.localPort);
64
+
65
+ const host = req.headers.host;
66
+ const hostResult = validateHostHeader(host, LOCALHOST_NAMES);
67
+ if (!hostResult.ok) return hostResult.message;
68
+ if (effectivePort(`http://${host}`) !== port) return `Invalid Host: ${host}`;
69
+
70
+ const origin = req.headers.origin;
71
+ const originResult = validateOriginHeader(origin, LOCALHOST_NAMES);
72
+ if (!originResult.ok) return originResult.message;
73
+ if (origin) {
74
+ const url = new URL(origin);
75
+ if (url.protocol !== 'http:' || effectivePort(origin) !== port) {
76
+ return `Invalid Origin: ${origin}`;
77
+ }
78
+ }
79
+ return undefined;
80
+ }
81
+
82
+ function effectivePort(url: string): string {
83
+ const parsed = new URL(url);
84
+ return parsed.port || (parsed.protocol === 'https:' ? '443' : '80');
85
+ }
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // @nowline/mcp — entry point for `npx @nowline/mcp`.
3
3
  //
4
- // Parses --root, --port, and --version flags, creates the MCP server, and
5
- // connects it to the appropriate transport:
4
+ // Parses --root, --port, and --version flags and hands them to
5
+ // startMcpServer (start.ts), which `nowline --mcp` calls too. Transports:
6
6
  // stdio (default) standard MCP stdio transport
7
7
  // http (--port <N>) Streamable HTTP transport on localhost:<N>
8
8
  //
@@ -11,51 +11,25 @@
11
11
  //
12
12
  // Spec: specs/mcp.md.
13
13
 
14
- import { readFileSync } from 'node:fs';
15
- import { createServer } from 'node:http';
16
- import { dirname, resolve } from 'node:path';
17
- import { fileURLToPath } from 'node:url';
18
- import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
19
- import { createMcpHttpHandler } from './http.js';
20
- import { expandRootPath } from './root-path.js';
21
- import { createMcpServer } from './server.js';
22
-
23
- const __filename = fileURLToPath(import.meta.url);
24
- const __dirname = dirname(__filename);
25
-
26
- function readPkgVersion(): string {
27
- try {
28
- const raw = readFileSync(resolve(__dirname, '../package.json'), 'utf-8');
29
- const pkg = JSON.parse(raw) as { version?: string };
30
- return pkg.version ?? '0.0.0';
31
- } catch {
32
- return '0.0.0';
33
- }
34
- }
35
-
36
- const PKG_VERSION = readPkgVersion();
14
+ import { MCP_VERSION } from './generated/version.js';
15
+ import { InvalidPortError, startMcpServer } from './start.js';
37
16
 
38
17
  function parseArgs(argv: string[]): {
39
18
  root?: string;
40
- port?: number;
19
+ port?: string;
41
20
  help: boolean;
42
21
  version: boolean;
43
22
  } {
44
23
  const args = argv.slice(2);
45
24
  let root: string | undefined;
46
- let port: number | undefined;
25
+ let port: string | undefined;
47
26
  let help = false;
48
27
  let version = false;
49
28
  for (let i = 0; i < args.length; i++) {
50
29
  if (args[i] === '--root' && i + 1 < args.length) {
51
30
  root = args[++i];
52
31
  } else if (args[i] === '--port' && i + 1 < args.length) {
53
- const n = parseInt(args[++i], 10);
54
- if (!Number.isFinite(n) || n < 1 || n > 65535) {
55
- process.stderr.write(`nowline-mcp: --port must be a number between 1 and 65535\n`);
56
- process.exit(1);
57
- }
58
- port = n;
32
+ port = args[++i];
59
33
  } else if (args[i] === '-h' || args[i] === '--help') {
60
34
  help = true;
61
35
  } else if (args[i] === '--version' || args[i] === '-v') {
@@ -68,7 +42,7 @@ function parseArgs(argv: string[]): {
68
42
  const { root, port, help, version } = parseArgs(process.argv);
69
43
 
70
44
  if (version) {
71
- process.stdout.write(`${PKG_VERSION}\n`);
45
+ process.stdout.write(`${MCP_VERSION}\n`);
72
46
  process.exit(0);
73
47
  }
74
48
 
@@ -92,34 +66,10 @@ if (help) {
92
66
  process.exit(0);
93
67
  }
94
68
 
95
- // Expand mcpb tokens (${HOME}/~/env vars) so a literal default from the
96
- // .mcpb directory picker resolves to a real path. An empty/blank value
97
- // (optional field left unset) collapses to undefined → cwd fallback, inline.
98
- const expandedRoot = expandRootPath(root);
99
-
100
- const serverOptions = {
101
- allowedRoot: expandedRoot,
102
- rootConfigured: expandedRoot !== undefined,
103
- version: PKG_VERSION,
104
- };
105
-
106
- if (port !== undefined) {
107
- // Streamable HTTP transport — stateless, one server per request.
108
- const httpServer = createServer(createMcpHttpHandler(() => createMcpServer(serverOptions)));
109
-
110
- httpServer.listen(port, '127.0.0.1', () => {
111
- process.stderr.write(
112
- `nowline-mcp: Streamable HTTP listening on http://127.0.0.1:${port}\n`,
113
- );
114
- });
115
-
116
- await new Promise<void>((resolve) => {
117
- httpServer.on('close', resolve);
118
- process.on('SIGINT', () => httpServer.close());
119
- process.on('SIGTERM', () => httpServer.close());
120
- });
121
- } else {
122
- // Default: stdio transport.
123
- const transport = new StdioServerTransport();
124
- await createMcpServer(serverOptions).connect(transport);
69
+ try {
70
+ await startMcpServer({ root, port });
71
+ } catch (err) {
72
+ if (!(err instanceof InvalidPortError)) throw err;
73
+ process.stderr.write(`nowline-mcp: ${err.message}\n`);
74
+ process.exit(1);
125
75
  }
@@ -0,0 +1,134 @@
1
+ // The path-root sandbox for the server's file tools.
2
+ //
3
+ // A path is checked twice: lexically (resolved against the primary root, so a
4
+ // path that names somewhere outside is refused before anything is touched)
5
+ // and again after symlinks are resolved, so a link inside a root cannot reach
6
+ // a file outside every root. File tools also name the extensions they accept,
7
+ // checked on both the requested and the real path, so a `.nowline` link to a
8
+ // non-roadmap file is refused too.
9
+ //
10
+ // Spec: specs/mcp.md "Path roots".
11
+
12
+ import { promises as fs } from 'node:fs';
13
+ import * as path from 'node:path';
14
+ import type { IncludePolicy } from '@nowline/core';
15
+ import { InputRequiredError, PathOutsideRootError } from './diagnostics.js';
16
+ import { isInsideRoots, type WorkspaceRoots } from './workspace-roots.js';
17
+
18
+ /** The extension the roadmap file tools (`read`, `create`, `update`, `delete`, `path` inputs) accept. */
19
+ export const NOWLINE_EXTENSIONS = ['.nowline'] as const;
20
+
21
+ /** The extensions `render` / `export` may write: one per export format. */
22
+ export const OUTPUT_EXTENSIONS = ['.svg', '.png', '.pdf', '.html', '.md', '.xml', '.xlsx'] as const;
23
+
24
+ export interface GuardedPath {
25
+ /** The path as requested, resolved against the primary root. Reported back to the client. */
26
+ readonly abs: string;
27
+ /** `abs` with every symlink resolved; what the tool reads or writes. */
28
+ readonly real: string;
29
+ /** The real allowed root `real` lies in. */
30
+ readonly root: string;
31
+ /** The allowed root as configured (symlinks not resolved) that `root` is the real path of. */
32
+ readonly displayRoot: string;
33
+ }
34
+
35
+ /** Symlinks followed before giving up, as the kernel's own limit (`ELOOP`). */
36
+ const MAX_SYMLINK_HOPS = 40;
37
+
38
+ function loopError(p: string): NodeJS.ErrnoException {
39
+ const err: NodeJS.ErrnoException = new Error(`Too many symbolic links: ${p}`);
40
+ err.code = 'ELOOP';
41
+ return err;
42
+ }
43
+
44
+ /**
45
+ * `p` with every symlink resolved, for a path that may not exist yet: the
46
+ * real path of its deepest existing ancestor joined with the missing rest. A
47
+ * dangling symlink resolves to where it points, so a write through it cannot
48
+ * create a file outside the root.
49
+ */
50
+ export async function realPathAllowingMissing(p: string, hops = 0): Promise<string> {
51
+ if (hops > MAX_SYMLINK_HOPS) throw loopError(p);
52
+ try {
53
+ return await fs.realpath(p);
54
+ } catch (err) {
55
+ const code = (err as NodeJS.ErrnoException).code;
56
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw err;
57
+ }
58
+ const stat = await fs.lstat(p).catch(() => undefined);
59
+ if (stat?.isSymbolicLink()) {
60
+ const target = path.resolve(path.dirname(p), await fs.readlink(p));
61
+ return realPathAllowingMissing(target, hops + 1);
62
+ }
63
+ const parent = path.dirname(p);
64
+ if (parent === p) return p;
65
+ return path.join(await realPathAllowingMissing(parent, hops), path.basename(p));
66
+ }
67
+
68
+ /** Whether `p` is `root` or inside it. */
69
+ export function isWithin(root: string, p: string): boolean {
70
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep;
71
+ return p === root || p.startsWith(prefix);
72
+ }
73
+
74
+ function hasExtension(p: string, extensions: readonly string[]): boolean {
75
+ const lower = p.toLowerCase();
76
+ return extensions.some((ext) => lower.endsWith(ext));
77
+ }
78
+
79
+ /**
80
+ * Resolve `filePath` against the primary root and check it lands inside an
81
+ * allowed root, both as written and with symlinks resolved. With
82
+ * `extensions`, the requested and the real path must each end in one of
83
+ * them (`NL.MCP.INPUT` otherwise). Throws `PathOutsideRootError` for a path
84
+ * outside every root (`NL.MCP.OUT_OF_ROOT`).
85
+ */
86
+ export async function guardPath(
87
+ filePath: string,
88
+ roots: WorkspaceRoots,
89
+ extensions?: readonly string[],
90
+ ): Promise<GuardedPath> {
91
+ const abs = path.resolve(roots.primary, filePath);
92
+ if (!isInsideRoots(abs, roots)) {
93
+ throw new PathOutsideRootError(filePath, roots.allowed.join(', '));
94
+ }
95
+ if (extensions && !hasExtension(abs, extensions)) {
96
+ throw new InputRequiredError(
97
+ `Path ${filePath} must end in ${extensions.join(', ')}; this tool does not touch other files.`,
98
+ );
99
+ }
100
+ const real = await realPathAllowingMissing(abs);
101
+ const realRoots = await Promise.all(roots.allowed.map((r) => realPathAllowingMissing(r)));
102
+ const index = realRoots.findIndex((r) => isWithin(r, real));
103
+ if (index === -1) {
104
+ throw new PathOutsideRootError(filePath, roots.allowed.join(', '));
105
+ }
106
+ const root = realRoots[index];
107
+ const displayRoot = roots.allowed[index];
108
+ if (extensions && !hasExtension(real, extensions)) {
109
+ throw new InputRequiredError(
110
+ `Path ${filePath} is a link to a file that does not end in ${extensions.join(', ')}.`,
111
+ );
112
+ }
113
+ return { abs, real, root, displayRoot };
114
+ }
115
+
116
+ /**
117
+ * The include policy for a roadmap at `target`: includes stay inside its
118
+ * root, symlinks resolved. Resolution works in the root's configured
119
+ * spelling: a real path inside the real root is re-expressed under
120
+ * `displayRoot`, so include diagnostics name the paths the client used
121
+ * (macOS's `/var` is `/private/var` once resolved). A real path outside the
122
+ * real root has no such spelling, stays outside, and is NL.E0208.
123
+ */
124
+ export function includePolicyFor(target: GuardedPath): IncludePolicy {
125
+ return {
126
+ kind: 'rooted',
127
+ root: target.displayRoot,
128
+ realPath: async (p) => {
129
+ const real = await fs.realpath(p);
130
+ if (!isWithin(target.root, real)) return real;
131
+ return path.join(target.displayRoot, path.relative(target.root, real));
132
+ },
133
+ };
134
+ }