@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 +19 -6
- package/dist/cli.js +119 -19
- package/dist/cli.js.map +1 -1
- package/dist/client/assets/{anthropic-DUwMYY1S.js → anthropic-lPPXtrig.js} +3 -3
- package/dist/client/assets/{bedrock-BIja-RWN.js → bedrock-B2FP1s10.js} +1 -1
- package/dist/client/assets/index-BSgeyMwl.css +1 -0
- package/dist/client/assets/index-C8P-vN-T.js +335 -0
- package/dist/client/assets/{node.browser-C_s9kvmM.js → node.browser-D3cYDtw3.js} +1 -1
- package/dist/client/assets/{node.browser-DWucOsQl.js → node.browser-DsCY38-C.js} +1 -1
- package/dist/client/assets/{openai-mbLa3c0B.js → openai-Dytrlt1h.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/index.d.ts +41 -10
- package/dist/index.js +120 -18
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
- package/dist/client/assets/index-Cl5VyaKo.js +0 -274
- package/dist/client/assets/index-DVz5tq4u.css +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as o}from"./anthropic-
|
|
1
|
+
import{A as o}from"./anthropic-lPPXtrig.js";import"./index-C8P-vN-T.js";function n(e){return new Proxy({},{get(i,t){if(typeof t!="symbol")throw new o(`\`${e}.${t}\` is not available in this environment; it needs a Node.js-compatible runtime`)}})}const s=n("fs"),f=n("path");export{s as fs,f as path};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as s}from"./anthropic-
|
|
1
|
+
import{A as s}from"./anthropic-lPPXtrig.js";import{D as R,M as B}from"./anthropic-lPPXtrig.js";import"./index-C8P-vN-T.js";function e(o){throw new s(`${o} requires Node.js or a Node-compatible runtime`)}const a=3e4,c=".anthropic-memory-store";class u extends s{constructor(t,r){super(t),this.name="SessionMemoryError",r!==void 0&&(this.cause=r)}}class l{constructor(t,r){e("SessionMemoryStores")}get roots(){return e("SessionMemoryStores")}get readOnlyRoots(){return e("SessionMemoryStores")}download(t){return e("SessionMemoryStores")}finish(){return e("SessionMemoryStores")}syncAll(t){return e("SessionMemoryStores")}syncIfDue(){return e("SessionMemoryStores")}flushWrites(t){return e("SessionMemoryStores")}dispose(){return e("SessionMemoryStores")}}function S(o){return e("setupSkills")}function _(o,t){return e("extractSkillArchive")}function m(o){return e("betaAgentToolset20260401")}function M(o,t){return e("resolvePath")}class h extends s{constructor(t){super(`bash command timed out after ${t}ms`),this.name="BashTimeoutError",this.timeoutMs=t}}class T{constructor(t,r){e("BashSession")}get closed(){return e("BashSession")}exec(t,r={}){return e("BashSession")}close(){e("BashSession")}}function d(o){return e("betaBashTool")}function f(o){return e("betaReadTool")}function b(o){return e("betaWriteTool")}function p(o){return e("betaEditTool")}function y(o){return e("betaGlobTool")}function x(o){return e("betaGrepTool")}export{T as BashSession,h as BashTimeoutError,R as DEFAULT_MEMORY_SYNC_INTERVAL_MS,c as MARKER_PATH,a as MEMORY_FLUSH_TIMEOUT_MS,B as MIN_MEMORY_SYNC_INTERVAL_MS,u as SessionMemoryError,l as SessionMemoryStores,m as betaAgentToolset20260401,d as betaBashTool,p as betaEditTool,y as betaGlobTool,x as betaGrepTool,f as betaReadTool,b as betaWriteTool,_ as extractSkillArchive,M as resolvePath,S as setupSkills};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as p,t as c,P as r,k as l}from"./index-
|
|
1
|
+
import{j as p,t as c,P as r,k as l}from"./index-C8P-vN-T.js";const d="https://api.openai.com/v1/responses",m=32e3;async function f(e){try{return(await e.json()).error?.message??`HTTP ${e.status}`}catch{return`HTTP ${e.status}`}}function h(e){return/json/i.test(e)?e:`${e}
|
|
2
2
|
|
|
3
3
|
Respond with a single JSON object.`}function w(e,i={}){const u=i.fetch??globalThis.fetch.bind(globalThis);return{id:"openai",async generate(n){let o;try{o=await u(d,{method:"POST",signal:n.signal,headers:{"content-type":"application/json",authorization:`Bearer ${e.credentials.apiKey??""}`},body:JSON.stringify({model:e.model,instructions:n.system,input:h(p(n)),max_output_tokens:n.maxTokens??m,text:{format:{type:"json_object"}}})})}catch(t){throw c(t)}if(!o.ok)throw new r(l(o.status),await f(o),o.status);const s=await o.json(),a=(s.output??[]).filter(t=>t.type==="message").flatMap(t=>t.content??[]);if(a.some(t=>t.type==="refusal"))throw new r("refusal",a.find(t=>t.type==="refusal")?.refusal??"Refused.");if(s.status==="incomplete"){const t=s.incomplete_details?.reason??"unknown";throw new r(t==="max_output_tokens"?"truncated":"other",`Response incomplete (${t}).`)}return{text:a.filter(t=>t.type==="output_text").map(t=>t.text??"").join("").trim(),model:s.model??e.model,usage:{inputTokens:s.usage?.input_tokens,outputTokens:s.usage?.output_tokens}}}}}export{d as OPENAI_RESPONSES_URL,w as createOpenAIProvider,h as openAIJsonModeInput};
|
package/dist/client/index.html
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>m4trix trace viewer</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-C8P-vN-T.js"></script>
|
|
8
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BSgeyMwl.css">
|
|
9
9
|
</head>
|
|
10
10
|
<body>
|
|
11
11
|
<div id="root"></div>
|
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,20 +104,31 @@ declare class PayloadIndex {
|
|
|
102
104
|
private evict;
|
|
103
105
|
}
|
|
104
106
|
|
|
105
|
-
|
|
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
|
-
|
|
111
|
-
/**
|
|
112
|
-
|
|
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[];
|
|
116
129
|
/** Case-insensitive regex against run names. */
|
|
117
130
|
name?: string;
|
|
118
|
-
status?: '
|
|
131
|
+
status?: Trace['status'];
|
|
119
132
|
/** Case-insensitive substring of the run error message. */
|
|
120
133
|
errorContains?: string;
|
|
121
134
|
minLatencyMs?: number;
|
|
@@ -128,6 +141,9 @@ type RunFilter = {
|
|
|
128
141
|
type TraceFilter = {
|
|
129
142
|
status?: Trace['status'];
|
|
130
143
|
projectId?: string;
|
|
144
|
+
/** Conversation or thread the trace belongs to. */
|
|
145
|
+
sessionId?: string;
|
|
146
|
+
userId?: string;
|
|
131
147
|
/** Case-insensitive regex against trace names. */
|
|
132
148
|
name?: string;
|
|
133
149
|
metadata?: Record<string, string | number | boolean>;
|
|
@@ -248,6 +264,17 @@ declare class TraceTools {
|
|
|
248
264
|
private loadPayloadValue;
|
|
249
265
|
}
|
|
250
266
|
|
|
267
|
+
type TraceMcpServerOptions = {
|
|
268
|
+
traceViewerApi: TraceViewerApi;
|
|
269
|
+
index?: PayloadIndexOptions;
|
|
270
|
+
version?: string;
|
|
271
|
+
/** Shared tool state (payload index). Pass one instance to keep loaded payloads across servers. */
|
|
272
|
+
tools?: TraceTools;
|
|
273
|
+
};
|
|
274
|
+
declare function createTraceMcpServer(options: TraceMcpServerOptions): McpServer;
|
|
275
|
+
/** Serves the trace MCP over stdio. Logs go to stderr; stdout carries the protocol. */
|
|
276
|
+
declare function startTraceMcpStdioServer(options: TraceMcpServerOptions): Promise<McpServer>;
|
|
277
|
+
|
|
251
278
|
type TraceViewerContext = {
|
|
252
279
|
traceViewerApi: TraceViewerApi;
|
|
253
280
|
};
|
|
@@ -265,9 +292,9 @@ declare const appRouterImpl: _trpc_server.TRPCBuiltRouter<{
|
|
|
265
292
|
}, _trpc_server.TRPCDecorateCreateRouterOptions<{
|
|
266
293
|
list: _trpc_server.TRPCQueryProcedure<{
|
|
267
294
|
input: {
|
|
268
|
-
status?: "error" | "running" | "success" | undefined;
|
|
269
295
|
limit?: number | undefined;
|
|
270
296
|
cursor?: string | undefined;
|
|
297
|
+
status?: "error" | "running" | "success" | "cancelled" | undefined;
|
|
271
298
|
projectId?: string | undefined;
|
|
272
299
|
} | undefined;
|
|
273
300
|
output: _m4trix_tracing.ListTracesResult;
|
|
@@ -302,8 +329,8 @@ declare const appRouterImpl: _trpc_server.TRPCBuiltRouter<{
|
|
|
302
329
|
patchRunAnnotation: _trpc_server.TRPCMutationProcedure<{
|
|
303
330
|
input: {
|
|
304
331
|
traceId: string;
|
|
305
|
-
runId: string;
|
|
306
332
|
annotation: Record<string, unknown>;
|
|
333
|
+
runId: string;
|
|
307
334
|
merge?: boolean | undefined;
|
|
308
335
|
};
|
|
309
336
|
output: _m4trix_tracing.TraceRun | null;
|
|
@@ -319,7 +346,11 @@ type StartServerOptions = {
|
|
|
319
346
|
traceViewerApi: TraceViewerApi;
|
|
320
347
|
port: number;
|
|
321
348
|
host?: string;
|
|
349
|
+
/** Serve the trace MCP (Streamable HTTP) at `/mcp`. Default true. */
|
|
350
|
+
mcp?: boolean;
|
|
351
|
+
/** Version reported by the MCP server. */
|
|
352
|
+
version?: string;
|
|
322
353
|
};
|
|
323
354
|
declare function startTraceViewerServer(options: StartServerOptions): http.Server;
|
|
324
355
|
|
|
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 };
|
|
356
|
+
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,6 +1,7 @@
|
|
|
1
1
|
import { TraceStore, TraceViewerApi, FsPayloadStoreAdapter, FsStructureStoreAdapter } from '@m4trix/tracing';
|
|
2
2
|
import { S3PayloadStoreAdapter, DynamoStructureStoreAdapter, resolveS3PayloadStoreOptionsFromEnv, resolveDynamoStructureStoreOptionsFromEnv } from '@m4trix/tracing/aws';
|
|
3
3
|
import { resolve, relative, sep, extname, join, dirname } from 'path';
|
|
4
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
4
5
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
5
6
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
6
7
|
import { z } from 'zod';
|
|
@@ -47,6 +48,7 @@ function parseCliArgs(argv) {
|
|
|
47
48
|
let adapter = "fs";
|
|
48
49
|
let path = DEFAULT_FS_RELATIVE_PATH;
|
|
49
50
|
let port = DEFAULT_PORT;
|
|
51
|
+
let mcp = true;
|
|
50
52
|
for (let i = 0; i < args.length; i++) {
|
|
51
53
|
const a = args[i];
|
|
52
54
|
if (a === "--adapter") {
|
|
@@ -74,6 +76,10 @@ function parseCliArgs(argv) {
|
|
|
74
76
|
port = n;
|
|
75
77
|
continue;
|
|
76
78
|
}
|
|
79
|
+
if (a === "--no-mcp") {
|
|
80
|
+
mcp = false;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
77
83
|
if (a === "--help" || a === "-h") {
|
|
78
84
|
throw new CliParseError("HELP");
|
|
79
85
|
}
|
|
@@ -91,7 +97,7 @@ function parseCliArgs(argv) {
|
|
|
91
97
|
} else if (!path) {
|
|
92
98
|
path = DEFAULT_FS_RELATIVE_PATH;
|
|
93
99
|
}
|
|
94
|
-
return { command, adapter, path, port };
|
|
100
|
+
return { command, adapter, path, port, mcp };
|
|
95
101
|
}
|
|
96
102
|
function cliHelpText(program) {
|
|
97
103
|
return `
|
|
@@ -102,18 +108,19 @@ Usage:
|
|
|
102
108
|
${program} mcp [--adapter fs|aws-stack] [--path <dir>]
|
|
103
109
|
|
|
104
110
|
Commands:
|
|
105
|
-
serve Start the web viewer (default)
|
|
106
|
-
mcp Serve
|
|
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)
|
|
107
113
|
|
|
108
114
|
Options:
|
|
109
115
|
--adapter fs|aws-stack Storage backend (default: fs)
|
|
110
116
|
--path <dir> Trace root for fs adapter (default: ${DEFAULT_FS_RELATIVE_PATH})
|
|
111
117
|
--port <n> HTTP port for serve (default: ${DEFAULT_PORT})
|
|
118
|
+
--no-mcp Do not serve the MCP endpoint at /mcp
|
|
112
119
|
-h, --help Show this help
|
|
113
120
|
|
|
114
121
|
Examples:
|
|
115
122
|
${program} --adapter fs --path ./tmp/tracing-example --port ${DEFAULT_PORT}
|
|
116
|
-
claude mcp add m4trix-traces
|
|
123
|
+
claude mcp add --transport http m4trix-traces http://127.0.0.1:${DEFAULT_PORT}/mcp
|
|
117
124
|
`.trim();
|
|
118
125
|
}
|
|
119
126
|
function createFsTraceViewerApi(traceRootPath) {
|
|
@@ -469,6 +476,8 @@ function statusIcon(status) {
|
|
|
469
476
|
return "\u2713";
|
|
470
477
|
case "error":
|
|
471
478
|
return "\u2717";
|
|
479
|
+
case "cancelled":
|
|
480
|
+
return "\u2298";
|
|
472
481
|
default:
|
|
473
482
|
return "\u2026";
|
|
474
483
|
}
|
|
@@ -502,6 +511,8 @@ function formatTraceRow(trace) {
|
|
|
502
511
|
formatTokens(trace.tokens),
|
|
503
512
|
trace.costUsd !== void 0 ? `$${trace.costUsd.toFixed(4)}` : "",
|
|
504
513
|
trace.projectId ? `project=${trace.projectId}` : "",
|
|
514
|
+
trace.sessionId ? `session=${trace.sessionId}` : "",
|
|
515
|
+
trace.userId ? `user=${trace.userId}` : "",
|
|
505
516
|
formatMetadata(trace.metadata),
|
|
506
517
|
trace.annotation ? "[annotated]" : ""
|
|
507
518
|
].filter(Boolean).join(" ");
|
|
@@ -511,6 +522,7 @@ function formatRunLabel(run, options = {}) {
|
|
|
511
522
|
const error = run.error && errorChars > 0 ? ` error: ${clip(run.error.message, errorChars)}` : "";
|
|
512
523
|
return [
|
|
513
524
|
`${statusIcon(run.status)} ${run.type} ${run.name}`,
|
|
525
|
+
run.model ? `model=${run.model}` : "",
|
|
514
526
|
formatMs(run.latencyMs),
|
|
515
527
|
formatTokens(run.tokens),
|
|
516
528
|
`[${shortId(run.runId)}]`
|
|
@@ -921,6 +933,7 @@ var PayloadIndex = class {
|
|
|
921
933
|
this.maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
|
|
922
934
|
this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
|
|
923
935
|
}
|
|
936
|
+
api;
|
|
924
937
|
traces = /* @__PURE__ */ new Map();
|
|
925
938
|
maxChars;
|
|
926
939
|
concurrency;
|
|
@@ -1056,6 +1069,8 @@ function metadataMatches(metadata, expected) {
|
|
|
1056
1069
|
function traceMatchesFilter(trace, filter, namePattern) {
|
|
1057
1070
|
if (filter.status && trace.status !== filter.status) return false;
|
|
1058
1071
|
if (filter.projectId && trace.projectId !== filter.projectId) return false;
|
|
1072
|
+
if (filter.sessionId && trace.sessionId !== filter.sessionId) return false;
|
|
1073
|
+
if (filter.userId && trace.userId !== filter.userId) return false;
|
|
1059
1074
|
if (namePattern && !namePattern.test(trace.name)) return false;
|
|
1060
1075
|
if (filter.minLatencyMs !== void 0 && (trace.latencyMs ?? -1) < filter.minLatencyMs)
|
|
1061
1076
|
return false;
|
|
@@ -1121,8 +1136,11 @@ function searchPayloads(traces, query) {
|
|
|
1121
1136
|
return { groups: [...groups.values()], totalOccurrences, searchedPayloads };
|
|
1122
1137
|
}
|
|
1123
1138
|
|
|
1139
|
+
// src/shared/langgraph-plumbing.ts
|
|
1140
|
+
var LANGGRAPH_PLUMBING_PATTERN = "^(ChannelWrite<.*>|Branch<.*>|__start__|__end__)$";
|
|
1141
|
+
|
|
1124
1142
|
// src/mcp/tree-outline.ts
|
|
1125
|
-
var DEFAULT_HIDE_PATTERN =
|
|
1143
|
+
var DEFAULT_HIDE_PATTERN = LANGGRAPH_PLUMBING_PATTERN;
|
|
1126
1144
|
function renderTreeOutline(roots, options = {}) {
|
|
1127
1145
|
const maxNodes = options.maxNodes ?? 200;
|
|
1128
1146
|
const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
|
|
@@ -1180,6 +1198,7 @@ var TraceTools = class {
|
|
|
1180
1198
|
this.api = api;
|
|
1181
1199
|
this.index = new PayloadIndex(api, options.index);
|
|
1182
1200
|
}
|
|
1201
|
+
api;
|
|
1183
1202
|
index;
|
|
1184
1203
|
async listTraces(input) {
|
|
1185
1204
|
const limit = input.limit ?? 20;
|
|
@@ -1191,6 +1210,8 @@ var TraceTools = class {
|
|
|
1191
1210
|
{
|
|
1192
1211
|
...input.status ? { status: input.status } : {},
|
|
1193
1212
|
...input.projectId ? { projectId: input.projectId } : {},
|
|
1213
|
+
...input.sessionId ? { sessionId: input.sessionId } : {},
|
|
1214
|
+
...input.userId ? { userId: input.userId } : {},
|
|
1194
1215
|
...input.since ? { startAfter: input.since } : {},
|
|
1195
1216
|
...input.until ? { startBefore: input.until } : {}
|
|
1196
1217
|
},
|
|
@@ -1717,7 +1738,8 @@ var scalar = z.union([z.string(), z.number(), z.boolean()]);
|
|
|
1717
1738
|
var traceIdField = z.string().min(1).describe('Trace id, unique prefix, or "latest".');
|
|
1718
1739
|
var runIdField = z.string().min(1).describe("Run id or unique prefix within the trace.");
|
|
1719
1740
|
var sideField = z.enum(["input", "output"]);
|
|
1720
|
-
var statusField = z.enum(["running", "success", "error"]);
|
|
1741
|
+
var statusField = z.enum(["running", "success", "error", "cancelled"]);
|
|
1742
|
+
var runTypesField = z.array(z.string()).max(50);
|
|
1721
1743
|
var readOnly = { readOnlyHint: true, openWorldHint: false };
|
|
1722
1744
|
async function respond(task) {
|
|
1723
1745
|
try {
|
|
@@ -1729,7 +1751,7 @@ async function respond(task) {
|
|
|
1729
1751
|
}
|
|
1730
1752
|
}
|
|
1731
1753
|
function createTraceMcpServer(options) {
|
|
1732
|
-
const tools = new TraceTools(options.traceViewerApi, { index: options.index });
|
|
1754
|
+
const tools = options.tools ?? new TraceTools(options.traceViewerApi, { index: options.index });
|
|
1733
1755
|
const server = new McpServer(
|
|
1734
1756
|
{ name: "m4trix-traces", version: options.version ?? "0.0.0" },
|
|
1735
1757
|
{ instructions: SERVER_INSTRUCTIONS }
|
|
@@ -1742,8 +1764,10 @@ function createTraceMcpServer(options) {
|
|
|
1742
1764
|
inputSchema: {
|
|
1743
1765
|
status: statusField.optional(),
|
|
1744
1766
|
projectId: z.string().optional(),
|
|
1767
|
+
sessionId: z.string().optional().describe("Conversation / thread id; lists every turn of one conversation."),
|
|
1768
|
+
userId: z.string().optional(),
|
|
1745
1769
|
name: z.string().optional().describe("Case-insensitive regex against the trace name."),
|
|
1746
|
-
metadata: z.record(scalar).optional().describe('Exact match on trace metadata, e.g. { "env": "dev" }.'),
|
|
1770
|
+
metadata: z.record(z.string(), scalar).optional().describe('Exact match on trace metadata, e.g. { "env": "dev" }.'),
|
|
1747
1771
|
since: z.string().optional().describe("ISO timestamp; only traces started after it."),
|
|
1748
1772
|
until: z.string().optional().describe("ISO timestamp; only traces started before it."),
|
|
1749
1773
|
minLatencyMs: z.number().nonnegative().optional(),
|
|
@@ -1779,15 +1803,15 @@ function createTraceMcpServer(options) {
|
|
|
1779
1803
|
title: "Find runs",
|
|
1780
1804
|
description: "Find runs by structural fields (type, name, status, error message, latency, tokens, metadata) across one or more traces. Does not read payloads.",
|
|
1781
1805
|
inputSchema: {
|
|
1782
|
-
traceIds: z.array(z.string().min(1)).optional().describe("Defaults to the newest traceLimit traces."),
|
|
1806
|
+
traceIds: z.array(z.string().min(1)).max(500).optional().describe("Defaults to the newest traceLimit traces."),
|
|
1783
1807
|
traceLimit: z.number().int().positive().max(500).optional().describe("Default 20."),
|
|
1784
|
-
type:
|
|
1808
|
+
type: runTypesField.optional().describe('Run types, e.g. ["tool", "chat_model"].'),
|
|
1785
1809
|
name: z.string().optional().describe("Case-insensitive regex against run names."),
|
|
1786
1810
|
status: statusField.optional(),
|
|
1787
1811
|
errorContains: z.string().optional(),
|
|
1788
1812
|
minLatencyMs: z.number().nonnegative().optional(),
|
|
1789
1813
|
minTokens: z.number().nonnegative().optional(),
|
|
1790
|
-
metadata: z.record(scalar).optional(),
|
|
1814
|
+
metadata: z.record(z.string(), scalar).optional(),
|
|
1791
1815
|
maxDepth: z.number().int().nonnegative().optional(),
|
|
1792
1816
|
limit: z.number().int().positive().max(500).optional().describe("Default 50.")
|
|
1793
1817
|
},
|
|
@@ -1835,7 +1859,7 @@ function createTraceMcpServer(options) {
|
|
|
1835
1859
|
title: "Load trace payloads",
|
|
1836
1860
|
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.",
|
|
1837
1861
|
inputSchema: {
|
|
1838
|
-
traceIds: z.array(z.string().min(1)).optional(),
|
|
1862
|
+
traceIds: z.array(z.string().min(1)).max(100).optional(),
|
|
1839
1863
|
status: statusField.optional(),
|
|
1840
1864
|
projectId: z.string().optional(),
|
|
1841
1865
|
limit: z.number().int().positive().max(100).optional().describe("Default 10 when traceIds is omitted.")
|
|
@@ -1854,7 +1878,7 @@ function createTraceMcpServer(options) {
|
|
|
1854
1878
|
regex: z.boolean().optional(),
|
|
1855
1879
|
caseSensitive: z.boolean().optional(),
|
|
1856
1880
|
traceIds: z.array(z.string().min(1)).max(20).optional(),
|
|
1857
|
-
runType:
|
|
1881
|
+
runType: runTypesField.optional(),
|
|
1858
1882
|
runName: z.string().optional().describe("Case-insensitive regex against run names."),
|
|
1859
1883
|
side: z.enum(["input", "output", "both"]).optional(),
|
|
1860
1884
|
pathPrefix: z.string().optional().describe('Only leaves under this path, e.g. "$.messages".'),
|
|
@@ -1919,7 +1943,7 @@ function createTraceMcpServer(options) {
|
|
|
1919
1943
|
inputSchema: {
|
|
1920
1944
|
traceId: traceIdField,
|
|
1921
1945
|
runId: runIdField.optional(),
|
|
1922
|
-
annotation: z.record(z.unknown()),
|
|
1946
|
+
annotation: z.record(z.string(), z.unknown()),
|
|
1923
1947
|
merge: z.boolean().optional().describe("Default true. false replaces the whole annotation.")
|
|
1924
1948
|
},
|
|
1925
1949
|
annotations: {
|
|
@@ -1938,16 +1962,79 @@ async function startTraceMcpStdioServer(options) {
|
|
|
1938
1962
|
await server.connect(new StdioServerTransport());
|
|
1939
1963
|
return server;
|
|
1940
1964
|
}
|
|
1965
|
+
|
|
1966
|
+
// src/mcp/http.ts
|
|
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
|
+
}
|
|
1941
2028
|
var t = initTRPC.context().create();
|
|
1942
2029
|
var listInput = z.object({
|
|
1943
2030
|
limit: z.number().int().positive().max(500).optional(),
|
|
1944
2031
|
cursor: z.string().optional(),
|
|
1945
|
-
status: z.enum(["running", "success", "error"]).optional(),
|
|
2032
|
+
status: z.enum(["running", "success", "error", "cancelled"]).optional(),
|
|
1946
2033
|
projectId: z.string().optional()
|
|
1947
2034
|
}).optional();
|
|
1948
2035
|
var annotationInput = z.object({
|
|
1949
2036
|
traceId: z.string().min(1),
|
|
1950
|
-
annotation: z.record(z.unknown()),
|
|
2037
|
+
annotation: z.record(z.string(), z.unknown()),
|
|
1951
2038
|
merge: z.boolean().optional()
|
|
1952
2039
|
});
|
|
1953
2040
|
var appRouterImpl = t.router({
|
|
@@ -2025,27 +2112,42 @@ function serveClientAsset(req, res) {
|
|
|
2025
2112
|
res.end("client bundle missing; run pnpm --filter @m4trix/trace-viewer build");
|
|
2026
2113
|
}
|
|
2027
2114
|
}
|
|
2115
|
+
function isMcpPath(url) {
|
|
2116
|
+
return url === MCP_HTTP_PATH || url.startsWith(`${MCP_HTTP_PATH}?`) || url.startsWith(`${MCP_HTTP_PATH}/`);
|
|
2117
|
+
}
|
|
2028
2118
|
function startTraceViewerServer(options) {
|
|
2029
|
-
const { traceViewerApi, port, host = "127.0.0.1" } = options;
|
|
2119
|
+
const { traceViewerApi, port, host = "127.0.0.1", mcp = true } = options;
|
|
2030
2120
|
const trpcHandler = createHTTPHandler({
|
|
2031
2121
|
router: appRouter,
|
|
2032
2122
|
createContext: () => ({ traceViewerApi }),
|
|
2033
2123
|
basePath: "/trpc/"
|
|
2034
2124
|
});
|
|
2125
|
+
const mcpHandler = mcp ? createTraceMcpHttpHandler({
|
|
2126
|
+
traceViewerApi,
|
|
2127
|
+
version: options.version,
|
|
2128
|
+
allowedHostnames: [host]
|
|
2129
|
+
}) : null;
|
|
2035
2130
|
const server = http.createServer((req, res) => {
|
|
2036
2131
|
const url = req.url ?? "/";
|
|
2037
2132
|
if (url.startsWith("/trpc")) {
|
|
2038
2133
|
void trpcHandler(req, res);
|
|
2039
2134
|
return;
|
|
2040
2135
|
}
|
|
2136
|
+
if (mcpHandler && isMcpPath(url)) {
|
|
2137
|
+
void mcpHandler(req, res);
|
|
2138
|
+
return;
|
|
2139
|
+
}
|
|
2041
2140
|
serveClientAsset(req, res);
|
|
2042
2141
|
});
|
|
2043
2142
|
server.listen(port, host, () => {
|
|
2044
2143
|
console.log(`Trace viewer listening on http://${host}:${port}`);
|
|
2144
|
+
if (mcpHandler) {
|
|
2145
|
+
console.log(`Trace MCP endpoint: http://${host}:${port}${MCP_HTTP_PATH}`);
|
|
2146
|
+
}
|
|
2045
2147
|
});
|
|
2046
2148
|
return server;
|
|
2047
2149
|
}
|
|
2048
2150
|
|
|
2049
|
-
export { CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, TraceTools, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpServer, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
|
|
2151
|
+
export { CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, MCP_HTTP_PATH, TraceTools, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpHttpHandler, createTraceMcpServer, isAllowedMcpRequest, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
|
|
2050
2152
|
//# sourceMappingURL=index.js.map
|
|
2051
2153
|
//# sourceMappingURL=index.js.map
|