spark-sense-ai
spark-sense-ai
一个 MCP(Model Context Protocol)服务器,为 AI 代理(Claude Desktop、Claude Code、Devin 或任何兼容 MCP 的客户端)提供两项用于处理 Apache Spark 作业的能力:
🔴
diagnose_spark_failure— 当 Spark 作业失败时,获取根本原因和具体修复方案,并基于实际错误日志和出问题的特定代码。🟢
optimize_spark_performance— 当 Spark 作业成功但运行缓慢或成本高昂时,获取有针对性的、基于证据的调优建议。
由一位拥有 12 年以上 Apache Spark 实战经验的数据工程师构建,旨在将同样的调试直觉——“这个错误到底涉及哪个文件,以及为什么”——带入 AI 辅助的工作流程中。
为什么存在
Spark 故障通常仅凭日志就能诊断——但要阅读一份 200 行的堆栈跟踪,在一个包含多个作业的大型代码库中将其对应到正确的文件,并判断它到底是十几种可能原因中的哪一种,确实需要真正的 Spark 经验。这个工具自动化了第一遍排查:它找出相关代码(而不是整个代码库),连同日志一起交给 LLM,并返回一份你可以验证并据此行动的结构化诊断。
Related MCP server: Spark MCP Optimizer
不同之处
设计选择 | 重要性 |
来源无关 — EMR(集群 + 步骤 ID)或本地文件夹 | 无论你的作业运行在 AWS 还是本地/自建环境中都适用 |
提供商无关 — Bedrock、Anthropic、OpenAI,或 none | 没有供应商锁定; |
智能文件选择 | 大型项目运行许多作业——此工具解析错误日志的堆栈跟踪(Python 和 Scala/Java,包括混合 PySpark 跟踪),只提取故障涉及的特定文件(最多 10 个),而不是将整个代码库倾倒进提示中 |
绝不捆绑凭据 | 每个用户都使用自己的 AWS 和/或 LLM 凭据。这里不会在用户之间共享计费或访问权限 |
示例输出
给定此 Scala 示例错误日志及其匹配的项目文件,diagnose_spark_failure(在配置了 provider 的情况下)返回:
ROOT CAUSE:
CustomerHelper.validate() calls .trim() on the "email" field without
checking for null first. Records with a missing email cause a
NullPointerException, which aborts the job after 4 failed task retries.
EVIDENCE:
- Caused by: java.lang.NullPointerException: Cannot invoke "String.trim()"
because "email" is null
- at com.company.jobs.CustomerHelper$.validate(CustomerHelper.scala:22)
- Source shows: email.trim().nonEmpty with no null check beforehand
SUGGESTED FIX:
def validate(row: Row): Boolean = {
val email = Option(row.getAs[String]("email"))
email.exists(_.trim.nonEmpty)
}
CONFIDENCE: High请注意,此工具自动提取了 CustomerHelper.scala(堆栈跟踪中 Caused by 实际指向的文件),而不是整个项目,甚至不是顶层入口文件 CustomerOrderJoin.scala——因为堆栈跟踪解析器解析出了最深的相关帧。
安装
pip install spark-sense-ai只安装你实际会用到的额外依赖:
pip install spark-sense-ai[aws] # for EMR source or Bedrock provider
pip install spark-sense-ai[anthropic] # for provider="anthropic"
pip install spark-sense-ai[openai] # for provider="openai"
pip install spark-sense-ai[all] # everythingprovider="none" 配合 source_type="local" 时完全不需要额外依赖——只需基础的 mcp 依赖。
四种使用方式
# | 日志/代码来源 | LLM 提供商 | 所需额外依赖 | 是否需要 AWS 凭据? |
1 | EMR 集群 + 步骤 | Bedrock |
| 是 — 用于获取和诊断 |
2 | EMR 集群 + 步骤 | Anthropic / OpenAI |
| 是 — 仅用于获取 |
3 | 本地文件夹 | None(代理自行推理,例如在 Devin 中) | none | 否 |
4 | 本地文件夹 | Anthropic / OpenAI |
| 否 |
需要时,AWS 凭据会自动从你现有的配置中获取(aws configure、附加的 IAM 角色或标准的 AWS_* 环境变量)——绝不会作为工具参数传递。
设置
Claude Desktop
编辑 claude_desktop_config.json:
{
"mcpServers": {
"sparksense": {
"command": "sparksense-mcp",
"env": {
"SPARKSENSE_AWS_REGION": "ap-south-1"
}
}
}
}Claude Code
claude mcp add sparksense -- sparksense-mcpDevin
有关你的 Devin 代理模式(Cascade 和 Devin Local 使用的配置位置略有不同)的当前配置方法,请参阅 Devin 的 MCP 文档。按照与上述相同的方式将其指向 sparksense-mcp 命令。
使用示例
“我的 Spark 作业失败了——EMR 集群 j-ABC123,步骤 s-XYZ789。使用 sparksense 通过 Bedrock 进行诊断。”
“我的本地作业日志在
./logs/error.log,代码在./src——请诊断这个故障。”
“我知道是
jobs/customer_order_join.py失败了——使用 sparksense 并以它作为入口点。”
“使用 sparksense 获取
./logs/job.log的日志——我自己来审查。” (provider="none"— 工具只负责获取;推理由调用方代理完成)
“我的作业成功了,但花了 40 分钟。使用 sparksense 检查执行统计信息,寻找优化机会。”
工具参考
diagnose_spark_failure
参数 | 是否必填 | 说明 |
| 是 |
|
| 如果 | |
| 如果 | |
| 否 | 源代码的 S3 URI |
| 如果 | 文件或文件夹 |
| 否 | 本地源代码文件夹 |
| 否 | 直接使用的特定文件名/相对路径,跳过自动提取——当你已经知道哪个作业失败时最适用 |
| 否(默认 |
|
| 否 | 用于 anthropic/openai;否则读取 |
optimize_spark_performance
参数与上述相同,另加:
参数 | 是否必填 | 说明 |
| 否 | Executor 内存、核心数、shuffle 分区等。 |
文件选择逻辑(两个工具均适用)
1. job_entry_point given?
→ use ONLY that file. No auto-extraction.
2. Else, parse the error log for:
→ Python: File "<path>", line <N>
→ Scala/Java: at <package>.<Class>.<method>(<Filename>:<N>)
(handles mixed PySpark traces — Python frames bottoming into JVM
frames — by scanning for both patterns in the same log)
→ filters out framework/library internals (site-packages, pyspark,
org.apache.spark, scala.*, java.*, etc.)
→ fetches up to 10 matched files
3. Else, fallback: broad scan of the project folder, capped at 10 files环境变量
变量 | 默认值 | 用途 |
|
| EMR/S3/Bedrock 调用的区域 |
|
| 要使用的 Bedrock 模型 |
| — | 当 |
| — | 当 |
测试
git clone https://github.com/YOUR_GITHUB_USERNAME/spark-sense-ai.git
cd spark-sense-ai
pip install -e ".[all]"
# Local source + Anthropic provider, includes Python and Scala samples
export ANTHROPIC_API_KEY="sk-ant-..."
python tests/test_local_anthropic.py
# EMR source + Bedrock provider (needs a real EMR cluster/step)
aws configure
python tests/test_emr_bedrock.py --cluster-id j-XXXXXXX --step-id s-XXXXXXX两个脚本在发起任何计费 LLM 调用之前,都会先运行一次免费、不调用 API 的健全性检查(provider="none")。
路线图
在 EMR/Glue 作业完成时通过 Lambda/EventBridge 自动触发
将 Databricks 作为第三种
source_type结构化 Spark History Server API 集成
基于分区级统计信息的倾斜检测
许可证
MIT — 参见 LICENSE。
Available Tools
2 toolsdiagnose_spark_failureARead-onlyIdempotent
Diagnose why an Apache Spark job failed.
Args: source_type: Where to fetch the log/code from - "emr" or "local". emr_cluster_id: EMR cluster ID (required if source_type="emr"). emr_step_id: EMR step ID (required if source_type="emr"). s3_project_location: Optional S3 URI to the job's source code (used only if source_type="emr"). local_log_path: Path to a local log file or folder (required if source_type="local"). local_project_path: Optional local folder containing the job's source code (used only if source_type="local"). job_entry_point: Optional filename/relative path of the specific job file that ran (e.g. "jobs/customer_order_join.py"). If given, ONLY this file is used as code context - skips auto-extraction entirely. Best used when the caller already knows which job failed. If omitted, the tool automatically parses the error log's stack trace (Python and/or Scala/Java patterns - handles mixed PySpark traces) to find the relevant file(s) in the project, up to 10 files, filtering out framework/library internals. This keeps large, multi-job projects from having their entire codebase sent to the model - only the code actually implicated by the failure is included. provider: Which LLM does the reasoning - "bedrock", "anthropic", "openai", or "none" (default). "none" returns the fetched log/code as-is, for the CALLING AGENT to diagnose itself - no LLM call is made by this tool in that case. api_key: API key for "anthropic" or "openai" providers. If omitted, reads from the ANTHROPIC_API_KEY / OPENAI_API_KEY environment variable. Not used for "bedrock" (uses locally configured AWS credentials) or "none".
Returns: A structured diagnosis (root cause, evidence, fix, confidence) if a provider is set, or the raw fetched log/code for the calling agent to analyze if provider="none".
| Name | Required | Description | Default |
|---|---|---|---|
| api_key | No | ||
| provider | No | none | |
| emr_step_id | No | ||
| source_type | Yes | ||
| emr_cluster_id | No | ||
| local_log_path | No | ||
| job_entry_point | No | ||
| local_project_path | No | ||
| s3_project_location | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The annotations (readOnlyHint=true, idempotentHint=true, destructiveHint=false) are consistent with the description, which implies fetch-and-analyze operations with no side effects. The description adds transparency about the optional LLM call and the 'none' provider returning raw data, which is valuable context beyond the annotations. No contradictions found.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is long but well-structured, with clear sections for parameters and returns. Each piece of information serves a purpose (e.g., explaining conditional requirements, provider options, and the detection algorithm). While slightly verbose, the complexity of the tool justifies the length. It is not padded with irrelevant details.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's complexity (multiple providers, conditional parameters, return type variations), the description is exceptionally complete. It covers return values for both provider and 'none' cases, explains the code extraction logic, and provides examples. No missing information that an agent would need to call this tool correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Despite the schema having zero description coverage, the tool description explains every parameter in detail, including conditional requirements (e.g., 'required if source_type="emr"'), defaults, environment variable fallbacks, and the behavior of job_entry_point. It even includes an example and explains the auto-extraction logic. This fully compensates for the schema's lack of per-parameter descriptions.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and object: 'Diagnose why an Apache Spark job failed.' This clearly distinguishes the tool from the sibling 'optimize_spark_performance' by focusing on failure diagnosis rather than performance tuning. The purpose is unambiguous and immediately actionable.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides thorough guidance on when to use the tool and how to configure it for different scenarios (source_type, provider, conditional parameters). It explains fallback behavior (env vars, 'none' provider) and the logic for auto-extraction. However, it does not explicitly contrast with the sibling tool, relying instead on the name difference. This is a minor gap, keeping it from a perfect score.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
optimize_spark_performanceARead-onlyIdempotent
Analyze a successful Spark job's execution log/stats and suggest performance optimizations.
Args: source_type: Where to fetch the log/code from - "emr" or "local". emr_cluster_id: EMR cluster ID (required if source_type="emr"). emr_step_id: EMR step ID (required if source_type="emr"). s3_project_location: Optional S3 URI to the job's source code. local_log_path: Path to a local log file/folder (required if source_type="local"). local_project_path: Optional local folder with source code. job_entry_point: Optional filename/relative path of the specific job file to focus on. If given, ONLY this file is used - skips auto-extraction. If omitted, the tool parses the execution log for stack-trace-like file references (Python and/or Scala/Java) to narrow down which of the project's files are relevant, up to 10 files. Useful for large, multi-job repositories. current_spark_config: Optional text describing the current Spark configuration (executor memory, cores, shuffle partitions, etc.), to ground recommendations in what's configurable. provider: "bedrock", "anthropic", "openai", or "none" (default - returns fetched content for the calling agent to analyze). api_key: API key for "anthropic"/"openai". Reads from env var if omitted. Unused for "bedrock" or "none".
Returns: A structured analysis (observations, recommendations, estimated impact) if a provider is set, or the raw fetched content for the calling agent to analyze if provider="none".
| Name | Required | Description | Default |
|---|---|---|---|
| api_key | No | ||
| provider | No | none | |
| emr_step_id | No | ||
| source_type | Yes | ||
| emr_cluster_id | No | ||
| local_log_path | No | ||
| job_entry_point | No | ||
| local_project_path | No | ||
| s3_project_location | No | ||
| current_spark_config | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare readOnly, idempotent, openWorld, and non-destructive. The description adds clarity by explaining that with provider='none' it returns raw fetched content, and otherwise returns a structured analysis. There is no contradiction with annotations, and the description provides useful context on what the tool does without describing side effects.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-organized with a main purpose statement, an Args section listing each parameter with explanations, and a Returns section. It is thorough but not redundant, providing all necessary information without unnecessary verbosity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description explains the full behavior of the tool: what it analyzes, how it uses the parameters, and what it returns under different provider settings. Although an explicit output schema is not shown, the description clearly describes the two possible return types (structured analysis or raw content), making it complete for the agent to use correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has 0% description coverage for its 10 parameters, but the tool description compensates fully by explaining each parameter: source_type, emr_cluster_id, emr_step_id, s3_project_location, local_log_path, local_project_path, job_entry_point, current_spark_config, provider, and api_key. It clarifies requirements (e.g., 'required if source_type=...') and optionality, making the semantics complete.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: analyze successful Spark job logs/stats and suggest performance optimizations. It names the specific action (analyze, suggest) and resource (execution log/stats), and differentiates from the sibling tool by emphasizing 'successful' jobs, implying a contrast with failure diagnosis.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies when to use the tool (for successful jobs to get optimization suggestions) by contrasting with 'successful' and the sibling 'diagnose_spark_failure'. It also explains provider options (including 'none' for raw content) and argument dependencies. However, it does not explicitly state 'use this instead of diagnose_spark_failure when the job succeeded,' leaving the distinction implicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
2 tool updates
v0.1.3- First observed
diagnose_spark_failure - First observed
optimize_spark_performance
TDQS
Scored across 2 tools
The two tools have clearly distinct purposes: one diagnoses failures and the other optimizes performance. Despite sharing similar arguments, their actions and return types are unambiguously different.
Both tool names follow the consistent verb_noun pattern (diagnose_spark_failure, optimize_spark_performance), which is clear and predictable.
With only two tools, the server is slightly below the typical well-scoped range, but it is focused on a narrow domain (Spark job analysis) where these two core operations are appropriate.
The server covers the primary needs of diagnosing failures and optimizing performance. However, there may be gaps such as retrieving job metrics or listing available jobs, though these are not strictly required for the stated purpose.
Maintenance
Related MCP Connectors
MCP server providing access to the Scorecard API to evaluate and optimize LLM systems.
MCP server for building and testing AI agents with multi-model experimentation and insights.
MCP server for AI dialogue using various LLM models via AceDataCloud
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAn MCP server for intelligent log analysis providing semantic search, error pattern clustering, and smart error detection. It enables users to process, vectorize, and query local logs to efficiently identify issues and generate AI-powered summaries.MIT
- FlicenseNot gradedqualityDmaintenanceAn MCP server that optimizes Apache Spark code using Claude AI, providing intelligent code optimization suggestions and performance analysis.29-
- AlicenseAqualityDmaintenanceMCP server for log file analysis. Gives LLMs the ability to efficiently analyze large log files without loading them into context.7101MIT
- AlicenseAqualityDmaintenanceMCP server that reads Spark profiler files to give accurate Minecraft server tuning advice, parsing binary protobuf directly and diagnosing TPS, MSPT, GC, heap, and call-tree issues.1415 npm5MIT