@m4trix/trace-viewer 0.18.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/README.md CHANGED
@@ -20,19 +20,30 @@ pnpm --filter @m4trix/trace-viewer exec m4trix-trace-viewer --adapter fs --path
20
20
  - **`--adapter aws-stack`** — DynamoDB structure + S3 payloads via `TRACE_DYNAMO_TABLE`, `TRACE_S3_BUCKET`, and `AWS_REGION`.
21
21
  - **`--port`** — HTTP listen port (default `4319`).
22
22
  - **`--path`** — trace root for `fs` (default `tmp/tracing-example`).
23
+ - **`--no-mcp`** — do not serve the MCP endpoint at `/mcp` (see below).
23
24
 
24
25
  Then open **http://127.0.0.1:4319** in a browser.
25
26
 
26
27
  ## MCP server for coding agents
27
28
 
28
- `m4trix-trace-viewer mcp` serves the same trace store as a local [MCP](https://modelcontextprotocol.io)
29
- server over stdio, so coding agents can inspect, search and compare traces. It accepts the same
30
- `--adapter` / `--path` flags. Pass an absolute `--path`, because agents may launch it from another directory.
29
+ The running viewer also serves an [MCP](https://modelcontextprotocol.io) endpoint at
30
+ **http://127.0.0.1:4319/mcp** (Streamable HTTP). Coding agents connect to it over localhost to
31
+ inspect, search and compare the same traces you see in the UI. Agents need no trace path or
32
+ credentials, and payloads loaded by one call stay searchable for later calls.
31
33
 
32
34
  ```bash
33
- claude mcp add m4trix-traces -- npx m4trix-trace-viewer mcp --path "$PWD/tmp/tracing-example"
35
+ # Claude Code
36
+ claude mcp add --transport http m4trix-traces http://127.0.0.1:4319/mcp
34
37
  ```
35
38
 
39
+ Other clients take the same URL, e.g. `.mcp.json` / Cursor:
40
+ `{ "mcpServers": { "m4trix-traces": { "type": "http", "url": "http://127.0.0.1:4319/mcp" } } }`.
41
+ Clients without HTTP support can bridge with `npx -y mcp-remote http://127.0.0.1:4319/mcp`.
42
+
43
+ The endpoint only accepts requests whose `Host` (and `Origin`, if sent) is loopback, so web pages
44
+ cannot reach it through your browser. Disable it with `--no-mcp`. To run the MCP without the
45
+ viewer, `m4trix-trace-viewer mcp --path <dir>` serves it over stdio instead.
46
+
36
47
  | Tool | Purpose |
37
48
  | --- | --- |
38
49
  | `list_traces` | Newest-first traces filtered by status, project, name, metadata, time range, latency |
@@ -88,8 +99,10 @@ const traceViewerApi = createFsTraceViewerApi('./tmp/tracing-example');
88
99
  startTraceViewerServer({ traceViewerApi, port: 4319 });
89
100
  ```
90
101
 
91
- `createTraceMcpServer({ traceViewerApi })` returns an `McpServer` you can connect to any MCP
92
- transport; `startTraceMcpStdioServer` does that for stdio.
102
+ `startTraceViewerServer` serves the MCP at `/mcp` unless `mcp: false` is passed.
103
+ `createTraceMcpHttpHandler({ traceViewerApi })` returns a Node request handler to mount it elsewhere,
104
+ and `createTraceMcpServer({ traceViewerApi })` returns an `McpServer` for any MCP transport
105
+ (`startTraceMcpStdioServer` does that for stdio).
93
106
 
94
107
  ## tRPC procedures
95
108
 
package/dist/cli.js CHANGED
@@ -9,10 +9,11 @@ import { existsSync, statSync, readFileSync } from 'fs';
9
9
  import http from 'http';
10
10
  import { fileURLToPath } from 'url';
11
11
  import { createHTTPHandler } from '@trpc/server/adapters/standalone';
12
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
12
13
  import { initTRPC } from '@trpc/server';
13
14
 
14
15
  // package.json
15
- var version = "0.18.0";
16
+ var version = "0.19.0";
16
17
 
17
18
  // src/cli-args.ts
18
19
  var DEFAULT_PORT = 4319;
@@ -29,6 +30,7 @@ function parseCliArgs(argv) {
29
30
  let adapter = "fs";
30
31
  let path = DEFAULT_FS_RELATIVE_PATH;
31
32
  let port = DEFAULT_PORT;
33
+ let mcp = true;
32
34
  for (let i = 0; i < args.length; i++) {
33
35
  const a = args[i];
34
36
  if (a === "--adapter") {
@@ -56,6 +58,10 @@ function parseCliArgs(argv) {
56
58
  port = n;
57
59
  continue;
58
60
  }
61
+ if (a === "--no-mcp") {
62
+ mcp = false;
63
+ continue;
64
+ }
59
65
  if (a === "--help" || a === "-h") {
60
66
  throw new CliParseError("HELP");
61
67
  }
@@ -73,7 +79,7 @@ function parseCliArgs(argv) {
73
79
  } else if (!path) {
74
80
  path = DEFAULT_FS_RELATIVE_PATH;
75
81
  }
76
- return { command, adapter, path, port };
82
+ return { command, adapter, path, port, mcp };
77
83
  }
78
84
  function cliHelpText(program2) {
79
85
  return `
@@ -84,18 +90,19 @@ Usage:
84
90
  ${program2} mcp [--adapter fs|aws-stack] [--path <dir>]
85
91
 
86
92
  Commands:
87
- serve Start the web viewer (default)
88
- mcp Serve an MCP server over stdio for coding agents
93
+ serve Start the web viewer and the MCP endpoint at /mcp (default)
94
+ mcp Serve the MCP over stdio instead (for clients without HTTP support)
89
95
 
90
96
  Options:
91
97
  --adapter fs|aws-stack Storage backend (default: fs)
92
98
  --path <dir> Trace root for fs adapter (default: ${DEFAULT_FS_RELATIVE_PATH})
93
99
  --port <n> HTTP port for serve (default: ${DEFAULT_PORT})
100
+ --no-mcp Do not serve the MCP endpoint at /mcp
94
101
  -h, --help Show this help
95
102
 
96
103
  Examples:
97
104
  ${program2} --adapter fs --path ./tmp/tracing-example --port ${DEFAULT_PORT}
98
- claude mcp add m4trix-traces -- npx ${program2} mcp --path "$PWD/tmp/tracing-example"
105
+ claude mcp add --transport http m4trix-traces http://127.0.0.1:${DEFAULT_PORT}/mcp
99
106
  `.trim();
100
107
  }
101
108
  function createAwsStackTraceViewerApi(options = {}) {
@@ -1731,7 +1738,7 @@ async function respond(task) {
1731
1738
  }
1732
1739
  }
1733
1740
  function createTraceMcpServer(options) {
1734
- const tools = new TraceTools(options.traceViewerApi, { index: options.index });
1741
+ const tools = options.tools ?? new TraceTools(options.traceViewerApi, { index: options.index });
1735
1742
  const server = new McpServer(
1736
1743
  { name: "m4trix-traces", version: options.version ?? "0.0.0" },
1737
1744
  { instructions: SERVER_INSTRUCTIONS }
@@ -1940,6 +1947,67 @@ async function startTraceMcpStdioServer(options) {
1940
1947
  await server.connect(new StdioServerTransport());
1941
1948
  return server;
1942
1949
  }
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
+ }
1943
2011
  var t = initTRPC.context().create();
1944
2012
  var listInput = z.object({
1945
2013
  limit: z.number().int().positive().max(500).optional(),
@@ -2029,23 +2097,38 @@ function serveClientAsset(req, res) {
2029
2097
  res.end("client bundle missing; run pnpm --filter @m4trix/trace-viewer build");
2030
2098
  }
2031
2099
  }
2100
+ function isMcpPath(url) {
2101
+ return url === MCP_HTTP_PATH || url.startsWith(`${MCP_HTTP_PATH}?`) || url.startsWith(`${MCP_HTTP_PATH}/`);
2102
+ }
2032
2103
  function startTraceViewerServer(options) {
2033
- const { traceViewerApi, port, host = "127.0.0.1" } = options;
2104
+ const { traceViewerApi, port, host = "127.0.0.1", mcp = true } = options;
2034
2105
  const trpcHandler = createHTTPHandler({
2035
2106
  router: appRouter,
2036
2107
  createContext: () => ({ traceViewerApi }),
2037
2108
  basePath: "/trpc/"
2038
2109
  });
2110
+ const mcpHandler = mcp ? createTraceMcpHttpHandler({
2111
+ traceViewerApi,
2112
+ version: options.version,
2113
+ allowedHostnames: [host]
2114
+ }) : null;
2039
2115
  const server = http.createServer((req, res) => {
2040
2116
  const url = req.url ?? "/";
2041
2117
  if (url.startsWith("/trpc")) {
2042
2118
  void trpcHandler(req, res);
2043
2119
  return;
2044
2120
  }
2121
+ if (mcpHandler && isMcpPath(url)) {
2122
+ void mcpHandler(req, res);
2123
+ return;
2124
+ }
2045
2125
  serveClientAsset(req, res);
2046
2126
  });
2047
2127
  server.listen(port, host, () => {
2048
2128
  console.log(`Trace viewer listening on http://${host}:${port}`);
2129
+ if (mcpHandler) {
2130
+ console.log(`Trace MCP endpoint: http://${host}:${port}${MCP_HTTP_PATH}`);
2131
+ }
2049
2132
  });
2050
2133
  return server;
2051
2134
  }
@@ -2098,7 +2181,7 @@ function main() {
2098
2181
  });
2099
2182
  return;
2100
2183
  }
2101
- startTraceViewerServer({ traceViewerApi, port: cfg.port });
2184
+ startTraceViewerServer({ traceViewerApi, port: cfg.port, mcp: cfg.mcp, version });
2102
2185
  }
2103
2186
  main();
2104
2187
  //# sourceMappingURL=cli.js.map