
使用 MLflow TypeScript SDK 追踪 Claude Code 会话与 Claude Agent SDK 运行【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow本文围绕 MLflow 仓库中的 mlflow/claude-code 集成包说明文档系统讲解如何将 Claude Code CLI 会话与 Claude Agent SDK 运行接入 MLflow Tracing涵盖安装、环境配置、Stop-hook 插件追踪、createTracedQuery包装器使用以及底层 span 树结构、配置优先级与 Token 用量记录机制。读者读完后可以直接在自己的 TypeScript/Node.js 项目中把 Claude Code 的每一次交互变成可检索、可审计的 MLflow trace。集成包概览mlflow/claude-code是 MLflow TypeScript SDK 生态中的一个独立 npm 包位于 libs/typescript/integrations/claude-code用于把两类 Claude 执行面接入 MLflow Tracing包名用途mlflow/claude-code追踪 Claude Code CLI 会话通过 Stop-hook与 Claude Agent SDK 查询从该包的 package.json 可以看到几个关键事实运行时依赖仅有mlflow/core^0.4.0span 的创建、上报与内存管理全部由核心 SDK 提供anthropic-ai/claude-agent-sdk^0.2.0是可选 peer dependency只用 CLI 追踪时无需安装只有用 Agent SDK 追踪时才需要包内带bin入口mlflow-claude-code提供命令行配置工具要求 Node.js 18且为 ESM 模块type: module。核心架构同一棵 span 树的两种构建路径在深入用法之前先理解本集成的架构。根据 liveTracing.ts 顶部注释两条追踪路径最终产出同一棵 span 树CLI 路径离线 transcriptClaude Code 每次会话结束触发 Stop-hookstop.cjs读取会话 JSONL transcript由processTranscripttracing.ts批量构建 span 并上报SDK 路径实时流createTracedQuery包装 Agent SDK 的query()在消息流抵达时通过LiveTracingContext增量构建 span长会话可实时看到进度即使进程中途崩溃已产生的部分 span 也能保留。两条路径共享 _internal.ts 中的内容提取、Token 归一化与 JSON 安全序列化工具保证两种方式产出的 trace 形态完全一致。安装npm install mlflow/claude-code如果还要追踪 Claude Agent SDK额外安装npm install anthropic-ai/claude-agent-sdk安装后包会自动注册mlflow-claude-codeCLI 命令来自bin字段入口为 cli.ts。前置准备接入 MLflow Tracking Server开始追踪前需要一个可访问的 MLflow Tracking Server并通过环境变量或后续介绍的 settings 文件指向它export MLFLOW_TRACKING_URIhttp://localhost:5000 export MLFLOW_EXPERIMENT_IDexperiment-idMLFLOW_TRACKING_URI除 http(s) URL 外也支持databricks或databricks://profile形式见 config.ts 中isValidTrackingUri的校验逻辑。Experiment 可以用 ID 指定也可以用名称指定MLFLOW_EXPERIMENT_NAME两者至少配置其一配置resolveExperiment会在名称存在时复用、不存在时自动创建。追踪 Claude Code CLI 会话Stop-hookCLI 追踪无需改动你的工作流。包内捆绑了 Stop-hook 插件配置hooks/hooks.json{ hooks: { Stop: [ { hooks: [ { type: command, command: node \${CLAUDE_PLUGIN_ROOT}/bundle/stop.cjs\, timeout: 120 } ] } ] } }Stop-hook 会在每次 Claude Code 会话结束时触发执行stop.cjs读取本次会话的 JSONL transcript解析出每一轮 assistant 回复、tool_use 与 tool_result、子代理调用等信息构建 trace 后异步上报。该插件只需一次性安装之后每次 CLI 会话都会被自动追踪。用 CLI 命令完成一次性配置包提供的mlflow-claude-code命令支持setup与status两个子命令用法定义见 cli.tsUsage: mlflow-claude-code command [options] Commands: setup 配置 MLflow tracing写入 Claude Code settings 文件 status 查看当前 MLflow tracing 配置setup的选项包括选项说明-p, --project写入当前仓库的./.claude/settings.json仅本项目生效-u, --user写入用户目录~/.claude/settings.json对所有仓库生效--tracking-uri uriMLflow tracking URIdatabricks、databricks://profile或绝对 http(s) URL--experiment-id id使用已存在的 experiment--experiment-name n按名称创建或复用 experiment--trace-location loc可选Databricks Unity Catalog trace 位置格式catalog.schema.table_prefix--workspace ws可选Databricks workspace 标识必填约束来自 setup.ts 的校验逻辑--project与--user二选一--tracking-uri必填且格式合法--experiment-id与--experiment-name二选一--trace-location若非空必须是三段点分格式。所有值都必须由用户显式给出工具不会静默选取默认值。示例# 项目级配置使用本地 tracking server 按名称创建 experiment $ mlflow-claude-code setup --project --tracking-uri http://localhost:5000 \ --experiment-name my-exp # 用户级配置使用 Databricks tracking 已存在 experiment $ mlflow-claude-code setup --user --tracking-uri databricks --experiment-id 12345 # Databricks 场景下同时指定 UC trace location $ mlflow-claude-code setup --user --tracking-uri databricks \ --experiment-id 12345 --trace-location my_catalog.my_schema.my_prefixsetup执行时会解析 experiment必要时调用createExperiment创建并把追踪配置写入对应 settings 文件同时输出Created/Updated settings 路径与最终生效配置摘要。status则直接打印当前生效的配置来源与各项参数未启用时还会提示运行setup。追踪 Claude Agent SDK 运行createTracedQuery当你在自己的 Node.js 程序里用 Claude Agent SDK 驱动 agent 时用createTracedQuery包装 SDK 的query函数即可示例来自 READMEimport { query } from anthropic-ai/claude-agent-sdk; import { createTracedQuery } from mlflow/claude-code; import * as mlflow from mlflow/core; mlflow.init({ trackingUri: http://localhost:5000, experimentId: experiment-id, }); const tracedQuery createTracedQuery(query); const result tracedQuery({ prompt: List the files in this directory, options: { permissionMode: bypassPermissions, }, }); for await (const message of result) { if (message.type result) { console.log(Result:, message.result); } }从 tracedClaudeAgent.ts 的源码可以看到该包装器的几个关键实现细节签名透明包装后的函数与原query签名和返回类型完全一致追踪对调用方完全无感返回的异步迭代器通过Proxy保留next/return/throw/interrupt等原生行为强制forwardSubagentText: true包装器会把该选项注入 SDK使子代理的内部消息流经父消息流透传仅本地、无网络开销否则 SDK 只会发出子代理的 tool_use/tool_result 心跳导致 trace 中丢失子代理的 LLM 与嵌套工具 span流式 prompt 捕获若prompt传入AsyncIterable包装器会包一层只读探针逐条提取用户文本追加到根 span 的inputs.prompt且不消费原始序列——SDK 拿到的仍是原迭代器健壮收尾finalize()与finalizeError()幂等以ended标志守卫即使消费者提前break跳出循环或流抛错finally中也会确保 trace 被关闭并 flush调用interrupt()时同样会以interrupted状态收尾 trace。配置解析环境变量与 settings 文件的优先级本集成支持环境变量与 Claude Code settings 文件两种配置来源config.ts 中的getEffectiveTracingConfig定义了明确的解析顺序环境变量source: environment优先级最高其次项目级./.claude/settings.jsonsource: project再次用户级~/.claude/settings.jsonsource: user。支持的全部环境变量如下环境变量含义MLFLOW_CLAUDE_TRACING_ENABLED是否启用 Claude 追踪真值识别true/1/yes大小写不敏感MLFLOW_TRACKING_URITracking Server 地址MLFLOW_EXPERIMENT_IDExperiment IDMLFLOW_EXPERIMENT_NAMEExperiment 名称与 ID 二选一MLFLOW_ENABLE_ASYNC_TRACE_LOGGING初始化时自动置为true启用异步 trace 上报MLFLOW_TRACE_LOCATION可选Databricks Unity Catalog trace 位置catalog.schema.table_prefix三段式MLFLOW_WORKSPACE可选Databricks workspace其中MLFLOW_TRACE_LOCATION会改变 trace 的路由方式配置后 trace 写入 UC table-prefix 目标V4 trace ID否则走 V3 实验experiment-backed路径。注意该 UC 位置必须已在 workspace 中预置SDK 不会自动创建格式解析失败非三段或含空段会在初始化时打印明确报错并跳过追踪ensureInitialized的校验逻辑。ensureInitialized还会在 experiment ID 已知时走快速路径跳过网络调用仅用 tracking URI、experiment ID 与 trace location 组成初始化键做幂等判断避免重复初始化。深入 span 树数据结构与元数据无论走 CLI 还是 SDK 路径最终生成的 trace 都是同一棵 span 树结构定义见 liveTracing.ts 顶部注释claude_code_conversation (AGENT) ← 根 span ├── llm (LLM) ← 每轮含文本/思考内容的 assistant 回复 ├── tool_name (TOOL) ← 每个 tool_use 块 │ └── subagent_type (AGENT) ← Task/Agent 工具调起的子代理 │ ├── llm │ └── tool_name └── ...几个值得注意的细节子代理归因SDK 路径下子代理归属由 SDKMessage 的parent_tool_use_id驱动SUBAGENT_TOOL_NAMES new Set([Task, Agent])同时覆盖 SDK 0.2.x 的新命名Agent与 CLI transcript 中遗留的Task。子代理 span 在 Task/Agent tool_use 出现时惰性创建其内部消息通过parent_tool_use_id路由到对应子 span 之下工具结果与错误tool_result 到达时关闭对应 TOOL span 并写入result输出is_error为真时以SpanStatusCode.ERROR标记并携带错误文本Token 用量每个 LLM span 记录usage见 _internal.ts 的buildUsageDict包括input_tokens、output_tokens、total_tokens input output以及可选的cache_read_input_tokens、cache_creation_input_tokens便于消费端计算缓存命中率会话结束时result消息的聚合用量会写入根 spanTrace 元数据根 span 关闭前会写入会话级元数据包括 session IDTRACE_SESSION、当前用户TRACE_USER、工作目录、权限模式permission_mode与 Claude Code 版本等键名见 _internal.ts 的METADATA_KEY_*常量JSON 安全记录 options 时通过sanitizeForSpan递归剔除函数与循环引用替换为[function]、[circular]占位避免 hooks 回调、canUseTool、MCP server 等含函数字段导致序列化失败或内存膨胀预览截断trace 的requestPreview/responsePreview截取至 1000 字符MAX_PREVIEW_LENGTH保证 UI 展示轻量。CLI 路径的 transcript 解析还具备额外能力识别同一个 assistant 回合被 Claude Code 拆成多个共享message.id的 JSONL 条目并合并处理保证同一回合的并行 tool_use 都能找到结果、解析工具执行错误、以及将子代理的 toolUseResult 归并到对应工具结果中见 tracing.ts 的findToolResults。验证与测试该集成在仓库内带有完整的单元测试tests/覆盖配置解析config.test.ts、setup 校验setup.test.ts、transcript 解析transcript.test.ts、SDK 包装tracedClaudeAgent.test.ts与 span 构建tracing.test.ts。测试夹具fixtures/提供了真实形态的 JSONL transcript 样例包括普通会话、带子代理、带并行子代理、带工具错误与带 token 用量的会话可直接用于理解 transcript 数据形态。在包目录下执行npm test即可运行全部测试。小结mlflow/claude-code提供了一条零侵入接入 MLflow Tracing 的路径CLI 用户安装后配置一次 Stop-hook之后每个 Claude Code 会话自动产生结构化的 agent trace无需改动任何工作流程SDK 开发者用createTracedQuery一行包装即可让程序内的 agent 运行具备完整的 span 树、Token 用量与子代理归因。两种路径共享统一的 span 结构与配置体系环境变量 / settings 文件三级优先级并支持 Databricks UC trace location。相关实现细节可进一步阅读 liveTracing.ts、tracing.ts、config.ts 与 commands/setup.ts。【免费下载链接】mlflowThe open source AI engineering platform for agents, LLMs, and ML models. MLflow enables teams of all sizes to debug, evaluate, monitor, and optimize production-quality AI applications while controlling costs and managing access to models and data.项目地址: https://gitcode.com/GitHub_Trending/ml/mlflow创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考