@m4trix/trace-viewer 0.18.0 → 0.20.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.20.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 = {}) {
@@ -471,6 +478,8 @@ function statusIcon(status) {
471
478
  return "\u2713";
472
479
  case "error":
473
480
  return "\u2717";
481
+ case "cancelled":
482
+ return "\u2298";
474
483
  default:
475
484
  return "\u2026";
476
485
  }
@@ -504,6 +513,8 @@ function formatTraceRow(trace) {
504
513
  formatTokens(trace.tokens),
505
514
  trace.costUsd !== void 0 ? `$${trace.costUsd.toFixed(4)}` : "",
506
515
  trace.projectId ? `project=${trace.projectId}` : "",
516
+ trace.sessionId ? `session=${trace.sessionId}` : "",
517
+ trace.userId ? `user=${trace.userId}` : "",
507
518
  formatMetadata(trace.metadata),
508
519
  trace.annotation ? "[annotated]" : ""
509
520
  ].filter(Boolean).join(" ");
@@ -513,6 +524,7 @@ function formatRunLabel(run, options = {}) {
513
524
  const error = run.error && errorChars > 0 ? ` error: ${clip(run.error.message, errorChars)}` : "";
514
525
  return [
515
526
  `${statusIcon(run.status)} ${run.type} ${run.name}`,
527
+ run.model ? `model=${run.model}` : "",
516
528
  formatMs(run.latencyMs),
517
529
  formatTokens(run.tokens),
518
530
  `[${shortId(run.runId)}]`
@@ -923,6 +935,7 @@ var PayloadIndex = class {
923
935
  this.maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
924
936
  this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
925
937
  }
938
+ api;
926
939
  traces = /* @__PURE__ */ new Map();
927
940
  maxChars;
928
941
  concurrency;
@@ -1058,6 +1071,8 @@ function metadataMatches(metadata, expected) {
1058
1071
  function traceMatchesFilter(trace, filter, namePattern) {
1059
1072
  if (filter.status && trace.status !== filter.status) return false;
1060
1073
  if (filter.projectId && trace.projectId !== filter.projectId) return false;
1074
+ if (filter.sessionId && trace.sessionId !== filter.sessionId) return false;
1075
+ if (filter.userId && trace.userId !== filter.userId) return false;
1061
1076
  if (namePattern && !namePattern.test(trace.name)) return false;
1062
1077
  if (filter.minLatencyMs !== void 0 && (trace.latencyMs ?? -1) < filter.minLatencyMs)
1063
1078
  return false;
@@ -1123,8 +1138,11 @@ function searchPayloads(traces, query) {
1123
1138
  return { groups: [...groups.values()], totalOccurrences, searchedPayloads };
1124
1139
  }
1125
1140
 
1141
+ // src/shared/langgraph-plumbing.ts
1142
+ var LANGGRAPH_PLUMBING_PATTERN = "^(ChannelWrite<.*>|Branch<.*>|__start__|__end__)$";
1143
+
1126
1144
  // src/mcp/tree-outline.ts
1127
- var DEFAULT_HIDE_PATTERN = "^(ChannelWrite<.*>|Branch<.*>|__start__|__end__)$";
1145
+ var DEFAULT_HIDE_PATTERN = LANGGRAPH_PLUMBING_PATTERN;
1128
1146
  function renderTreeOutline(roots, options = {}) {
1129
1147
  const maxNodes = options.maxNodes ?? 200;
1130
1148
  const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
@@ -1182,6 +1200,7 @@ var TraceTools = class {
1182
1200
  this.api = api;
1183
1201
  this.index = new PayloadIndex(api, options.index);
1184
1202
  }
1203
+ api;
1185
1204
  index;
1186
1205
  async listTraces(input) {
1187
1206
  const limit = input.limit ?? 20;
@@ -1193,6 +1212,8 @@ var TraceTools = class {
1193
1212
  {
1194
1213
  ...input.status ? { status: input.status } : {},
1195
1214
  ...input.projectId ? { projectId: input.projectId } : {},
1215
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
1216
+ ...input.userId ? { userId: input.userId } : {},
1196
1217
  ...input.since ? { startAfter: input.since } : {},
1197
1218
  ...input.until ? { startBefore: input.until } : {}
1198
1219
  },
@@ -1719,7 +1740,8 @@ var scalar = z.union([z.string(), z.number(), z.boolean()]);
1719
1740
  var traceIdField = z.string().min(1).describe('Trace id, unique prefix, or "latest".');
1720
1741
  var runIdField = z.string().min(1).describe("Run id or unique prefix within the trace.");
1721
1742
  var sideField = z.enum(["input", "output"]);
1722
- var statusField = z.enum(["running", "success", "error"]);
1743
+ var statusField = z.enum(["running", "success", "error", "cancelled"]);
1744
+ var runTypesField = z.array(z.string()).max(50);
1723
1745
  var readOnly = { readOnlyHint: true, openWorldHint: false };
1724
1746
  async function respond(task) {
1725
1747
  try {
@@ -1731,7 +1753,7 @@ async function respond(task) {
1731
1753
  }
1732
1754
  }
1733
1755
  function createTraceMcpServer(options) {
1734
- const tools = new TraceTools(options.traceViewerApi, { index: options.index });
1756
+ const tools = options.tools ?? new TraceTools(options.traceViewerApi, { index: options.index });
1735
1757
  const server = new McpServer(
1736
1758
  { name: "m4trix-traces", version: options.version ?? "0.0.0" },
1737
1759
  { instructions: SERVER_INSTRUCTIONS }
@@ -1744,8 +1766,10 @@ function createTraceMcpServer(options) {
1744
1766
  inputSchema: {
1745
1767
  status: statusField.optional(),
1746
1768
  projectId: z.string().optional(),
1769
+ sessionId: z.string().optional().describe("Conversation / thread id; lists every turn of one conversation."),
1770
+ userId: z.string().optional(),
1747
1771
  name: z.string().optional().describe("Case-insensitive regex against the trace name."),
1748
- metadata: z.record(scalar).optional().describe('Exact match on trace metadata, e.g. { "env": "dev" }.'),
1772
+ metadata: z.record(z.string(), scalar).optional().describe('Exact match on trace metadata, e.g. { "env": "dev" }.'),
1749
1773
  since: z.string().optional().describe("ISO timestamp; only traces started after it."),
1750
1774
  until: z.string().optional().describe("ISO timestamp; only traces started before it."),
1751
1775
  minLatencyMs: z.number().nonnegative().optional(),
@@ -1781,15 +1805,15 @@ function createTraceMcpServer(options) {
1781
1805
  title: "Find runs",
1782
1806
  description: "Find runs by structural fields (type, name, status, error message, latency, tokens, metadata) across one or more traces. Does not read payloads.",
1783
1807
  inputSchema: {
1784
- traceIds: z.array(z.string().min(1)).optional().describe("Defaults to the newest traceLimit traces."),
1808
+ traceIds: z.array(z.string().min(1)).max(500).optional().describe("Defaults to the newest traceLimit traces."),
1785
1809
  traceLimit: z.number().int().positive().max(500).optional().describe("Default 20."),
1786
- type: z.array(z.string()).optional().describe('Run types, e.g. ["tool", "chat_model"].'),
1810
+ type: runTypesField.optional().describe('Run types, e.g. ["tool", "chat_model"].'),
1787
1811
  name: z.string().optional().describe("Case-insensitive regex against run names."),
1788
1812
  status: statusField.optional(),
1789
1813
  errorContains: z.string().optional(),
1790
1814
  minLatencyMs: z.number().nonnegative().optional(),
1791
1815
  minTokens: z.number().nonnegative().optional(),
1792
- metadata: z.record(scalar).optional(),
1816
+ metadata: z.record(z.string(), scalar).optional(),
1793
1817
  maxDepth: z.number().int().nonnegative().optional(),
1794
1818
  limit: z.number().int().positive().max(500).optional().describe("Default 50.")
1795
1819
  },
@@ -1837,7 +1861,7 @@ function createTraceMcpServer(options) {
1837
1861
  title: "Load trace payloads",
1838
1862
  description: "Load all input/output payloads of traces into the in-memory search index (required before search_payloads can search them). Pass traceIds, or omit them to load the newest `limit` traces matching status/projectId. Reloading a trace only fetches new payloads.",
1839
1863
  inputSchema: {
1840
- traceIds: z.array(z.string().min(1)).optional(),
1864
+ traceIds: z.array(z.string().min(1)).max(100).optional(),
1841
1865
  status: statusField.optional(),
1842
1866
  projectId: z.string().optional(),
1843
1867
  limit: z.number().int().positive().max(100).optional().describe("Default 10 when traceIds is omitted.")
@@ -1856,7 +1880,7 @@ function createTraceMcpServer(options) {
1856
1880
  regex: z.boolean().optional(),
1857
1881
  caseSensitive: z.boolean().optional(),
1858
1882
  traceIds: z.array(z.string().min(1)).max(20).optional(),
1859
- runType: z.array(z.string()).optional(),
1883
+ runType: runTypesField.optional(),
1860
1884
  runName: z.string().optional().describe("Case-insensitive regex against run names."),
1861
1885
  side: z.enum(["input", "output", "both"]).optional(),
1862
1886
  pathPrefix: z.string().optional().describe('Only leaves under this path, e.g. "$.messages".'),
@@ -1921,7 +1945,7 @@ function createTraceMcpServer(options) {
1921
1945
  inputSchema: {
1922
1946
  traceId: traceIdField,
1923
1947
  runId: runIdField.optional(),
1924
- annotation: z.record(z.unknown()),
1948
+ annotation: z.record(z.string(), z.unknown()),
1925
1949
  merge: z.boolean().optional().describe("Default true. false replaces the whole annotation.")
1926
1950
  },
1927
1951
  annotations: {
@@ -1940,16 +1964,77 @@ async function startTraceMcpStdioServer(options) {
1940
1964
  await server.connect(new StdioServerTransport());
1941
1965
  return server;
1942
1966
  }
1967
+ var MCP_HTTP_PATH = "/mcp";
1968
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
1969
+ function hostnameOf(value) {
1970
+ try {
1971
+ return new URL(value.includes("://") ? value : `http://${value}`).hostname;
1972
+ } catch {
1973
+ return null;
1974
+ }
1975
+ }
1976
+ function isAllowedMcpRequest(req, allowedHostnames = []) {
1977
+ const allowed = /* @__PURE__ */ new Set([...LOOPBACK_HOSTNAMES, ...allowedHostnames]);
1978
+ const host = req.headers.host ? hostnameOf(req.headers.host) : null;
1979
+ if (!host || !allowed.has(host)) return false;
1980
+ const origin = req.headers.origin;
1981
+ if (origin === void 0) return true;
1982
+ const originHost = hostnameOf(origin);
1983
+ return originHost !== null && LOOPBACK_HOSTNAMES.has(originHost);
1984
+ }
1985
+ function sendJsonRpcError(res, status, message) {
1986
+ res.writeHead(status, { "Content-Type": "application/json" });
1987
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message }, id: null }));
1988
+ }
1989
+ function createTraceMcpHttpHandler(options) {
1990
+ const tools = new TraceTools(options.traceViewerApi, { index: options.index });
1991
+ return async (req, res) => {
1992
+ if (!isAllowedMcpRequest(req, options.allowedHostnames)) {
1993
+ sendJsonRpcError(res, 403, "Forbidden: MCP endpoint only accepts local requests.");
1994
+ return;
1995
+ }
1996
+ if (req.method !== "POST") {
1997
+ res.setHeader("Allow", "POST");
1998
+ sendJsonRpcError(
1999
+ res,
2000
+ 405,
2001
+ "Method not allowed: this stateless MCP endpoint only accepts POST."
2002
+ );
2003
+ return;
2004
+ }
2005
+ const server = createTraceMcpServer({
2006
+ traceViewerApi: options.traceViewerApi,
2007
+ version: options.version,
2008
+ tools
2009
+ });
2010
+ const transport = new StreamableHTTPServerTransport({
2011
+ sessionIdGenerator: void 0,
2012
+ enableJsonResponse: true
2013
+ });
2014
+ res.on("close", () => {
2015
+ void transport.close();
2016
+ void server.close();
2017
+ });
2018
+ try {
2019
+ await server.connect(transport);
2020
+ await transport.handleRequest(req, res);
2021
+ } catch (error) {
2022
+ if (!res.headersSent) {
2023
+ sendJsonRpcError(res, 500, error instanceof Error ? error.message : String(error));
2024
+ }
2025
+ }
2026
+ };
2027
+ }
1943
2028
  var t = initTRPC.context().create();
1944
2029
  var listInput = z.object({
1945
2030
  limit: z.number().int().positive().max(500).optional(),
1946
2031
  cursor: z.string().optional(),
1947
- status: z.enum(["running", "success", "error"]).optional(),
2032
+ status: z.enum(["running", "success", "error", "cancelled"]).optional(),
1948
2033
  projectId: z.string().optional()
1949
2034
  }).optional();
1950
2035
  var annotationInput = z.object({
1951
2036
  traceId: z.string().min(1),
1952
- annotation: z.record(z.unknown()),
2037
+ annotation: z.record(z.string(), z.unknown()),
1953
2038
  merge: z.boolean().optional()
1954
2039
  });
1955
2040
  var appRouterImpl = t.router({
@@ -2029,23 +2114,38 @@ function serveClientAsset(req, res) {
2029
2114
  res.end("client bundle missing; run pnpm --filter @m4trix/trace-viewer build");
2030
2115
  }
2031
2116
  }
2117
+ function isMcpPath(url) {
2118
+ return url === MCP_HTTP_PATH || url.startsWith(`${MCP_HTTP_PATH}?`) || url.startsWith(`${MCP_HTTP_PATH}/`);
2119
+ }
2032
2120
  function startTraceViewerServer(options) {
2033
- const { traceViewerApi, port, host = "127.0.0.1" } = options;
2121
+ const { traceViewerApi, port, host = "127.0.0.1", mcp = true } = options;
2034
2122
  const trpcHandler = createHTTPHandler({
2035
2123
  router: appRouter,
2036
2124
  createContext: () => ({ traceViewerApi }),
2037
2125
  basePath: "/trpc/"
2038
2126
  });
2127
+ const mcpHandler = mcp ? createTraceMcpHttpHandler({
2128
+ traceViewerApi,
2129
+ version: options.version,
2130
+ allowedHostnames: [host]
2131
+ }) : null;
2039
2132
  const server = http.createServer((req, res) => {
2040
2133
  const url = req.url ?? "/";
2041
2134
  if (url.startsWith("/trpc")) {
2042
2135
  void trpcHandler(req, res);
2043
2136
  return;
2044
2137
  }
2138
+ if (mcpHandler && isMcpPath(url)) {
2139
+ void mcpHandler(req, res);
2140
+ return;
2141
+ }
2045
2142
  serveClientAsset(req, res);
2046
2143
  });
2047
2144
  server.listen(port, host, () => {
2048
2145
  console.log(`Trace viewer listening on http://${host}:${port}`);
2146
+ if (mcpHandler) {
2147
+ console.log(`Trace MCP endpoint: http://${host}:${port}${MCP_HTTP_PATH}`);
2148
+ }
2049
2149
  });
2050
2150
  return server;
2051
2151
  }
@@ -2098,7 +2198,7 @@ function main() {
2098
2198
  });
2099
2199
  return;
2100
2200
  }
2101
- startTraceViewerServer({ traceViewerApi, port: cfg.port });
2201
+ startTraceViewerServer({ traceViewerApi, port: cfg.port, mcp: cfg.mcp, version });
2102
2202
  }
2103
2203
  main();
2104
2204
  //# sourceMappingURL=cli.js.map