@m4trix/trace-viewer 0.17.0 → 0.19.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/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as _m4trix_tracing from '@m4trix/tracing';
2
2
  import { TraceViewerApi, Trace, TraceRun, TraceRecord } from '@m4trix/tracing';
3
+ import http, { IncomingMessage, ServerResponse } from 'node:http';
3
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
5
  import * as _trpc_server from '@trpc/server';
5
6
  import { AnyRouter } from '@trpc/server';
6
- import http from 'node:http';
7
7
 
8
8
  type AwsStackTraceViewerOptions = {
9
9
  dynamoTable?: string;
@@ -15,7 +15,7 @@ type AwsStackTraceViewerOptions = {
15
15
  declare function createAwsStackTraceViewerApi(options?: AwsStackTraceViewerOptions): TraceViewerApi;
16
16
 
17
17
  type AdapterKind = 'fs' | 'aws-stack';
18
- /** `serve` starts the HTTP viewer; `mcp` serves the trace MCP over stdio. */
18
+ /** `serve` starts the HTTP viewer (with the MCP at `/mcp`); `mcp` serves the trace MCP over stdio. */
19
19
  type CliCommand = 'serve' | 'mcp';
20
20
  type ParsedCli = {
21
21
  command: CliCommand;
@@ -23,6 +23,8 @@ type ParsedCli = {
23
23
  /** Resolved absolute or cwd-relative path for fs adapter */
24
24
  path: string | undefined;
25
25
  port: number;
26
+ /** Serve the MCP endpoint at `/mcp` alongside the viewer. */
27
+ mcp: boolean;
26
28
  };
27
29
  declare const DEFAULT_PORT = 4319;
28
30
  declare const DEFAULT_FS_RELATIVE_PATH = "tmp/tracing-example";
@@ -102,14 +104,25 @@ declare class PayloadIndex {
102
104
  private evict;
103
105
  }
104
106
 
105
- type TraceMcpServerOptions = {
107
+ declare const MCP_HTTP_PATH = "/mcp";
108
+ type TraceMcpHttpHandlerOptions = {
106
109
  traceViewerApi: TraceViewerApi;
107
110
  index?: PayloadIndexOptions;
108
111
  version?: string;
112
+ /** Extra hostnames accepted in the Host header, e.g. when bound to a non-loopback interface. */
113
+ allowedHostnames?: string[];
109
114
  };
110
- declare function createTraceMcpServer(options: TraceMcpServerOptions): McpServer;
111
- /** Serves the trace MCP over stdio. Logs go to stderr; stdout carries the protocol. */
112
- declare function startTraceMcpStdioServer(options: TraceMcpServerOptions): Promise<McpServer>;
115
+ type TraceMcpHttpHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
116
+ /**
117
+ * Guards against DNS rebinding and cross-site requests from browser pages: the Host must be
118
+ * loopback (or explicitly allowed) and an Origin, when sent, must be loopback too.
119
+ */
120
+ declare function isAllowedMcpRequest(req: IncomingMessage, allowedHostnames?: string[]): boolean;
121
+ /**
122
+ * Streamable HTTP MCP endpoint in stateless mode: each POST gets a fresh protocol server, while
123
+ * the tool state (payload index) is shared, so payloads loaded by one call stay searchable.
124
+ */
125
+ declare function createTraceMcpHttpHandler(options: TraceMcpHttpHandlerOptions): TraceMcpHttpHandler;
113
126
 
114
127
  type RunFilter = {
115
128
  type?: string[];
@@ -248,6 +261,17 @@ declare class TraceTools {
248
261
  private loadPayloadValue;
249
262
  }
250
263
 
264
+ type TraceMcpServerOptions = {
265
+ traceViewerApi: TraceViewerApi;
266
+ index?: PayloadIndexOptions;
267
+ version?: string;
268
+ /** Shared tool state (payload index). Pass one instance to keep loaded payloads across servers. */
269
+ tools?: TraceTools;
270
+ };
271
+ declare function createTraceMcpServer(options: TraceMcpServerOptions): McpServer;
272
+ /** Serves the trace MCP over stdio. Logs go to stderr; stdout carries the protocol. */
273
+ declare function startTraceMcpStdioServer(options: TraceMcpServerOptions): Promise<McpServer>;
274
+
251
275
  type TraceViewerContext = {
252
276
  traceViewerApi: TraceViewerApi;
253
277
  };
@@ -319,7 +343,11 @@ type StartServerOptions = {
319
343
  traceViewerApi: TraceViewerApi;
320
344
  port: number;
321
345
  host?: string;
346
+ /** Serve the trace MCP (Streamable HTTP) at `/mcp`. Default true. */
347
+ mcp?: boolean;
348
+ /** Version reported by the MCP server. */
349
+ version?: string;
322
350
  };
323
351
  declare function startTraceViewerServer(options: StartServerOptions): http.Server;
324
352
 
325
- export { type AdapterKind, type AppRouter, type AwsStackTraceViewerOptions, type CliCommand, CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, type ParsedCli, type TraceMcpServerOptions, TraceTools, type TraceViewerContext, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpServer, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
353
+ export { type AdapterKind, type AppRouter, type AwsStackTraceViewerOptions, type CliCommand, CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, MCP_HTTP_PATH, type ParsedCli, type TraceMcpHttpHandlerOptions, type TraceMcpServerOptions, TraceTools, type TraceViewerContext, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpHttpHandler, createTraceMcpServer, isAllowedMcpRequest, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import { TraceStore, S3PayloadStoreAdapter, DynamoStructureStoreAdapter, resolveS3PayloadStoreOptionsFromEnv, resolveDynamoStructureStoreOptionsFromEnv, TraceViewerApi, FsPayloadStoreAdapter, FsStructureStoreAdapter } from '@m4trix/tracing';
1
+ import { TraceStore, TraceViewerApi, FsPayloadStoreAdapter, FsStructureStoreAdapter } from '@m4trix/tracing';
2
+ import { S3PayloadStoreAdapter, DynamoStructureStoreAdapter, resolveS3PayloadStoreOptionsFromEnv, resolveDynamoStructureStoreOptionsFromEnv } from '@m4trix/tracing/aws';
2
3
  import { resolve, relative, sep, extname, join, dirname } from 'path';
4
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
5
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
7
  import { z } from 'zod';
@@ -46,6 +48,7 @@ function parseCliArgs(argv) {
46
48
  let adapter = "fs";
47
49
  let path = DEFAULT_FS_RELATIVE_PATH;
48
50
  let port = DEFAULT_PORT;
51
+ let mcp = true;
49
52
  for (let i = 0; i < args.length; i++) {
50
53
  const a = args[i];
51
54
  if (a === "--adapter") {
@@ -73,6 +76,10 @@ function parseCliArgs(argv) {
73
76
  port = n;
74
77
  continue;
75
78
  }
79
+ if (a === "--no-mcp") {
80
+ mcp = false;
81
+ continue;
82
+ }
76
83
  if (a === "--help" || a === "-h") {
77
84
  throw new CliParseError("HELP");
78
85
  }
@@ -90,7 +97,7 @@ function parseCliArgs(argv) {
90
97
  } else if (!path) {
91
98
  path = DEFAULT_FS_RELATIVE_PATH;
92
99
  }
93
- return { command, adapter, path, port };
100
+ return { command, adapter, path, port, mcp };
94
101
  }
95
102
  function cliHelpText(program) {
96
103
  return `
@@ -101,18 +108,19 @@ Usage:
101
108
  ${program} mcp [--adapter fs|aws-stack] [--path <dir>]
102
109
 
103
110
  Commands:
104
- serve Start the web viewer (default)
105
- mcp Serve an MCP server over stdio for coding agents
111
+ serve Start the web viewer and the MCP endpoint at /mcp (default)
112
+ mcp Serve the MCP over stdio instead (for clients without HTTP support)
106
113
 
107
114
  Options:
108
115
  --adapter fs|aws-stack Storage backend (default: fs)
109
116
  --path <dir> Trace root for fs adapter (default: ${DEFAULT_FS_RELATIVE_PATH})
110
117
  --port <n> HTTP port for serve (default: ${DEFAULT_PORT})
118
+ --no-mcp Do not serve the MCP endpoint at /mcp
111
119
  -h, --help Show this help
112
120
 
113
121
  Examples:
114
122
  ${program} --adapter fs --path ./tmp/tracing-example --port ${DEFAULT_PORT}
115
- claude mcp add m4trix-traces -- npx ${program} mcp --path "$PWD/tmp/tracing-example"
123
+ claude mcp add --transport http m4trix-traces http://127.0.0.1:${DEFAULT_PORT}/mcp
116
124
  `.trim();
117
125
  }
118
126
  function createFsTraceViewerApi(traceRootPath) {
@@ -1728,7 +1736,7 @@ async function respond(task) {
1728
1736
  }
1729
1737
  }
1730
1738
  function createTraceMcpServer(options) {
1731
- const tools = new TraceTools(options.traceViewerApi, { index: options.index });
1739
+ const tools = options.tools ?? new TraceTools(options.traceViewerApi, { index: options.index });
1732
1740
  const server = new McpServer(
1733
1741
  { name: "m4trix-traces", version: options.version ?? "0.0.0" },
1734
1742
  { instructions: SERVER_INSTRUCTIONS }
@@ -1937,6 +1945,69 @@ async function startTraceMcpStdioServer(options) {
1937
1945
  await server.connect(new StdioServerTransport());
1938
1946
  return server;
1939
1947
  }
1948
+
1949
+ // src/mcp/http.ts
1950
+ var MCP_HTTP_PATH = "/mcp";
1951
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
1952
+ function hostnameOf(value) {
1953
+ try {
1954
+ return new URL(value.includes("://") ? value : `http://${value}`).hostname;
1955
+ } catch {
1956
+ return null;
1957
+ }
1958
+ }
1959
+ function isAllowedMcpRequest(req, allowedHostnames = []) {
1960
+ const allowed = /* @__PURE__ */ new Set([...LOOPBACK_HOSTNAMES, ...allowedHostnames]);
1961
+ const host = req.headers.host ? hostnameOf(req.headers.host) : null;
1962
+ if (!host || !allowed.has(host)) return false;
1963
+ const origin = req.headers.origin;
1964
+ if (origin === void 0) return true;
1965
+ const originHost = hostnameOf(origin);
1966
+ return originHost !== null && LOOPBACK_HOSTNAMES.has(originHost);
1967
+ }
1968
+ function sendJsonRpcError(res, status, message) {
1969
+ res.writeHead(status, { "Content-Type": "application/json" });
1970
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message }, id: null }));
1971
+ }
1972
+ function createTraceMcpHttpHandler(options) {
1973
+ const tools = new TraceTools(options.traceViewerApi, { index: options.index });
1974
+ return async (req, res) => {
1975
+ if (!isAllowedMcpRequest(req, options.allowedHostnames)) {
1976
+ sendJsonRpcError(res, 403, "Forbidden: MCP endpoint only accepts local requests.");
1977
+ return;
1978
+ }
1979
+ if (req.method !== "POST") {
1980
+ res.setHeader("Allow", "POST");
1981
+ sendJsonRpcError(
1982
+ res,
1983
+ 405,
1984
+ "Method not allowed: this stateless MCP endpoint only accepts POST."
1985
+ );
1986
+ return;
1987
+ }
1988
+ const server = createTraceMcpServer({
1989
+ traceViewerApi: options.traceViewerApi,
1990
+ version: options.version,
1991
+ tools
1992
+ });
1993
+ const transport = new StreamableHTTPServerTransport({
1994
+ sessionIdGenerator: void 0,
1995
+ enableJsonResponse: true
1996
+ });
1997
+ res.on("close", () => {
1998
+ void transport.close();
1999
+ void server.close();
2000
+ });
2001
+ try {
2002
+ await server.connect(transport);
2003
+ await transport.handleRequest(req, res);
2004
+ } catch (error) {
2005
+ if (!res.headersSent) {
2006
+ sendJsonRpcError(res, 500, error instanceof Error ? error.message : String(error));
2007
+ }
2008
+ }
2009
+ };
2010
+ }
1940
2011
  var t = initTRPC.context().create();
1941
2012
  var listInput = z.object({
1942
2013
  limit: z.number().int().positive().max(500).optional(),
@@ -2024,27 +2095,42 @@ function serveClientAsset(req, res) {
2024
2095
  res.end("client bundle missing; run pnpm --filter @m4trix/trace-viewer build");
2025
2096
  }
2026
2097
  }
2098
+ function isMcpPath(url) {
2099
+ return url === MCP_HTTP_PATH || url.startsWith(`${MCP_HTTP_PATH}?`) || url.startsWith(`${MCP_HTTP_PATH}/`);
2100
+ }
2027
2101
  function startTraceViewerServer(options) {
2028
- const { traceViewerApi, port, host = "127.0.0.1" } = options;
2102
+ const { traceViewerApi, port, host = "127.0.0.1", mcp = true } = options;
2029
2103
  const trpcHandler = createHTTPHandler({
2030
2104
  router: appRouter,
2031
2105
  createContext: () => ({ traceViewerApi }),
2032
2106
  basePath: "/trpc/"
2033
2107
  });
2108
+ const mcpHandler = mcp ? createTraceMcpHttpHandler({
2109
+ traceViewerApi,
2110
+ version: options.version,
2111
+ allowedHostnames: [host]
2112
+ }) : null;
2034
2113
  const server = http.createServer((req, res) => {
2035
2114
  const url = req.url ?? "/";
2036
2115
  if (url.startsWith("/trpc")) {
2037
2116
  void trpcHandler(req, res);
2038
2117
  return;
2039
2118
  }
2119
+ if (mcpHandler && isMcpPath(url)) {
2120
+ void mcpHandler(req, res);
2121
+ return;
2122
+ }
2040
2123
  serveClientAsset(req, res);
2041
2124
  });
2042
2125
  server.listen(port, host, () => {
2043
2126
  console.log(`Trace viewer listening on http://${host}:${port}`);
2127
+ if (mcpHandler) {
2128
+ console.log(`Trace MCP endpoint: http://${host}:${port}${MCP_HTTP_PATH}`);
2129
+ }
2044
2130
  });
2045
2131
  return server;
2046
2132
  }
2047
2133
 
2048
- export { CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, TraceTools, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpServer, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
2134
+ export { CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, MCP_HTTP_PATH, TraceTools, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpHttpHandler, createTraceMcpServer, isAllowedMcpRequest, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
2049
2135
  //# sourceMappingURL=index.js.map
2050
2136
  //# sourceMappingURL=index.js.map