@tonyclaw/llm-inspector 1.12.0 → 1.14.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.
Files changed (35) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/index-B5q3Llgm.css +1 -0
  3. package/.output/public/assets/index-C6tbslcs.js +105 -0
  4. package/.output/public/assets/{main-BYCM7aJx.js → main-C1k6vRnH.js} +3 -3
  5. package/.output/server/_libs/cfworker__json-schema.mjs +1 -0
  6. package/.output/server/_libs/lucide-react.mjs +64 -58
  7. package/.output/server/_libs/modelcontextprotocol__server.mjs +9738 -0
  8. package/.output/server/_libs/zod.mjs +79 -16
  9. package/.output/server/_ssr/{index-DhChP_jV.mjs → index-AxruZp16.mjs} +1201 -165
  10. package/.output/server/_ssr/index.mjs +2 -2
  11. package/.output/server/_ssr/{router-PZjNwOcw.mjs → router-DtleGqN8.mjs} +650 -29
  12. package/.output/server/_tanstack-start-manifest_v-B1WAHWIa.mjs +4 -0
  13. package/.output/server/index.mjs +24 -24
  14. package/README.md +98 -0
  15. package/package.json +3 -1
  16. package/src/components/ProxyViewer.tsx +126 -2
  17. package/src/components/proxy-viewer/CompareDrawer.tsx +880 -0
  18. package/src/components/proxy-viewer/ConversationGroup.tsx +8 -0
  19. package/src/components/proxy-viewer/LogEntry.tsx +14 -1
  20. package/src/components/proxy-viewer/LogEntryHeader.tsx +28 -0
  21. package/src/components/proxy-viewer/formats/openai/ResponseView.tsx +74 -4
  22. package/src/components/proxy-viewer/requestDiff.ts +277 -0
  23. package/src/lib/serverPort.ts +41 -0
  24. package/src/mcp/loopback.ts +76 -0
  25. package/src/mcp/previewExtractor.ts +166 -0
  26. package/src/mcp/server.ts +320 -0
  27. package/src/mcp/toolHandlers.ts +259 -0
  28. package/src/proxy/formats/openai/schemas.ts +19 -0
  29. package/src/proxy/handler.ts +23 -2
  30. package/src/proxy/openaiOrphanToolStrip.ts +148 -0
  31. package/src/proxy/schemas.ts +1 -0
  32. package/src/routes/api/mcp.ts +25 -0
  33. package/.output/public/assets/index-DVgdkDgq.js +0 -105
  34. package/.output/public/assets/index-DZx2yk8v.css +0 -1
  35. package/.output/server/_tanstack-start-manifest_v-l1kWkG0h.mjs +0 -4
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Format-parser-driven preview extractor for the MCP `inspector_list_logs`
3
+ * "thick summary" shape. See `openspec/changes/add-mcp-server/design.md`
4
+ * decision D5.
5
+ *
6
+ * Why we re-parse with the format schemas (not slice `rawRequestBody`):
7
+ * a 500-char prefix is almost always JSON envelope + system prompt boilerplate
8
+ * with zero signal about what the user actually asked. The format parsers
9
+ * give us the first text block of the last user message, which is what an
10
+ * agent needs to make a "is this the log I care about?" judgment from
11
+ * `list_logs` alone.
12
+ *
13
+ * Null returns are an expected and frequent outcome — they cover:
14
+ * - `apiFormat === "unknown"`
15
+ * - `rawRequestBody` / `responseText` is null
16
+ * - JSON.parse failure
17
+ * - schema validation failure
18
+ * - no qualifying user / assistant message
19
+ * - the relevant content is non-text (e.g., image-only multimodal block)
20
+ */
21
+
22
+ import type { CapturedLog } from "../proxy/schemas";
23
+ import {
24
+ AnthropicRequestSchema,
25
+ AnthropicResponseSchema,
26
+ } from "../proxy/formats/anthropic/schemas";
27
+ import { OpenAIRequestSchema, OpenAIResponseSchema } from "../proxy/formats/openai/schemas";
28
+
29
+ /** Preview length cap, per design D5. */
30
+ const PREVIEW_MAX_CHARS = 500;
31
+
32
+ function truncate(text: string): string {
33
+ return text.length <= PREVIEW_MAX_CHARS ? text : text.slice(0, PREVIEW_MAX_CHARS);
34
+ }
35
+
36
+ /**
37
+ * Safely extract the first text from an Anthropic `Message.content` (string
38
+ * or array of blocks). Returns `null` for non-text-only or empty content.
39
+ */
40
+ function firstAnthropicText(
41
+ content: string | ReadonlyArray<{ type: string; text?: string }>,
42
+ ): string | null {
43
+ if (typeof content === "string") {
44
+ return content.length > 0 ? content : null;
45
+ }
46
+ for (const block of content) {
47
+ if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) {
48
+ return block.text;
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * Safely extract the first text from an OpenAI message content (string or
56
+ * array of `{type:"text"|"image_url",...}`). Returns `null` for non-text /
57
+ * empty content.
58
+ */
59
+ function firstOpenAIText(
60
+ content: string | ReadonlyArray<{ type: string; text?: string }> | null | undefined,
61
+ ): string | null {
62
+ if (content === null || content === undefined) return null;
63
+ if (typeof content === "string") {
64
+ return content.length > 0 ? content : null;
65
+ }
66
+ for (const part of content) {
67
+ if (part.type === "text" && typeof part.text === "string" && part.text.length > 0) {
68
+ return part.text;
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * Extract a 500-char preview of the last `role: "user"` message's first text
76
+ * block. Returns `null` for unknown format, parse failures, or non-text
77
+ * content. See module-level docstring for the full null-case list.
78
+ */
79
+ export function extractLastUserMessagePreview(log: CapturedLog): string | null {
80
+ if (log.apiFormat === "unknown") return null;
81
+ if (log.rawRequestBody === null) return null;
82
+
83
+ let json: unknown;
84
+ try {
85
+ json = JSON.parse(log.rawRequestBody);
86
+ } catch {
87
+ return null;
88
+ }
89
+
90
+ if (log.apiFormat === "anthropic") {
91
+ const parsed = AnthropicRequestSchema.safeParse(json);
92
+ if (!parsed.success) return null;
93
+ // Iterate from the end to find the most recent user turn.
94
+ for (let i = parsed.data.messages.length - 1; i >= 0; i--) {
95
+ const msg = parsed.data.messages[i];
96
+ if (msg && msg.role === "user") {
97
+ const text = firstAnthropicText(msg.content);
98
+ return text === null ? null : truncate(text);
99
+ }
100
+ }
101
+ return null;
102
+ }
103
+
104
+ if (log.apiFormat === "openai") {
105
+ const parsed = OpenAIRequestSchema.safeParse(json);
106
+ if (!parsed.success) return null;
107
+ for (let i = parsed.data.messages.length - 1; i >= 0; i--) {
108
+ const msg = parsed.data.messages[i];
109
+ if (msg && msg.role === "user") {
110
+ const text = firstOpenAIText(msg.content);
111
+ return text === null ? null : truncate(text);
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+
117
+ return null;
118
+ }
119
+
120
+ /**
121
+ * Extract a 500-char preview of the assistant's response text. Returns
122
+ * `null` for unknown format, parse failures, missing response, or non-text
123
+ * content.
124
+ */
125
+ export function extractResponsePreview(log: CapturedLog): string | null {
126
+ if (log.apiFormat === "unknown") return null;
127
+ if (log.responseText === null) return null;
128
+
129
+ let json: unknown;
130
+ try {
131
+ json = JSON.parse(log.responseText);
132
+ } catch {
133
+ return null;
134
+ }
135
+
136
+ if (log.apiFormat === "anthropic") {
137
+ const parsed = AnthropicResponseSchema.safeParse(json);
138
+ if (!parsed.success) return null;
139
+ for (const block of parsed.data.content) {
140
+ if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) {
141
+ return truncate(block.text);
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ if (log.apiFormat === "openai") {
148
+ const parsed = OpenAIResponseSchema.safeParse(json);
149
+ if (!parsed.success) return null;
150
+ // Pick the first choice that actually carries a text-like content.
151
+ for (const choice of parsed.data.choices) {
152
+ const msg = choice.message;
153
+ if (!msg) continue;
154
+ const direct = firstOpenAIText(msg.content);
155
+ if (direct !== null) return truncate(direct);
156
+ // Some MiniMax / Moonshot-style providers stuff the text into
157
+ // reasoning_content / thinking / think instead of content. We surface
158
+ // whichever is the first non-empty one in a stable priority order.
159
+ const fallback = msg.reasoning_content ?? msg.thinking ?? msg.think;
160
+ if (typeof fallback === "string" && fallback.length > 0) return truncate(fallback);
161
+ }
162
+ return null;
163
+ }
164
+
165
+ return null;
166
+ }
@@ -0,0 +1,320 @@
1
+ /**
2
+ * MCP (Model Context Protocol) server for llm-inspector.
3
+ *
4
+ * Exposes 11 `inspector_*` tools that delegate to existing `/api/*` endpoints
5
+ * via internal HTTP loopback (see `loopback.ts` for the rationale). Mounted
6
+ * at `POST /api/mcp` in the existing TanStack Start process using HTTP Streamable
7
+ * transport. localhost-only, no auth in v1 — see
8
+ * `openspec/changes/add-mcp-server/design.md` decisions D1, D2, D9.
9
+ *
10
+ * The `McpServer` + `WebStandardStreamableHTTPServerTransport` pair is
11
+ * instantiated once per process on first request and reused for all
12
+ * subsequent requests (stateless mode — no `sessionIdGenerator`).
13
+ *
14
+ * Tool implementations live in `./toolHandlers.ts` so they can be unit
15
+ * tested with a mock `callApi`. This file just wires them to the SDK.
16
+ */
17
+
18
+ import { z } from "zod";
19
+ import { McpServer, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server";
20
+ import { setCurrentPort } from "../lib/serverPort";
21
+ import { callApi } from "./loopback";
22
+ import {
23
+ addProviderImpl,
24
+ getLogChunksImpl,
25
+ getLogImpl,
26
+ getProviderImpl,
27
+ listLogsImpl,
28
+ listModelsImpl,
29
+ listProvidersImpl,
30
+ listSessionsImpl,
31
+ replayLogImpl,
32
+ safeCall,
33
+ testProviderImpl,
34
+ updateProviderImpl,
35
+ } from "./toolHandlers";
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Lazy singleton: build the McpServer + transport on first use.
39
+ // ---------------------------------------------------------------------------
40
+
41
+ type ServerPair = { server: McpServer; transport: WebStandardStreamableHTTPServerTransport };
42
+
43
+ let initialized: ServerPair | null = null;
44
+ let initPromise: Promise<ServerPair> | null = null;
45
+
46
+ function buildServer(): ServerPair {
47
+ const server = new McpServer(
48
+ { name: "llm-inspector", version: "1.0.0" },
49
+ { capabilities: { tools: {} } },
50
+ );
51
+ registerTools(server);
52
+ const transport = new WebStandardStreamableHTTPServerTransport({
53
+ sessionIdGenerator: undefined, // stateless — see module docstring
54
+ });
55
+ // The connect() call is async but we don't need to await it here; the SDK
56
+ // buffers the first request internally.
57
+ void server.connect(transport);
58
+ return { server, transport };
59
+ }
60
+
61
+ async function getServer(): Promise<ServerPair> {
62
+ if (initialized !== null) return initialized;
63
+ if (initPromise === null) {
64
+ initPromise = Promise.resolve(buildServer()).then((pair) => {
65
+ initialized = pair;
66
+ return pair;
67
+ });
68
+ }
69
+ return initPromise;
70
+ }
71
+
72
+ /** Reset for tests. */
73
+ export async function _resetForTests(): Promise<void> {
74
+ if (initialized !== null) {
75
+ try {
76
+ await initialized.server.close();
77
+ } catch {
78
+ // ignore
79
+ }
80
+ }
81
+ initialized = null;
82
+ initPromise = null;
83
+ }
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Public entry point for the route handler.
87
+ // ---------------------------------------------------------------------------
88
+
89
+ /**
90
+ * Handle an incoming MCP HTTP request. Suitable as a TanStack Start route
91
+ * handler — accepts a Web `Request`, returns a `Promise<Response>`.
92
+ */
93
+ export async function handleMcpRequest(request: Request): Promise<Response> {
94
+ // Extract port from the incoming request URL so loopback calls work even
95
+ // when PORT env var is unset (e.g. MCP client connected before server init).
96
+ try {
97
+ const url = new URL(request.url);
98
+ const port = Number(url.port);
99
+ if (port > 0) setCurrentPort(port);
100
+ } catch {
101
+ // URL parse failure → fall through to PORT env var in getCurrentPort()
102
+ }
103
+ const { transport } = await getServer();
104
+ return transport.handleRequest(request);
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Tool descriptions (kept here, not in toolHandlers.ts, because they are
109
+ // only relevant to the wire-level MCP registration).
110
+ // ---------------------------------------------------------------------------
111
+
112
+ const TOOL_LIST_LOGS_DESC = `List recent captured LLM proxy logs in reverse-chronological order with parsed previews. Useful for "what did I just send?" discovery.
113
+
114
+ REFLEXIVE-LOOP WARNING: this list includes the agent's own recent /proxy calls. If results appear to be the agent's own tool calls (e.g., the agent called inspector_list_logs and now sees itself in the results), filter by clientPid (your own PID) or by timestamp on the client side.
115
+
116
+ Parameters:
117
+ - offset (number, default 0): skip this many entries from the start of the filtered list
118
+ - limit (number, default 3, hard-clamped to 5): how many summaries to return
119
+ - sessionId (string, optional): filter by session/affinity id
120
+ - model (string, optional): filter by model name
121
+
122
+ Returns: array of "thick summary" objects, each containing:
123
+ - id, timestamp, provider, model, apiFormat, method, path, status, isStreaming,
124
+ hasError, latencyMs, tokens { input, output, cacheCreate, cacheRead },
125
+ sessionId, clientPid,
126
+ - lastUserMessagePreview (string|null, ≤500 chars) — first text block of the last user message, parsed via the format-specific schema (NOT a raw body slice)
127
+ - responsePreview (string|null, ≤500 chars) — first text block of the assistant response
128
+ - hasChunks, hasRawRequestBody (booleans)
129
+
130
+ Either preview field is null when the body is unknown format, unparseable, or the relevant content is non-text (e.g., image-only).`;
131
+
132
+ const PROVIDER_WRITE_WARNING =
133
+ "⚠ This tool mutates provider configuration. Confirm with the user before invoking.";
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Tool registration (thin wiring of impls to the SDK)
137
+ // ---------------------------------------------------------------------------
138
+
139
+ function registerTools(server: McpServer): void {
140
+ // ----- Read tools -----
141
+
142
+ server.registerTool(
143
+ "inspector_list_logs",
144
+ {
145
+ title: "List captured LLM logs",
146
+ description: TOOL_LIST_LOGS_DESC,
147
+ inputSchema: z.object({
148
+ offset: z.number().int().nonnegative().optional().describe("Skip this many entries."),
149
+ limit: z
150
+ .number()
151
+ .int()
152
+ .positive()
153
+ .optional()
154
+ .describe("How many summaries to return. Hard-capped at 5."),
155
+ sessionId: z.string().optional().describe("Filter by session/affinity id."),
156
+ model: z.string().optional().describe("Filter by model name."),
157
+ }),
158
+ },
159
+ (args) => safeCall(() => listLogsImpl(callApi, args)),
160
+ );
161
+
162
+ server.registerTool(
163
+ "inspector_get_log",
164
+ {
165
+ title: "Get a single captured log by id",
166
+ description:
167
+ "Returns the full CapturedLog for the given id, including rawRequestBody and responseText with no truncation. SSE streaming chunks are NOT included — use inspector_get_log_chunks for those. Returns an error if the id does not exist.",
168
+ inputSchema: z.object({
169
+ id: z.number().int().positive().describe("The log id."),
170
+ }),
171
+ },
172
+ ({ id }) => safeCall(() => getLogImpl(callApi, id)),
173
+ );
174
+
175
+ server.registerTool(
176
+ "inspector_get_log_chunks",
177
+ {
178
+ title: "Get SSE streaming chunks for a captured log",
179
+ description:
180
+ "Returns the SSE chunks array for a streaming log, in the order they were received. Returns an error if the log has no chunks (i.e. was non-streaming or the log id is unknown).",
181
+ inputSchema: z.object({
182
+ id: z.number().int().positive().describe("The log id."),
183
+ }),
184
+ },
185
+ ({ id }) => safeCall(() => getLogChunksImpl(callApi, id)),
186
+ );
187
+
188
+ server.registerTool(
189
+ "inspector_list_sessions",
190
+ {
191
+ title: "List known session ids",
192
+ description:
193
+ "Returns the array of session ids that have been observed in captured logs. Useful for discovering what sessionId values to pass to inspector_list_logs.",
194
+ inputSchema: z.object({}),
195
+ },
196
+ () => safeCall(() => listSessionsImpl(callApi)),
197
+ );
198
+
199
+ server.registerTool(
200
+ "inspector_list_models",
201
+ {
202
+ title: "List distinct model names seen in captured logs",
203
+ description: "Returns the array of distinct model names observed across all captured logs.",
204
+ inputSchema: z.object({}),
205
+ },
206
+ () => safeCall(() => listModelsImpl(callApi)),
207
+ );
208
+
209
+ server.registerTool(
210
+ "inspector_list_providers",
211
+ {
212
+ title: "List configured LLM providers",
213
+ description:
214
+ "Returns the full ProviderConfig array, including apiKey in PLAINTEXT. MCP is localhost-only — any process that can call /api/mcp can also read <dataDir>/providers.json directly, so the apiKey is not redacted. Do not expose this MCP server to non-trusted local processes.",
215
+ inputSchema: z.object({}),
216
+ },
217
+ () => safeCall(() => listProvidersImpl(callApi)),
218
+ );
219
+
220
+ // ----- Action tools -----
221
+
222
+ server.registerTool(
223
+ "inspector_get_provider",
224
+ {
225
+ title: "Get a single provider by id",
226
+ description:
227
+ "Returns the full ProviderConfig for the given id, including apiKey in PLAINTEXT (same posture as inspector_list_providers).",
228
+ inputSchema: z.object({
229
+ id: z.string().describe("The provider id."),
230
+ }),
231
+ },
232
+ ({ id }) => safeCall(() => getProviderImpl(callApi, id)),
233
+ );
234
+
235
+ server.registerTool(
236
+ "inspector_replay_log",
237
+ {
238
+ title: "Replay a captured log against its provider",
239
+ description:
240
+ "Re-sends the captured request body to the upstream LLM and returns the response summary: success flag, status, responseText, input/output token counts, elapsedMs, and whether the response was streaming. Useful for re-running a request after a fix or a transient failure. Returns an error if the log id is unknown or the upstream call fails.",
241
+ inputSchema: z.object({
242
+ id: z.number().int().positive().describe("The log id to replay."),
243
+ }),
244
+ },
245
+ (args) => safeCall(() => replayLogImpl(callApi, args)),
246
+ );
247
+
248
+ // ----- Provider write tools -----
249
+
250
+ server.registerTool(
251
+ "inspector_add_provider",
252
+ {
253
+ title: "Add a new LLM provider",
254
+ description: `${PROVIDER_WRITE_WARNING}\n\nPersists a new provider to <dataDir>/providers.json. Required fields: name, apiKey, format (anthropic|openai), model. Optional: baseUrl, authHeader (default: bearer), apiDocsUrl.`,
255
+ inputSchema: z.object({
256
+ name: z.string().min(1),
257
+ apiKey: z.string().min(1),
258
+ format: z.enum(["anthropic", "openai"]),
259
+ model: z.string().min(1),
260
+ anthropicBaseUrl: z.string().optional(),
261
+ openaiBaseUrl: z.string().optional(),
262
+ authHeader: z.enum(["bearer", "x-api-key"]).optional(),
263
+ apiDocsUrl: z.string().optional(),
264
+ }),
265
+ },
266
+ (provider) => safeCall(() => addProviderImpl(callApi, provider)),
267
+ );
268
+
269
+ server.registerTool(
270
+ "inspector_update_provider",
271
+ {
272
+ title: "Update an existing provider",
273
+ description: `${PROVIDER_WRITE_WARNING} Updating with nonsense values effectively soft-deletes a provider. Confirm with the user before invoking.
274
+
275
+ PATCH-style update: only the fields you supply are changed. Returns the updated ProviderConfig.`,
276
+ inputSchema: z.object({
277
+ id: z.string().describe("The provider id to update."),
278
+ name: z.string().min(1).optional(),
279
+ apiKey: z.string().min(1).optional(),
280
+ format: z.enum(["anthropic", "openai"]).optional(),
281
+ model: z.string().min(1).optional(),
282
+ baseUrl: z.string().min(1).optional(),
283
+ authHeader: z.enum(["bearer", "x-api-key"]).optional(),
284
+ anthropicBaseUrl: z.string().optional(),
285
+ openaiBaseUrl: z.string().optional(),
286
+ apiDocsUrl: z.string().optional(),
287
+ }),
288
+ },
289
+ (input) => safeCall(() => updateProviderImpl(callApi, input)),
290
+ );
291
+
292
+ server.registerTool(
293
+ "inspector_test_provider",
294
+ {
295
+ title: "Test a provider's connectivity",
296
+ description:
297
+ "Runs the same connectivity test the UI's 'Test' button does, against both Anthropic and OpenAI endpoints if configured. Returns the per-endpoint success/failure result. Returns an error if the provider id is unknown.",
298
+ inputSchema: z.object({
299
+ id: z.string().describe("The provider id to test."),
300
+ }),
301
+ },
302
+ ({ id }) => safeCall(() => testProviderImpl(callApi, id)),
303
+ );
304
+ }
305
+
306
+ // Surface the tool catalog for tests that assert on the 11-tool name set.
307
+ export const TOOL_NAMES = [
308
+ "inspector_list_logs",
309
+ "inspector_get_log",
310
+ "inspector_get_log_chunks",
311
+ "inspector_list_sessions",
312
+ "inspector_list_models",
313
+ "inspector_list_providers",
314
+ "inspector_get_provider",
315
+ "inspector_replay_log",
316
+ "inspector_add_provider",
317
+ "inspector_update_provider",
318
+ "inspector_test_provider",
319
+ ] as const;
320
+ export type ToolName = (typeof TOOL_NAMES)[number];